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

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 「ラピュタの島」の海洋プラごみ生かせ ベンチや補強剤で新たな価値 https://www.itmedia.co.jp/business/articles/2202/10/news178.html itmedia 2022-02-10 20:49:00
IT ITmedia 総合記事一覧 [ITmedia Mobile] 寺尾社長、BALMUDA Phoneは「結果オーライになると信じている」と自信 https://www.itmedia.co.jp/mobile/articles/2202/10/news177.html balmudaphone 2022-02-10 20:46:00
IT ITmedia 総合記事一覧 [ITmedia News] 「BALMUDA Phone」、売上高は28億円超えも端末値下げ 全体の売上高は過去最高に https://www.itmedia.co.jp/news/articles/2202/10/news176.html balmudaphone 2022-02-10 20:30:00
AWS AWSタグが付けられた新着投稿 - Qiita [AWS]今週の問題2週目 https://qiita.com/cakofei/items/abca8243b19d5fdc0df1 一方サーバーAにはパブリックIPが振られており、これを経由することでサーバーBに接続する技術がある。 2022-02-10 20:16:54
技術ブログ Developers.IO Alteryx で使える Outlook 365 ツール https://dev.classmethod.jp/articles/alteryx-outlook365-tool-jp/ alteryx 2022-02-10 11:55:07
技術ブログ Developers.IO How to use the Outlook 365 Tool in Alteryx https://dev.classmethod.jp/articles/alteryx-outlook365-tool-en/ How to use the Outlook Tool in Alteryx Click here for Japanese Introduction With the recent release of Alteryx a new tool was launched to 2022-02-10 11:54:58
技術ブログ Developers.IO การอัปโหลดข้อมูลไปยัง Amazon S3 ด้วย CloudBerry Explorer https://dev.classmethod.jp/articles/uploading-to-amazon-s3-with-cloudberry-explorer/ การอัปโหลดข้อมูลไปยังAmazon S ด้วยCloudBerry Explorerครั้งนี้จะมาแนะนำวิธีการอัปโหลดข้อมูลไปยังAmazon S ด้วยCloudBerry Explorer ต่อจากบทความHow To Static Websi 2022-02-10 11:00:38
海外TECH MakeUseOf Make Windows 11 Faster, Microsoft Defender Surprises, Data Recovery Explained, and Get Amazon Prime for Less https://www.makeuseof.com/improve-windows-11-performance/ Make Windows Faster Microsoft Defender Surprises Data Recovery Explained and Get Amazon Prime for LessLearn how to make Windows faster trust Microsoft Defender and beat the Amazon Prime price rise in this week s podcast 2022-02-10 11:30:12
海外TECH MakeUseOf 6 Best Wellness Challenge Ideas and Apps to Try Now https://www.makeuseof.com/best-wellness-challenge-ideas/ things 2022-02-10 11:30:12
海外TECH MakeUseOf Samsung Galaxy S22 Ultra: The Top 10 Features https://www.makeuseof.com/galaxy-s22-ultra-best-features/ galaxy 2022-02-10 11:15:12
海外TECH DEV Community How To Create Data Driven Framework In Selenium https://dev.to/himanshusheth004/how-to-create-data-driven-framework-in-selenium-2li5 How To Create Data Driven Framework In SeleniumThe efficiency of Selenium automation testing largely depends on how well the functionality under test is behaving against different input combinations For instance an email provider would have to verify different screens like login sign up etc by supplying different input values to the scenarios However the effort involved in maintaining the test code rises significantly with new functionalities in the web product SourceThe question that needs to be asked is “Should changes in the business rules lead to new test scenarios or can existing test scenarios be extended to suit the needs of the new rules This is where Data Driven Framework in Selenium can come in super handy as it enables the QA engineer to test different scenarios using different data sets The beauty of the Data Driven Testing Framework in Selenium lies in the fact that there is a clear bifurcation of the test code and test data The test data is kept in an external data feed like MS Excel Sheets CSV Files and more In this Selenium Java tutorial we deep dive into the nuances of data driven tests in Selenium and how the popular Data Driven Framework in Selenium can be used for realizing data driven testing as well as cross browser testing The demonstration of the Data Driven Framework in Selenium WebDriver is performed using the TestNG framework and Apache POI Poor Obfuscation Implementation API in Selenium Introduction to Data Driven Testing in Selenium WebDriverAs new functionalities or features are added to a web product test cases or test suites must be implemented to test the new set of features Before adding a new test case you should have relevant answers to the following questions Do we really need to develop a new test case for verifying the corresponding functionality functionality Is it feasible to modify an existing test case to suit the testing needs of the feature under test Is it possible to change the existing test implementation so that the said product features can be tested against different input combinations or data sets Is it required to add new test implementation when there are minimal changes in the business rules Is there a more optimal way to separate the test data from the test implementation The answers to the questions mentioned above lie with Data Driven Testing in Selenium WebDriver What is Data Driven Testing Data Driven Testing is a methodology where a sequence of steps in the test script is run repeatedly against different input values fetched from the corresponding data source It is one of the widely used automation testing best practices for verifying the behavior and efficiency of tests when handling various types of input values Here are the popular external data feed or data sources in data driven testing MS Excel Sheets xls xlsx CSV Files csv XML Files xml MS Access Tables mdb The data feed or data source not only contains the input values used for Selenium automation testing but can also be used for storing the expected test result and the output test result This can be useful in comparing the test execution result and storing the same for referring to later stages Advantages of Data Driven TestingSome of the significant benefits of Data Driven Testing are Data Driven Testing accelerates the process of efficiently performing regression testing on the features of a web product Regression tests can be used to verify end to end workflow logic across using different values stored in external data sources Data Driven Tests are easier to maintain since the test logic is logically separated from the data used for testing the logic Hence minor business rules changes might only create new scenarios and additional data sets against which the tests have been verified Data Driven Tests are useful for record keeping since you can store the test execution status along with the input values against which the test automation was run Data Driven Testing is a preferred choice for iteratively testing the application or web product against a large data set The data set can contain input values covering positive and negative test scenarios thereby helping achieve improved test efficiency and coverage Now that we have covered the basics of data driven testing let s have a look at the Data Driven Framework in Selenium WebDriver and how data driven testing in Selenium WebDriver can be realized using Apache POI Data Driven Framework in Selenium WebDriverData Driven Testing Framework in Selenium is one of the widely preferred automation testing frameworks that let you realize iterative development and testing In line with data driven testing principles Data Driven Framework is used for driving test cases and or test suites from external data feeds like Excel Sheets xls xlsx CSV files csv etc The test script connects to the external data source or feed to get the required operations on the test data Using the Data Driven Framework in Selenium WebDriver the test data set is separated from the test implementation reducing the overall effort involved in maintaining and updating the test code Minimal changes in the business rules will require changes in the test data set with without minimal or no changes in the test code Selenium WebDriver lets you perform automated cross browser testing on web applications however it does not have the support to perform create read update and delete CRUD operations on external data feeds like Excel sheets CSV files and more This is where third party APIs like Apache POI has to be used since it lets you access and performs relevant operations on external data sources What is Apache POIApache POI Poor Obfuscation Implementation is an open source library developed and distributed by the Apache Software Foundation It is the most commonly used API for realizing data driven tests in Selenium The API provided by the library files in Apache POI lets the user manipulate Microsoft Documents Excel files xls xlsx Doc files doc and more In a nutshell Apache POI is the Java Excel solution that lets you read write modify data from to external data feeds Handling Excel Files using Apache POIThe Apache POI consists of classes and methods that simplify processing MS Excel sheets in Java Therefore it is important to be well versed with the common terminologies used when working with MS Excel Workbook A Workbook in Microsoft Excel is primarily used to create and maintain the Spreadsheet or Sheet It can contain one or more spreadsheets Sheet A Sheet in a workbook is a page made up of Rows and Columns Row A Row in a Sheet runs horizontally and is represented as a collection of Cells Cell A Cell in a Sheet is represented by a Row and Column combination Data entered by the user is stored in a cell For example Cell indicates the data is stored in Row and Column The Apache POI library provides an HSSF implementation for performing operations on MS Excel files in the xls format On the other hand XSSF implementation in Apache POI lets you perform operations on MS Excel Files in the xlsx format Handling xls Files using Apache POIFor reading xls files HSSF implementation is provided by the Apache POI library The methods used for performing operations on the xls files are available in the classes that belong to the org apache poi hssf usermodel package Here are the important classes amp methods in the org apache poi hssf usermodel package that helps in performing CRUD operations on xls files HSSFWorkbook Represents a Workbook in the xls formatHSSFSheet Represents a Sheet in the xls workbookHSSFRow Represents a Row in the xls fileHSSFCell Represents a Cell in the Row of the xls fileUsing Apache POI with Java and TestNG makes it easy to manage the Apache POI Selenium Maven dependency in the pom xml file You could refer to our detailed blog on Maven for Selenium Testing for a quick recap on Maven with Selenium Here is the Maven dependency for using the Apache POI library to access xls files in Java lt dependencies gt lt dependency gt lt groupId gt org apache poi lt groupId gt lt artifactId gt poi lt artifactId gt lt version gt lt version gt lt dependency gt lt dependencies gt Handling xlsx Files using Apache POIFor reading xlsx files XSSF implementation is provided by the Apache POI library and the org apache poi xssf usermodel package contains classes and methods that let you achieve the same Here are the important classes amp methods in the org apache poi xssf usermodel package that helps in performing CRUD operations on xlsx files XSSFWorkbook Represents a Workbook in the xlsx formatXSSFSheet Represents a Sheet in the xlsx workbookXSSFRow Represents a Row in the xlsx fileXSSFCell Represents a Cell in the Row of the xlsx fileHere is the Maven dependency for using the Apache POI library to access xlsx files in Java lt dependencies gt lt dependency gt lt groupId gt org apache poi lt groupId gt lt artifactId gt poi ooxml lt artifactId gt lt version gt lt version gt lt scope gt test lt scope gt lt dependency gt lt dependencies gt Shown below is the Apache POI Selenium Maven dependency that would download the libraries for accessing the xls and xlsx Excel formats lt dependencies gt lt Apache POI Accessing xls format gt lt dependency gt lt groupId gt org apache poi lt groupId gt lt artifactId gt poi lt artifactId gt lt version gt lt version gt lt dependency gt lt Apache POI Accessing xlsx format gt lt dependency gt lt groupId gt org apache poi lt groupId gt lt artifactId gt poi ooxml lt artifactId gt lt version gt lt version gt lt scope gt test lt scope gt lt dependency gt lt dependencies gt The Enum CellType contains the different field types that can be accessed to get the Cell Type i e String Boolean etc Here are the following fields in a Cell that is accessible via the getCellType method CellType NONE Represents a state before the initialization or the lack of a concrete typeCellType NUMERIC Represents numeric data in a CellCellType STRING Represents String in a CellCellType FORMULA Represents Formula result that is applied on the CellCellType BLANK Represents an Empty CellCellType BOOLEAN Represents a Boolean value in a CellCellType ERROR Represents an Error value in a CellAt the time of writing this blog the latest version of Apache POI was It is recommended to look at the methods interfaces classes enums and deprecations in the Apache POI documentation For example the getCellTypeEnum will be removed in Apache POI and the same has been renamed to getCellType It is essential to use the latest or up to date classes and APIs so that the implementation works flawlessly even when we migrate to future versions of Apache POI e g Here is the pictorial view of the classes and interfaces that are widely used when accessing xls and xlsx files using Java and Apache POI Here is the pictorial view of the classes and interfaces that are widely used when accessing xls and xlsx files using Java and Apache POI Data Driven FrameworkNow that we have covered the essential fundamentals of the Data Driven Framework in Selenium WebDriver we take a look at how Apache POI can be used with Maven and TestNG to realize data driven testing in Selenium Excelling with automated testing is a vital and competent skill today and can present you with a viable future TestNG will equip you with the right skill set needed to begin your journey as an automation expert TestNG certification from LambdaTest can help you take your test engineering skills to the next level Here s a short glimpse of the TestNG certification offered by LambdaTest How to create Data Driven Framework in Selenium WebDriver using Apache POIIn this section of this Selenium Java tutorial we look at how to perform read write and update operations on Excel files that are available in the xls and xlsx formats Here are the prerequisites for implementing the Data Driven Framework in Selenium IDE IntelliJ IDEA or Eclipse IDE Framework TestNGMS Excel xls and xlsx files that would contain the data for realizing data driven testingFor demonstration we create a Data Driven Project with Maven with the following structure The following class files are created under the package named DataDrivenFramework test DataDrivenFramework javatest LT DataDrivenFramework javaThe tests demonstrating Data Driven Framework in Selenium WebDriver are run on cloud based online Selenium Grid by LambdaTest To get started with LambdaTest we create a profile on LambdaTest and note the user name amp access key available on the LambdaTest profile page Then the Desired Capabilities for the browser amp OS combination under test is generated using the LambdaTest Capabilities Generator and the respective tests are run on LambdaTest s Selenium Grid Shown below is pom xml that contains the required dependencies and testng xml that contains the test classes to be run lt xml version encoding UTF gt lt project xmlns xmlns xsi xsi schemaLocation gt lt modelVersion gt lt modelVersion gt lt groupId gt org ddf lt groupId gt lt artifactId gt DataDrivenFramework lt artifactId gt lt version gt SNAPSHOT lt version gt lt dependencies gt lt dependency gt lt groupId gt org testng lt groupId gt lt artifactId gt testng lt artifactId gt lt version gt lt version gt lt scope gt test lt scope gt lt dependency gt lt dependency gt lt groupId gt org slfj lt groupId gt lt artifactId gt slfj nop lt artifactId gt lt version gt lt version gt lt scope gt test lt scope gt lt dependency gt lt dependency gt lt groupId gt org seleniumhq selenium lt groupId gt lt artifactId gt selenium java lt artifactId gt lt version gt alpha lt version gt lt dependency gt lt dependency gt lt groupId gt org seleniumhq selenium lt groupId gt lt artifactId gt selenium remote driver lt artifactId gt lt version gt alpha lt version gt lt dependency gt lt dependency gt lt groupId gt org seleniumhq selenium lt groupId gt lt artifactId gt selenium chrome driver lt artifactId gt lt version gt alpha lt version gt lt dependency gt lt dependency gt lt groupId gt junit lt groupId gt lt artifactId gt junit lt artifactId gt lt version gt lt version gt lt scope gt test lt scope gt lt dependency gt lt gt lt dependency gt lt groupId gt org apache poi lt groupId gt lt artifactId gt poi lt artifactId gt lt version gt lt version gt lt dependency gt lt dependency gt lt groupId gt org apache poi lt groupId gt lt artifactId gt poi ooxml lt artifactId gt lt version gt lt version gt lt scope gt test lt scope gt lt dependency gt lt dependencies gt lt build gt lt defaultGoal gt install lt defaultGoal gt lt plugins gt lt plugin gt lt artifactId gt maven compiler plugin lt artifactId gt lt version gt lt version gt lt configuration gt lt source gt lt source gt lt target gt lt target gt lt configuration gt lt plugin gt lt plugin gt lt groupId gt org apache maven plugins lt groupId gt lt artifactId gt maven compiler plugin lt artifactId gt lt configuration gt lt source gt lt source gt lt target gt lt target gt lt configuration gt lt plugin gt lt plugins gt lt build gt lt project gt FileName pom xml lt xml version encoding UTF gt lt DOCTYPE suite SYSTEM gt lt suite name All Test Suite gt lt test verbose preserve order true name DataDrivenFrameWork gt lt classes gt lt class name com DataDrivenFramework test DataDrivenFramework gt lt class gt lt class name com DataDrivenFramework test LT DataDrivenFramework gt lt class gt lt classes gt lt test gt lt suite gt Now let s look at the different ways in which Data Driven Framework in Selenium is used along with Apache POI for running automated browser testing scenarios Read and Write data from amp to Excel sheets xls in Selenium using Apache POIFor performing CRUD operations on MS Excel sheets in the xlsx format we use the XSSF implementation provided by the Apache POI library Test Scenario a 🡪Search for LambdaTest on Bing com b 🡪Search for LambdaTest Blog on Bing comClick on the First test resultAssert if the current page title does not match with the expected page titleAppend the corresponding test result in the cell next to the test caseHere is the content of the MS Excel File i e Test xls that contains details of the test scenario Implementationpackage com DataDrivenFramework import java io import java net MalformedURLException import java net URL import org apache poi hssf usermodel HSSFWorkbook import org apache poi ss usermodel import org apache poi xssf usermodel XSSFWorkbook import org openqa selenium import org openqa selenium chrome ChromeDriver import org openqa selenium remote DesiredCapabilities import org openqa selenium remote RemoteWebDriver import org testng Assert import org testng annotations AfterClass import org testng annotations BeforeTest import org testng annotations DataProvider import org testng annotations Test public class test DataDrivenFramework WebDriver driver XSSFWorkbook workbook Sheet sheet Cell cell String username user name String access key access key BeforeTest public void init throws InterruptedException MalformedURLException DesiredCapabilities capabilities new DesiredCapabilities capabilities setCapability build Java Data Driven Framework in Selenium WebDriver capabilities setCapability name Java Data Driven Framework in Selenium WebDriver capabilities setCapability platformName OS X Yosemite capabilities setCapability browserName MicrosoftEdge capabilities setCapability browserVersion capabilities setCapability tunnel false capabilities setCapability network true capabilities setCapability console true capabilities setCapability visual true driver new RemoteWebDriver new URL http username access key hub lambdatest com wd hub capabilities System out println Started session Test description Testing data input from XLS i e HSSF priority enabled true public void Test ddf hssf input throws IOException InterruptedException HSSFWorkbook workbook String test url null WebElement lt link null String exp title null Import Excel Sheet File src new File C Folder Test xls Load the file FileInputStream fis new FileInputStream src Load the workbook workbook new HSSFWorkbook fis Load the sheet in the workbook Index gt Tab sheet workbook getSheetAt for int counter counter lt sheet getLastRowNum counter Row gt Contains the site details and search term Hence we skip that row cell sheet getRow counter getCell Cell contains the test URL if cell getCellType CellType STRING test url cell getStringCellValue driver get test url Cell gt Search Term cell sheet getRow counter getCell if cell getCellType CellType STRING String search string cell getStringCellValue Let s perform the search operation try Enter the search term in the Google Search Box WebElement search box driver findElement By xpath input id sb form q search box sendKeys search string Keys ENTER Thread sleep if search string equalsIgnoreCase LambdaTest lt link driver findElement By xpath a Most Powerful Cross Browser Testing Tool Online LambdaTest exp title Most Powerful Cross Browser Testing Tool Online LambdaTest else if search string equalsIgnoreCase LambdaTest Blog lt link driver findElement By xpath a LambdaTest A Cross Browser Testing Blog exp title LambdaTest A Cross Browser Testing Blog if lt link null lt link click Thread sleep String curr window title driver getTitle Assert assertEquals curr window title exp title Write the result in the excel sheet Write Data in the Result Column FileOutputStream fos new FileOutputStream src String message Passed sheet getRow counter createCell setCellValue message workbook write fos fos close catch Exception e System out println e getMessage AfterClass public void tearDown if driver null driver quit Code WalkthroughImport the packages that contain the methods and interfaces for performing operations on xls fileimport org apache poi ss usermodel import org apache poi xssf usermodel XSSFWorkbook The method implemented under the BeforeTest annotation sets the desired browser capabilities A RemoteWebDriver instance is created with the desired browser capabilities with the Selenium Grid URL set to the cloud based Selenium Grid on LambdaTest hub lambdatest com wd hub BeforeTestpublic void init throws InterruptedException MalformedURLException DesiredCapabilities capabilities new DesiredCapabilities capabilities setCapability build Java Data Driven Framework in Selenium WebDriver capabilities setCapability name Java Data Driven Framework in Selenium WebDriver capabilities setCapability platformName OS X Yosemite capabilities setCapability browserName MicrosoftEdge capabilities setCapability browserVersion capabilities setCapability tunnel false driver new RemoteWebDriver new URL http username access key hub lambdatest com wd hub capabilities Create a new workbook of type HSSFWorkbook It will be further used when accessing the Sheet and reading writing at appropriate cells in the Sheet public void Test ddf hssf input throws IOException InterruptedException HSSFWorkbook workbook Create a Workbook object by referring to the FileInputStream object that points to the location where the Excel File xls is located on the host machine File src new File C Folder Test xls FileInputStream fis new FileInputStream src Load the Excel Workbook using the FileInputStream object obtained from Step workbook new HSSFWorkbook fis Using the Workbook object we access the Sheet at index using the getSheetAt method sheet workbook getSheetAt Row zero contains the Header or title in the sheet Hence that row is ignored Cell 🡪Test URL Cell 🡪Search Term and Cell 🡪Test Result A for loop starting from to the total number of rows i e in this case obtained using getLastRowNum method of the Sheet class is run for executing the test scenarios a and b for int counter counter lt sheet getLastRowNum counter The getRow method returns the logical row number i e for test scenario a and for test scenario b Once we have the row number the getCell cell number method of the HSSFRow object is used for accessing the specific cell Shown below are the contents of the cells on Row Cell 🡪Cell 🡪LambdaTestCell 🡪Result Test Status updated post test execution cell sheet getRow counter getCell Cell contains the URL under test Using the Cell obtained from step the getStringCellValue method gets the value of the cell as a String Next we navigate to the test URL if cell getCellType CellType STRING test url cell getStringCellValue driver get test url The required search terms are located in the following Cells Cell 🡪LambdaTestCell 🡪LambdaTest BlogThe getRow method returns the logical row number For example row number represents Test Scenario a and row number represents Test Scenario b Cell number remains unchanged Hence it is hard coded to Finally the search string is retrieved from the Cell using the getStringCellValue method cell sheet getRow counter getCell String search string cell getStringCellValue Now that we have the search string from the previous step it is entered in the search box and an Enter key is pressed to initiate the search operation For test scenario a the search term is LambdaTest and for scenario b the search term is LambdaTest Blog Though the search terms for both tests are different the overall execution path remains unchanged WebElement search box driver findElement By xpath input id sb form q search box sendKeys search string Keys ENTER Depending on the search term the link that appears as the first result also changes A case insensitive string comparison is done with the search term and based on the comparison result and the top result link is located using the XPath property of the WebElement Test Scenario a lt link driver findElement By xpath a Most Powerful Cross Browser Testing Tool Online LambdaTest exp title Most Powerful Cross Browser Testing Tool Online LambdaTest Test Scenario b lt link driver findElement By xpath a LambdaTest A Cross Browser Testing Blog exp title LambdaTest A Cross Browser Testing Blog A click operation is performed on the WebElement that points to the first test result on the Bing Search page if lt link null lt link click Assert is thrown if the Page Title does not match with the expected page title String curr window title driver getTitle Assert assertEquals curr window title exp title We use the Java FileOutputStream class an output stream used for writing data in the file The Excel Workbook which has the test data i e Path To File File xls is opened to write the test result Test Scenario a Test result to be written to Cell Test Scenario b Test result to be written to Cell Using the required row number we create a new Cell using the createCell method In our case the Cell number where the test result is to be written is Then in the Cell inline with the corresponding test scenario we write the test result in String format in the current cell using the setCellValue method offered by the HSSFCell class FileOutputStream fos new FileOutputStream src String message Passed sheet getRow counter createCell setCellValue message We now write to the OutputStream i e fos and then close the output stream using the close method offered by the Output Streamworkbook write fos fos close ExecutionAs seen in the snapshot of the Excel Workbook that contained the test inputs the test scenarios were executed successfully and the test result was written in the respective cells in the Sheet Read and Write data from amp to Excel sheets xlsx in Selenium using Apache POIFor performing CRUD operations on MS Excel sheets in the xlsx format we use the XSSF implementation provided by the Apache POI library Test Scenario a amp b 🡪Test URL Add a new item in the LambdaTest ToDo appTest Scenario a Testing on LambdaTestTest Scenario b Hello World on LambdaTestAssert if the new item is not added successfully to the listWrite the test result in the input Excel fileHere is the content of the MS Excel File i e Test xlsx that contains details of the test scenario ImportantWhen using Apache POI for xls files and POI OOXML for xlsx files in the same class it is important to have poi and poi ooxml point to the same version in pom xml This is because Apache Maven POI dependencies for poi amp poi ooxml pointing to different versions lead to the error java lang IncompatibleClassChangeError In pom xml the dependencies for POI and POI OOXML point to the same versions i e Implementationpackage com DataDrivenFramework import java io import java net MalformedURLException import java net URL import org apache poi hssf usermodel HSSFWorkbook import org apache poi ss usermodel import org apache poi xssf usermodel XSSFWorkbook import org openqa selenium import org openqa selenium chrome ChromeDriver import org openqa selenium remote DesiredCapabilities import org openqa selenium remote RemoteWebDriver import org testng Assert import org testng annotations AfterClass import org testng annotations BeforeTest import org testng annotations DataProvider import org testng annotations Test public class test DataDrivenFramework WebDriver driver XSSFWorkbook workbook Sheet sheet Cell cell String username user name String access key access key BeforeTest public void init throws InterruptedException MalformedURLException DesiredCapabilities capabilities new DesiredCapabilities capabilities setCapability build Java Data Driven Framework in Selenium WebDriver capabilities setCapability name Java Data Driven Framework in Selenium WebDriver capabilities setCapability platformName OS X Yosemite capabilities setCapability browserName MicrosoftEdge capabilities setCapability browserVersion capabilities setCapability tunnel false capabilities setCapability network true capabilities setCapability console true capabilities setCapability visual true driver new RemoteWebDriver new URL http username access key hub lambdatest com wd hub capabilities System out println Started session Test description Testing data input from XLSX i e XSSF priority enabled true public void Test ddf xssf input throws IOException InterruptedException XSSFWorkbook workbook Import the Excel Sheet File src new File C Folder Test xlsx Load the file FileInputStream fis new FileInputStream src Load the workbook workbook new XSSFWorkbook fis The sheet is in Tab sheet workbook getSheetAt for int counter counter lt sheet getLastRowNum counter Skip Row cell sheet getRow counter getCell Cell contains the test URL if cell getCellType CellType STRING String test url cell getStringCellValue driver get test url Cell gt Search Term cell sheet getRow counter getCell if cell getCellType CellType STRING String new item cell getStringCellValue try Let s mark done first two items in the list driver findElement By name li click driver findElement By name li click Get the item to be added from the sheet Let s add an item in the list driver findElement By id sampletodotext sendKeys new item driver findElement By id addbutton click Let s check that the item we added is added in the list String enteredText driver findElement By xpath html body div div div ul li span getText if enteredText equals new item System out println Demonstration is complete String status passed Write the result in the excel sheet Write Data in the Result Column FileOutputStream fos new FileOutputStream src String message Passed sheet getRow counter createCell setCellValue message workbook write fos fos close catch Exception e System out println e getMessage AfterClass public void tearDown if driver null driver quit Code WalkthroughCreate an object of XSSFWorkbook This object will be further used when accessing the Sheet and reading writing at appropriate cells in the Sheet XSSFWorkbook workbook Create a Workbook object by referring to the FileInputStream object that points to the location where the Excel File xlsx is located on the host machine File src new File C Folder Test xlsx FileInputStream fis new FileInputStream src Load the Excel Workbook using the FileInputStream object obtained from Step workbook new XSSFWorkbook fis Using the Workbook object we access the Sheet at index using the getSheetAt method sheet workbook getSheetAt Like the earlier test which demonstrated the usage of the HSSF Workbook row also contains the title of the fields i e Test URL Item to Add and Result Hence we exclude Row from the test execution A for loop is run from rows to sheet getLastRowNum which equates to in our case so that the two test scenarios in the sheet can be executed one after the other for int counter counter lt sheet getLastRowNum counter The getRow method returns the logical row number i e for test scenario a and for test scenario b Now that we have the row number the getCell cell number method of the XSSFRow is used for accessing the specific cell Shown below are the contents of the cells on Row Cell 🡪Cell 🡪Testing on LambdaTestCell 🡪Result Test Status updated post test execution Cell contains the URL under test The getStringCellValue method gets the value of the cell as a String Next we navigate to the test URL cell sheet getRow counter getCell Cell contains the test URL if cell getCellType CellType STRING String test url cell getStringCellValue driver get test url New items to be added are located in the following Cells Cell 🡪Testing on LambdaTestCell 🡪Hello World on LambdaTestRow number represents Test Scenario a and row number represents Test Scenario b Cell number remains unchanged hence it is hard coded to The new items to be added to the ToDo list are retrieved from the Cell using the getStringCellValue method cell sheet getRow counter getCell if cell getCellType CellType STRING String new item cell getStringCellValue First two items in the ToDo list are marked as Done by locating the respective WebElement using the Name property and then performing the click operation on that WebElement driver findElement By name li click driver findElement By name li click New entry to the ToDo list is added by locating the WebElement using the ID property and using the sendKeys method for entering the new entry in the text box The Add Button on the page is located using the ID property and click operation is performed on the button for adding the new entry to the ToDo list driver findElement By id sampletodotext sendKeys new item driver findElement By id addbutton click The content of the newly added item is fetched using the getText method in Selenium If the newly added item equals the expected item the test is considered as Passed String enteredText driver findElement By xpath html body div div div ul li span getText if enteredText equals new item System out println Demonstration is complete String status passed The Java FileOutputStream class is used for writing the data in the file Then the Excel Workbook with the test data i e Path To File File xlsx is opened to write the test result Test Scenario a Test result to be written to Cell Test Scenario b Test result to be written to Cell The test result for the respective tests is written in the corresponding Cells as a String Value The setCellValue method writes the test result in the Cell FileOutputStream fos new FileOutputStream src String message Passed sheet getRow counter createCell setCellValue message We now write to the OutputStream i e fos Post the write operation the close method is invoked for closing the OutputStream workbook write fos fos close ExecutionAs seen in the Excel Workbook snapshot containing the test inputs test scenarios are executed successfully and test results are written in the correct Cells in the Sheet Data Driven Framework in Selenium using TestNG DataProvider with ExcelDataProvider in TestNG is popularly used with MS Excel where the data to be supplied in the DataProvider is read from an Excel sheet This approach is primarily useful when the test has to be performed against a massive amount of test data You can refer to DataProviders in TestNG for a quick recap on the topic Test Scenario a 🡪Search for LambdaTest on Google b 🡪Search for LambdaTest Blog on GoogleClick on the First test resultAssert if the current page title does not match with the expected page titleAppend the corresponding test result in the cell next to the test caseTo get started we create a test data set in an Excel Sheet The first column contains the Search Term and the second column contains the Expected Page Title after the search is executed Implementationpackage com DataDrivenFramework import java io import java net MalformedURLException import java net URL import org apache poi hssf usermodel HSSFWorkbook import org apache poi ss usermodel import org apache poi xssf usermodel XSSFRow import org apache poi xssf usermodel XSSFSheet import org apache poi xssf usermodel XSSFWorkbook import org openqa selenium import org openqa selenium chrome ChromeDriver import org openqa selenium remote DesiredCapabilities import org openqa selenium remote RemoteWebDriver import org testng Assert import org testng annotations AfterClass import org testng annotations BeforeTest import org testng annotations DataProvider import org testng annotations Test public class test DataDrivenFramework WebDriver driver XSSFWorkbook workbook Sheet sheet Cell cell String username user name String access key access key BeforeTest public void init throws InterruptedException MalformedURLException DesiredCapabilities capabilities new DesiredCapabilities capabilities setCapability build Java Data Driven Framework in Selenium WebDriver capabilities setCapability name Java Data Driven Framework in Selenium WebDriver capabilities setCapability platformName OS X Yosemite capabilities setCapability browserName MicrosoftEdge capabilities setCapability browserVersion capabilities setCapability tunnel false capabilities setCapability network true capabilities setCapability console true capabilities setCapability visual true driver new RemoteWebDriver new URL http username access key hub lambdatest com wd hub capabilities System out println Started session DataProvider name dataset public Object getExcelData Object arrObj getExData C Folder Test xlsx TestData return arrObj public String getExData String fileName String sheetName String data null try FileInputStream fis new FileInputStream fileName XSSFWorkbook workbook new XSSFWorkbook fis XSSFSheet sheet workbook getSheet sheetName XSSFRow row sheet getRow int noOfRows sheet getPhysicalNumberOfRows int noOfCols row getLastCellNum Cell cell data new String noOfRows noOfCols for int outer cnt outer cnt lt noOfRows outer cnt for int inner cnt inner cnt lt noOfCols inner cnt row sheet getRow outer cnt cell row getCell inner cnt data outer cnt inner cnt cell getStringCellValue System out println data outer cnt inner cnt catch Exception e System out println The exception is e getMessage return data Test dataProvider dataset description Data Driven framework using Data Provider priority enabled true public void Test ddf dataprovider excel String search string String expected title throws IOException InterruptedException String test url WebElement lt link null driver manage window maximize driver get test url Thread sleep try Enter the search term in the Google Search Box WebElement search box driver findElement By xpath input name q search box sendKeys search string search box submit Thread sleep Click on the first result which will open up the LambdaTest homepage if search string equalsIgnoreCase LambdaTest lt link driver findElement By xpath span LambdaTest Most Powerful Cross Browser Testing Tool Online else if search string equalsIgnoreCase LambdaTest Blog lt link driver findElement By xpath span A Cross Browser Testing Blog LambdaTest lt link click Thread sleep String curr window title driver getTitle Assert assertEquals curr window title expected title catch Exception e System out println e getMessage AfterClass public void tearDown if driver null driver quit Code WalkThroughgetExData MethodAn object of Workbook is created by referring to the FileInputStream object that points to the location where the Excel File xlsx is located on the host machine The object of type XSSFWorkbook will be further used for accessing the Sheet and the various Cells in the Sheet FileInputStream fis new FileInputStream fileName XSSFWorkbook workbook new XSSFWorkbook fis We get the Sheet using the getSheet method that takes the Sheetname as the input argument In our case the test data is available in the sheet with the name TestData hence the same is passed to the getSheet method Once inside the Sheet we read the first using the getRow method which returns an object of type XSSFRowXSSFSheet sheet workbook getSheet sheetName XSSFRow row sheet getRow We get the total number of rows and columns or Cells using the getPhysicalNumberOfRows method in XSSFSheet class and getLastCellNum method in XFFSRow class int noOfRows sheet getPhysicalNumberOfRows int noOfCols row getLastCellNum In our case the number of Rows amp Columns are amp respectively We create a new D String array of dimensionsdata new String noOfRows noOfCols In a nested for loop outer count 🡪 no of rows inner count 🡪 no of columns we fetch the current row using the getRow method The getCell method returns the current column Now that we have the row and column the data in that particular cell is read using the getStringCellValue method provided by the Cell class Since the Row contains the title i e Keyword Expected Title we start reading from the first row First for loop runrow cell data LambdaTest i e Cell row cell data Most Powerful Cross Browser Testing Tool Online LambdaTest i e Cell Second for loop runrow cell data LambdaTest Blog i e Cell row cell data LambdaTest A Cross Browser Testing Blog i e Cell for int outer cnt outer cnt lt noOfRows outer cnt for int inner cnt inner cnt lt noOfCols inner cnt row sheet getRow outer cnt cell row getCell inner cnt data outer cnt inner cnt cell getStringCellValue System out println data outer cnt inner cnt Return the D array i e data that we populated with the values from the Sheet in Step return data getExcelDataIn this method we create a DataProvider method that uses the getExData method that returns a D object created by reading the required Cell values from the Excel Sheet DataProvider name dataset public Object getExcelData Object arrObj getExData C Folder Test xlsx TestData return arrObj Test ddf dataprovider excelThis test method uses the dataset DataProvider that returns a D object containing the search string and expected page title Test dataProvider dataset description Data Driven framework using Data Provider priority enabled true public void Test ddf dataprovider excel String search string String expected title throws IOException InterruptedException Once we navigate to the test URL i e Google Homepage enter the search term in the search box using the sendKeys method in Selenium The search box is located using the findElement method in Selenium which uses the XPath property for locating the search box Web Element WebElement search box driver findElement By xpath input name q search box sendKeys search string Trigger the search using the submit method search box submit Perform a case insensitive comparison of the Search String i e LambdaTest LambdaTest Blog and accordingly locate the first link using the findElement method with the WebElement s XPath property if search string equalsIgnoreCase LambdaTest lt link driver findElement By xpath span LambdaTest Most Powerful Cross Browser Testing Tool Online else if search string equalsIgnoreCase LambdaTest Blog lt link driver findElement By xpath span A Cross Browser Testing Blog LambdaTest Now that the link is located click on the link to navigate to the resultant page lt link click Get the current page title using the getTitle method of Selenium WebDriver Assert if the current page title does not match the expected title String curr window title driver getTitle Assert assertEquals curr window title expected title ExecutionBelow is the execution snapshot from the IntelliJ IDE which indicates that the data from the external data set i e Excel Sheet was read successfully As a result the DataProvider in TestNG was able to use that data for performing the search operation on Google Perform Cross Browser Testing in Selenium using Apache POIIn all the examples we showcased so far the test data was fetched from an external data feed i e xls xlsx and the test data was used in running the same test against different data sets What if you intend to run a cross browser test where the online browser amp OS combinations are read from an external file xls xlsx In this section we look at how the APIs provided by the Apache POI library can be leveraged for running a cross browser test First here is the snapshot of the Excel file Test xls which contains the required setting of the Desired Capabilities for the Remote WebDriver As shown above the same test is run against two different virtual browser combinations Chrome on Windows Chrome on macOS Catalina Test ScenarioGo to Run the steps thru for the browser amp OS combinations specified in the external Excel file Click on the I Accept buttonScroll to the End of the PageFind the element with link List of Browsers and click on the elementCheck if the current page URL is and set the Test Result accordinglyWrite the test result at appropriate Cells in the excel sheetImplementationpackage com DataDrivenFramework import java io import java net URL import org apache poi hssf usermodel HSSFWorkbook import org apache poi ss usermodel import org apache poi xssf usermodel XSSFWorkbook import org openqa selenium By import org openqa selenium JavascriptExecutor import org openqa selenium WebDriver import org openqa selenium WebElement import org openqa selenium remote DesiredCapabilities import org openqa selenium remote RemoteWebDriver import org testng Assert import org testng annotations Test public class test LT DataDrivenFramework WebDriver driver XSSFWorkbook workbook Sheet sheet Cell cell public static String username user name public static String access key access key Test description CBT Testing data input from XLS i e HSSF priority enabled true public void Test ddf cbt input throws IOException InterruptedException String test combs new String Integer cnt String test url HSSFWorkbook workbook Import the Excel Sheet File src new File C Folder Test xls Load the File FileInputStream fis new FileInputStream src Load the Workbook workbook new HSSFWorkbook fis The Excel file contains two sheets Sheet Browser and OS Combination Load the data in Sheet for creating an instance of Remote WebDriver sheet workbook getSheetAt Get the relevant capabilities headings from row while cnt lt cell sheet getRow getCell cnt test combs cnt cell getStringCellValue cnt Assign the capabilities from row onwards for int row cnt row cnt lt sheet getLastRowNum row cnt DesiredCapabilities capabilities new DesiredCapabilities for cnt cnt lt cnt String props sheet getRow row cnt getCell cnt getStringCellValue capabilities setCapability test combs cnt props capabilities setCapability tunnel false capabilities setCapability network true capabilities setCapability console true capabilities setCapability visual true driver new RemoteWebDriver new URL http username access key hub lambdatest com wd hub capabilities Now comes the test scenario driver get test url WebElement elem accept driver findElement By xpath a I ACCEPT elem accept click Thread sleep Scroll till the end of the page JavascriptExecutor driver executeScript window scrollBy document body scrollHeight WebElement elem brow list driver findElement By xpath a List of Browsers elem brow list click Thread sleep Assert assertEquals driver getCurrentUrl Update result in the excel sheet Write Data in the Result Column FileOutputStream fos new FileOutputStream src String message Passed sheet getRow row cnt createCell setCellValue message workbook write fos fos close System out println CBT test to demo Data Driven Framework successful n driver quit FileName test LT DataDrivenFramework javaCode WalkthroughCreate an instance of Selenium WebDriver HSSFWorkBook Sheet and Cell respectively WebDriver driver HSSFWorkbook workbook Sheet sheet Cell cell Import the Excel Sheet and load the file using FileInputStreamFile src new File C Folder Test xls workbook new HSSFWorkbook fis Create an object of HSSFWorkbook and load the data in the Sheet where the fields for creating the Desired Capabilities are present sheet workbook getSheetAt The first row i e row contains strings indicating the respective fields used to create the Capabilities i e build name platformName browserName etc It is inline with what has to be passed in terms of DesiredCapabilities to the Remote WebDriver In a while loop with end count as the String Value in Cell Cell is read and populated in a String array test combs This array only contains the Capabilities that have to be set i e build name etc while cnt lt cell sheet getRow getCell cnt test combs cnt cell getStringCellValue cnt From row onwards we start assigning values to set the DesiredCapabilities Then in a for loop we read the String value from each cell and assign the same to the corresponding String element from the array test combs For Combination test combs 🡪build capability is set to Data Driven Framework String value from Cell test combs 🡪name capability is set to Data Driven Framework String value from Cell test combs 🡪platformName capability is set to Windows String value from Cell test combs 🡪browserName capability is set to Chrome String value from Cell test combs 🡪browserVersion capability is set to String value from Cell The same set of actions are repeated for Test Combination the capabilities of which are present in Cell thru Cell DesiredCapabilities capabilities new DesiredCapabilities for cnt cnt lt cnt String props sheet getRow row cnt getCell cnt getStringCellValue capabilities setCapability test combs cnt props Now that the DesiredCapabilities are set an instance of Remote WebDriver is created with Selenium Grid set to cloud based Selenium Grid on LambdaTest hub lambdatest com wd hub driver new RemoteWebDriver new URL http username access key hub lambdatest com wd hub capabilities We navigate to the desired test URL i e String test url driver get test url One the test URL locate the I Accept button using the XPath property and click on the located WebElement WebElement elem accept driver findElement By xpath a I ACCEPT elem accept click Scroll to the end of the web page by invoking the “window scrollBy method in JavaScript The executeScript command executes the scrollBy method in the context of the currently selected window JavascriptExecutor driver executeScript window scrollBy document body scrollHeight Locate the WebElement List of Browsers using the XPath property and click on the element WebElement elem brow list driver findElement By xpath a List of Browsers elem brow list click Assert is thrown if the current URL does not match the expected URL Assert assertEquals driver getCurrentUrl We use the Java FileOutputStream class an output stream used for writing data in the file The Excel Workbook which has the test data i e Path To File File xls is opened to write the test result Test Combination Test result to be written to Cell Test Combination Test result to be written to Cell The setCellValue method offered by the HSSFCell class is used for writing the test result i e Passed to the cells shown above FileOutputStream fos new FileOutputStream src String message Passed sheet getRow row cnt createCell setCellValue message We write to the OutputStream i e fos post which we close the Output Stream using the close method workbook write fos fos close ExecutionThe test was successfully run against the browser amp OS combinations mentioned in the Excel Sheet Therefore the test status is also updated in the cells with the title Result We also executed all the approaches demonstrated earlier in a single go and the test execution was successful The Automation Dashboard in LambdaTest indicates the status of the test execution As seen above the tests were successfully executed on LambdaTest s cloud based Selenium Grid ConclusionData Driven Testing is one of the ideal ways for performing testing at scale Separation of test data from Functional tests is one of the major advantages of the Data Driven Framework in Selenium The separation of test data from the tests ensures that minimal changes in the business rules do not result in changes in the test implementation This also avoids rewriting of test code when testing against multiple sets of data SourceApache POI is a popular library that provides APIs for performing CRUD Create Read Update and Delete operations on external data sources like MS Excel Sheets MS Access databases and more Data Driven Framework in Selenium is used along with Apache POI for performing data driven testing using different test combinations External data sources like Excel Sheets can also supply different browser amp OS combinations for realizing cross browser testing for web projects 2022-02-10 11:51:10
海外TECH DEV Community Know the luxuriant DeFi Marketing Services right now! https://dev.to/shirleydazzle/know-the-luxuriant-defi-marketing-services-right-now-3ae9 Know the luxuriant DeFi Marketing Services right now It is no wonder that Blockchain technology would provide us with numerous profitable benefits In such a category being an entrepreneur you must have noticed that Decentralized Finance DeFi platforms are flourishing in the crypto market Considering that fact the cryptopreneurs like you must undergo the DeFi marketing services to gain instant visibility among a wide audience These DeFi platforms have excelled by offering crypto users the means of third parties Yes this decentralized platform protects the complete data and prevents financial intermediaries Therefore DeFi Platform is driving the whole crypto market to the next stage of financial exchange We shall jump into the privileges you attain through effective marketing services without further delay What Are The Perks You Gain From DeFi Marketing Agency When you have decided to promote your platform you must lean on the most predominant DeFi marketing agency Here they will work as a pillar of support to lift your project and make it visible in the market Apart from this they will also provide innovative ideas that can make more crypto users thrive on your platform A few notable ways that are included in DeFi marketing services are listed below Social Media Marketing Effective Landing Page Getting Towards Influencers Creating Engaging Community Utilize The NewslettersOrganize Alluring Campaign And Events Host Enticing Giveaway And RewardsSpread the word of your DeFi platform and it is a uniqueness to all parts of the cities in the blink of an eye Winding UpIn brief undergoing the DeFi marketing company to uplift your business is an ideal choice that makes one stand ahead of the competitors Keeping a constant analysis of the growth of your business will ensure you obtain a profit in the forthcoming years 2022-02-10 11:27:55
海外TECH DEV Community Remarkable Tips to Hire Full Stack Developers https://dev.to/etelligens/remarkable-tips-to-hire-full-stack-developers-25ko Remarkable Tips to Hire Full Stack DevelopersDevelopers are an ultimatum for creating innovative applications for your business relying on different front end back end and other cross disciplines role model developers can be hectic and expensive Hiring full stack Developers might be the significant key solution to these all annoyance What is a full stack developer A full stack Developer is indeed a whole package of all the professional skills needed to create an application blessed with both frontend and backend expertise Familiar with numerous programming languages destined to manage the above three tier architecture of any application development team Significant Objective of the full stack Developers Compensating unnecessary troubles the expertise of Full stack developers results in a high quality effective application apart from which these developers lead with primary objectives throughout their developing projects•Forming a responsive User interface with the brilliance of numerous programming language•Efficaciously developed application on both front end and back end side for immense audience result •Managing the technicalities of developing projects between the entire project development team •Usage of latest technical code and recent front end and back end development technologies •Manifesting with higher flexibility and knowledgeable approach for the network security Quick check on the required skill of Full stack DevelopersUsually the full stack developers are skilled with all the knowledge in the sea still these remarkably particular skills should be ideally determined while hiring full stack developers These skills are Differentiated into Two categories Technical Backend Frontend and database and soft skill as in non technical Understanding of front end technology•Knowledge of third parties libraries like Ajax or DOM•Hiring node JS developer or Vue Js developer could help•Creative mastery of UX UI and proficiency in programming languages like PHP Java CSS HTML Crucial expertise in Back end development•Known to a creative framework such as larael Ruby on Rails Django Net•Person Skilled with one server side language including Java Python PHP Ruby could do the job•Have no problem with API development and connecting databaseConveniently working with Database•Effortlessly gets along with Storage of Data sets •Separating files and facilitating computation task skill•Familiar with database management with SQL Server MongoDB or oracleNon Technical skills to configure apart from the technical competency•Project management skill•Extensive experience•Team co ordination•Capabilities to take the bigger decision•Adaptability and flexibilityConsidering their immense flexibility versatility competency and adaptability the entire stack developers make an ideal fit for your productive responsive top notch business within a reasonable budget Why wait then 2022-02-10 11:23:36
海外TECH DEV Community Arrow Functions vs Normal Functions https://dev.to/thenerdydev/arrow-functions-vs-normal-functions-3djk Arrow Functions vs Normal FunctionsHey everyone In this article let us understand the differences between Arrow Functions and Normal Functions This article was first published on Check the website for more interesting articles and tutorials on Web Development Arrow Functions vs Normal FunctionsWe know that we can define JavaScript functions in many ways The first way is by making use of the function keyword So as an example consider this piece of code function greet name return Hey name This comes under normal functions that we declare when we write code Another syntax that we often see getting used in the code is Function Expression SyntaxSo let us transform the above function declaration into a function expression const greet function name return Hey name The second way is using the arrow function syntax So let us transform the above code based on function expression to a code that uses the arrow function syntaxconst greet name gt return Hey name Now if you see any of the above syntaxes can be used for defining functions what you choose depends on you but knowing the differences between these syntaxes will make it easier to decide regarding the choice of syntax in different cases this keywordthis keyword as we know is a property of an execution context The main use of it is observed in functions and constructors Here is a video where you can learn about the rules of the this keyword Normal functions this inside a normal function is dynamic By dynamic it means that the value of this depends on how we invoke the function Let us see the ways we can invoke a normal function So during a normal invocation the value of this equals to the global object There is a small exception to this If the function runs in strict mode then the this keyword equals undefined So let us see an example function someFunction console log this someFunction The above examples logs the window object to the console Next if we have a method that is sitting within an object then the this keyword when referenced in the scope of method will point to the object that owns that particular methods which also represents the context in which that method is defined in So let us see an example for this as well const someObject greet console log this console log hello someObject greet So the above code calls the greet method that is sitting inside the someObject object Next we can also make use of the call method to perform an indirect invocation here the value of this equals to the first argument that the call method receives function someFunction console log this const someContext a some value someFunction call someContext For the above example code the this keyword points to the someContext object Next let us see what this equals to in a constructor function that is created using the normal function syntax function User console log this new User If we invoke the constructor function using the new keyword then this equals to the newly created instance Arrow FunctionsArrow functions do not have their own this instead they look up the scope chain to find a this that they can use or until the lookup hits the global scope much in the same way as a variable resolves its value So if you reference a variable in a nested scope then the lookup will go up the scope chain until it resolves its declaration This in essence means that arrow function does not define its own execution context This also means that no matter how or where the arrow functions get executed the this value inside an arrow function always equals the this value from the outer function IOW arrow functions resolve the this in a lexical manner Let us take an example const someObject someMethod elements console log this elements forEach element gt console log element console log this someObject someMethod this value inside the callback of forEach equals to this of the outer function someMethod ConstructorsNormal Functions We now know that normal functions can be used for creating new objects So for example if we want to create a new user then we can create a constructor function with the name User and that will give us the ability to create new instances of a car when used with the new keyword So let us see the code for this function User name age profession this name name this age age this profession profession const newUser new User alex developer console log newUser instanceof User So if you see above User is a normal function When invoked with the new keyword new User alex developer new instances of User gets created Arrow Functions Arrow functions cannot be used as constructor So if you try to invoke an arrow function using the new keyword JavaScript will yell at you with an error So let us see an example for this as well const User gt this name name this age age this profession profession const newUser new User alex developer So for above code invoking new User alex developer will throw an error specifically this error TypeError User is not a constructor Implicit ReturnNormal Function See the following code function someFunction return some value const value someFunction console log value In the above code we are just invoking the normal function someFunction and at the point of invocation we receive a value which we store in value variable that we defined above Now if we omit the return statement in the above code or if there is no expression after the return statement the normal function will do an implicit return here with the value of undefined So let me demonstrate this with the help of an example function someFunction some value function someFunction return console log someFunction console log someFunction In above code the first console log will give us undefined because it misses the return keyword it actually returns nothing Coming to the second console log it does return but there is no value as such hence this is also undefinedArrow Function In case of an arrow function you can perform implicit return but the condition for same is that your arrow function should contain only one expression If so is the case you can then omit the function s curly braces and simply do an implicit return for the expression So let us see an example for this const multiplyBy num gt num console log multiplyBy The multiplyBy arrow function if you see comprises of just one expression num gt num So here the expression is implicitly returned by the arrow function without the use of return keyword MethodsNormal FunctionNormal functions as we know is the usual way for defining methods on classes Let us see an example class User constructor name age profession this name name this age age this profession profession logUserDetails console log this name console log this age console log this profession const user new User alex developer user logUserDetails So the above code does works But let us assume that we need to supply the logUserDetails method as a callback say for example to a setTimeout or some other event listener Now in such cases we may get a wrong context while trying to access the this value So consider this code setTimeout user logUserDetails So after second the above code will call the logUserDetails method on the user object Now for the above code this points to the window object Let us manually fix the context so by correctly binding this value to point to the user object So for this we can make use of the bind method setTimeout user logUserDetails bind user In the above code user logUserDetails bind user binds the this value to the user instance So this ensures that we don t loose the context and that the this keyword is correctly bound to the instance There is another workaround for this as well which is using arrow functions Arrow Function Now with the introduction of class fields we can use the arrow functions as methods inside classes Contrary to the normal functions the method that we define using arrow functions binds this lexically to the instance of the class So let us see an example for same class User constructor name age profession this name name this age age this profession profession logUserDetails gt console log this name console log this age console log this profession const user new User alex developer user logUserDetails Now for the above code if we use user logUserDetails as a callback without even performing a bind it will give us the correct values The value of this inside our logUserDetails will be the class instance itself So if you try the below code you will get alex and developer to the console as output setTimeout user logUserDetails So this is it for this article Thanks for reading If you enjoy my articles consider following me on Twitter for more interesting stuff Twitter Don t forget to leave a like if you loved the article Also share it with your friends and colleagues PS If you are looking to learn Web Development I have curated a FREE course for you on my YouTube Channel check the below article Web Developer Full Course HTML CSS JavaScript Node js and MongoDB The Nerdy Dev・Apr ・ min read html css node javascript Looking to learn React js with one Full Project check this out Learn React with one BIG Project NOTES included Demo and Video Link The Nerdy Dev・Jun ・ min read daysofcode javascript react webdev 2022-02-10 11:21:09
海外TECH DEV Community Some cool little hacks I've learned. https://dev.to/wolfmath/some-cool-little-hacks-ive-learned-4i7e Some cool little hacks I x ve learned IntroThis is going to be an ongoing documentation of cool little hacks that I ve learned Each entry will consist of what I did originally and what the better version is Hack Using or instead of conditional React Context While iterating through a list of phone numbers show lt PhoneIcon gt next to only the first phone number Original code Using a ternary operator phoneNumbers map phoneNumber i gt lt div gt i lt PhoneIcon gt phoneNumber lt div gt Better Using an or statementcontact phones map phoneNumber i gt lt div gt i amp amp lt PhoneIcon gt phoneNumber lt div gt Explanation This works because the truthiness value of is false So while iterating through the phone numbers if the index is we can conditionally show the lt PhoneIcon gt with i amp amp lt PhoneIcon gt Hack Joining an array Context Sometimes there is an object with empty values and I don t want this object to display if the values are empty The problem is empty values can be either null or empty strings Example firstName null lastName null phone location null favoriteColor Original code const emptyChecker obj gt const nulls Object values obj filter val gt val null const empties Object values obj filter val gt val checks length of nulls amp amp empties against length of the whole return nulls concat empties length Object values obj length Iterate through the values of the object and if they re null add them to an array Do it again but with empty strings Concat the arrays and compare the length to the original Better const emptyChecker obj gt const empties Object values obj filter val gt val checks length of nulls amp amp empties against length of the whole return empties length Object values obj length Explanation This works because instead of iterating through the object values twice we convert the values to booleans as they re being iterated over This works because null has a truthiness value of false as does an empty string Therefore filter val gt val only adds false values to the array and then we can compare the length to to the original 2022-02-10 11:20:23
海外TECH DEV Community FullStack JWT Auth: Diving into SvelteKit - Login and Registration https://dev.to/sirneij/fullstack-jwt-auth-diving-into-sveltekit-login-and-registration-10c2 FullStack JWT Auth Diving into SvelteKit Login and Registration IntroductionHaving hit the ground running with SvelteKit by building our project s layout as well as its logout feature in the previous article we ll continue exploring SvelteKit in this article by implementing login and registration features Source codeThe overall source code for this project can be accessed here Sirneij django svelte jwt auth A robust and secure Authentication and Authorization System built with Django and SvelteKit django svelte jwt authThis is the codebase that follows the series of tutorials on building a FullStack JWT Authentication and Authorization System with Django and SvelteKit This project was deployed on heroku backend and vercel frontend and its live version can be accessed here To run this application locally you need to run both the backend and frontend projects While the latter has some instructions already for spinning it up the former can be spinned up following the instructions below Run locallyTo run locallyClone this repo git clone Change directory into the backend folder cd backendCreate a virtual environment pipenv shellYou might opt for other dependencies management tools such as virtualenv poetry or venv It s up to you Install the dependencies pipenv installMake migrations and migrate the database python manage py makemigrations python manage py migrateFinally run the application python manage py runserver View on GitHub Live versionThis project was deployed on heroku backend and vercel frontend and its live version can be accessed here Step Implement the login functionalityLet s begin by implementing the login functionality of our app Open up routes accounts login index svelte in your editor and make the content look like lt script gt import notificationData from store notificationStore import post browserSet browserGet from lib requestUtils import goto from app navigation import BASE API URI from lib constants import fly from svelte transition import onMount from svelte let email password error const handleLogin async gt if browserGet refreshToken localStorage removeItem refreshToken const jsonRes err await post fetch BASE API URI login user email email password password if err error err else if jsonRes user tokens browserSet refreshToken jsonRes user tokens refresh notificationData set Login successful await goto onMount gt const notifyEl document getElementsByClassName notification if notifyEl amp amp notificationData setTimeout gt notifyEl display none notificationData set lt script gt lt svelte head gt lt title gt Login FullStack Django amp SvelteKit lt title gt lt svelte head gt lt section class container in fly x duration delay out fly duration gt lt h gt Login lt h gt if error lt p class center error gt error lt p gt if lt form class form on submit preventDefault handleLogin gt lt input bind value email name email type email aria label Email address placeholder Email address gt lt input bind value password name password type password aria label password placeholder password gt lt button class btn type submit gt Login lt button gt lt p class center gt No account yet lt a href accounts register gt Get started lt a gt lt p gt lt form gt lt section gt This svelte file contains a couple of new imports and some scripts aside the notificationData explained in the previous article The first notable import is post This abstracts away sending POST requests to the server and has the following definition in lib requestUtils ts lib gt requestUtils ts export const post async fetch url string body unknown gt try const headers if body instanceof FormData headers Content Type application json body JSON stringify body const token browserGet refreshToken if token headers Authorization Bearer token const res await fetch url method POST body headers if res status const data await res json const error data user error return error throw id error id message error const response await res json return response catch error console error Error outside error throw id message An unknown error occurred return An unknown error occurred error It is an asynchronous function which expects the global window fetch the url to send the request and the data to be sent Looking into the try block we enforced that only json data type will be handled and then went on to make the post request while ensuring proper error handling from the response Back to the svelte file we declared some variables ーemail and password ーand bound them to their respective form inputs using the bind value directive A very simple and intuitive way of binding input values without the ceremonial state bindings in react To give feedbacks about possible errors we also have the error variable declared which later on was given the error response from the post function Entering the handleLogin asynchronous function we first remove any residual refreshToken that might lurking around user s browser If not done we will be faced with some non informative error if the user tries to login Then we called on our post function and passed in the required arguments If no errors was encountered we save the user s refeshToken to localStorage update the notoficationData and redirects the user to the home page The handleLogin function was called on the form s submission using the on submit directive Notice that before assigning this directive to the function we added preventDefault This is extremely important to prevent full page refresh which defeats app like feel Since users are automatically redirected to the login page after logging out of their accounts we also implemented a simple way of resetting the notificationData and animating the notification via the setTimeout function located inside onMount onMount is almost equivalent to react s componentDidMount lifecycle The reason setTimeout was put inside this lifecycle is too ensure that the page has fully been loaded and we have access to document getElementsByClassName notification Step Implement the registration flow Now that we ve gone through how the login was implemented let s checkout the registration flow In the routes accounts register index svelte we have the snippets below outes accounts register index svelte lt script gt import fly from svelte transition import goto from app navigation import BASE API URI from lib constants import notificationData from store notificationStore let email fullName bio username password confirmPassword error const submitForm async gt await fetch BASE API URI register method POST mode cors headers Content Type application json body JSON stringify user email email username username password password bio bio full name fullName then response gt if response status notificationData set Registration successful Login now goto accounts login console log User response json else if response status console log response json catch error gt error error console error Error error const passwordConfirm gt password confirmPassword false true lt script gt lt svelte head gt lt title gt Register FullStack Django amp SvelteKit lt title gt lt svelte head gt lt section class container in fly y duration delay out fly duration gt lt h gt Register lt h gt if error lt p class center error gt error lt p gt if lt form class form on submit preventDefault submitForm gt lt input bind value email type email aria label Email address placeholder Email address required gt lt input bind value username type text aria label Username placeholder Username required gt lt input bind value fullName type text aria label Full name placeholder Full name required gt lt input bind value bio type text aria label Brief bio placeholder Tell us about yourself required gt lt input bind value password type password name password aria label password placeholder password required gt lt input bind value confirmPassword type password name confirmPassword aria label Confirm password placeholder Confirm password required gt if confirmPassword lt button class btn type submit gt Register lt button gt else lt button class btn type submit disabled gt Register lt button gt if lt form gt lt section gt We did same thing as what we did with the login flow aside from using different api endpoint updating notificationData to a different string sending more data to the server and redirecting to the login page Also we didn t use our post function here but using it should produce same output That s basically it We have successfully implemented a robust full stack jwt authentication system Though we have done some authorizations as well but not intentional enough We will try to do some intentional authorizations in our bonus article where we ll look into how to update user data and maybe create an endpoint which only users with admin role can assess and manipulate its data Please be on a lookup for it OutroEnjoyed this article consider contacting me for a job something worthwhile or buying a coffee You can also connect with follow me on LinkedIn 2022-02-10 11:16:27
海外TECH DEV Community Useful BadUSBs: Making a brute force password cracker on Arduino https://dev.to/lambdamamba/a-badusb-that-is-pretty-useful-making-a-keystroke-injector-in-arduino-that-can-crack-passwords-using-brute-force-3e77 Useful BadUSBs Making a brute force password cracker on ArduinoThis time we will be using the BadUSB made in my previous blog post to crack passwords using brute force Table Of ContentsThe brute force algorithmUsing the BadUSB brute force cracker to actually crack thingsGetting around mechanisms put in place to deter multiple attempts The brute force algorithm We will use the following recursive algorithm to get all combinations of a character set namely for password lengths of Here we assume that characters will be repeated char charset main int len sizeof charset main sizeof char void bruteforce char charset String prev int len int n check if n if n Keyboard println will also enter the value after typing the string out Serial println prev return for each character in charset int i for i i lt len i convert previous charset to String String newprev prev charset i decrement n and recursively call bruteforce bruteforce charset newprev len n void setup void loop n is the length of the password int n for n n lt n try bruteforce for different lengths bruteforce charset main len n This ino file can be found on my Github Once the uploading finishes you can open up the Serial Monitor on Arduino s IDE to see the output The output should look like the following All password combinations that can be made from numbers with the password length of can be seen here on my Github Using brute force to actually crack things Now let s get to the interesting part where we actually start cracking things using the keystroke injector To actually type out the passwords we will be using Keyboard println as this will also enter the password after typing it out For simplicity let s assume we only want to crack systems that uses a digit PIN number as the password so the character set will be char charset main and we will use n for the password length Also we will assume there are no mechanisms in place to block multiple attempts which include stopping reloading resetting after multiple failed attempts We will be making use of the switch mechanism to turn the BadUSB on off as shown in my other previous post Thus we will only start the brute force algorithm when the switch is on void loop check the state of pin whether it is HIGH on or LOW off switchstate digitalRead switchPin if switchstate HIGH n is the length of the password int n bruteforce charset main len n else if switchstate LOW We only want the password cracker to brute force passwords while the switch is on and stop as soon as we turn the switch off We also want it to resume where it left off once we turn the switch back on We will place the while digitalRead switchPin LOW loop in the beginning of the recursive function to indefinitely loop through nothing while the switch is off and exit the loop to continue on to the recursive function once the switch turns back on void bruteforce char charset String prev int len int n while digitalRead switchPin LOW pause exeuction while switch is off after turning the switch on it will resume from where it left off Also the password cracker may not work if the password is typed out and entered too fast so we will use a delay of at least ms between different password attempts The time for the delay can be adjusted as different systems applications will have different time intervals between login attempts check if n if n Keyboard println will also enter the value after typing the string out Keyboard println prev wait at least ms before typing out next password delay return The full code can be found on my Github Turning off unplugging the Arduino will cause the password cracker to restart from The following shows the demo on a text editor Suppose we have a pdf file that we know uses a digit PIN number as its password We can open it up Mac s Preview because it doesn t have mechanisms in place to stop multiple failed attempts Here is a demo when the password is Getting around mechanisms put in place to deter multiple attempts Suppose the application has some mechanisms put in place to deter multiple failed attempts In this example we will be using Chrome s PDF viewer which will ask you to enter after failed login attempts and will reload the browser like shown in the following To get around this we will place a counter variable count When this count gets to the program will press enter using Keyboard println and will wait second for the page to reload before resuming the password cracking int count void bruteforce char charset String prev int len int n while digitalRead switchPin LOW pause exeuction while switch is off after turning the switch on it will resume from where it left off check if n if n Keyboard println will also enter the value after typing the string out Keyboard println prev count if count after third attempt press enter Keyboard println reset the counter count wait second for page to reload delay delay return The full code can be found on my Github The following shows the demo where we are cracking the same pdf file from the previous section and the password is Note that it takes much longer cracking the pdf on Chrome s PDF viewer compared to Mac s Preview There are many other ways apps system can deter multiple failed login attempts so you will need to experiment on different apps systems to find out the best delay timings and how to get around the brute force deterring mechanisms Good luck on making a BadUSB that can be used for password cracking and don t get yourself locked out of your account when attempting to brute force 2022-02-10 11:09:23
海外TECH DEV Community Amazon CloudFront 🌩️ - An Global Edge Network https://dev.to/aws-builders/amazon-cloudfront-an-global-edge-network-1da9 Amazon CloudFront ️ An Global Edge Network DAY Deliver your content like Lightning Mcqueen Amazon CloudFront ️ days of Cloud Day Five Follow Me on TwitterTweet This Blog Read on GitHub Read On iCTPro co nz What is ️Amazon CloudFront Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content such as html css js and image files to your users When users request content that is been delivered via CloudFront the demand is fullfilled through a nearest edge location to archive lowest latency Global Edge NetworkReliable low latency and high throughput network connectivity CloudFront Edge locations are fully redundant multiple GbE parallel fiber that circles the globe and links with tens of thousands of networks for improved origin fetches and dynamic content acceleration Featuresprotection against layer and layer Application amp Network attacksSSL TLS certificates you can create free certificates from Amazon certificate manager and embed to CloudFront Control on accessing the data ex restrict access to only authenticated viewers signed URLs and Signed Cookies Token Authentication Compliance PCI DSS Level HIPAA and ISO ISO IEC SOC and DevOps Fast Change Propagation and InvalidationsCost effective Tutorial PrerequisitesAWS account and Privilage to manage CloudFront and SHost a Static web content in S if you don t know how to here is the tutorial link Lets create our CDN Once you sign in go to ClodFrontStepsScreenshotsClick on to Create distributionName and Update details if you want the orgin to access the content in s via CDN only use OAIHTPPS TLSACM Certificate The certificate must be in the US East N Virginia Region us east Enter CNAME if you wanna serve via custom domain names that you use in URLs for the files served by this distribution Keep everything elseDefaultNow Click Create distribution Wait till the deployment get ️successNow Under Domain Name you will get xxxxxxxxxxxxxx cloudfront net Copy and visit the link you will be able to see the content via CDN If you have added CNAME for your domain update this with your domain provider tadaa congratulations you have successfully configured your first CDN with AWS 2022-02-10 11:04:44
海外TECH DEV Community 'How to learn anything faster!' https://dev.to/khalidhossain/how-to-learn-anything-faster-18d4 x How to learn anything faster x I was revising Front end stuff Was watching advanced CSS topics over and over but at the moment I realize that only following the tutorial isn t enough for me Then I do explore a whole new thing If I do any projects from my own self and at the same time if I apply those properties attributes in my projects from those tutorials I already watched And this time I am catching everything faster 2022-02-10 11:04:43
海外TECH DEV Community Use SvelteKit to create npm packages https://dev.to/dreitzner/use-sveltekit-to-create-npm-packages-3l6i Use SvelteKit to create npm packagesI have been using svelte for about years and have had a lot of fun with it The simplicity of using it or the ability to jump into the REPL and trying out a crazy idea are just some of the great things that make it such a pleasure to use The next big thingAlmost a year ago things were about to get even better SvelteKit the application framework for Svelte apps was announced and entered public beta SvelteKit is to Svelte what Next is to React or Nuxt is to Vue One of the hidden features included with this new tool belt for building Svelte Apps is the command svelte kit package This command will auto generate a package from your src lib folder this is a special folder for your shared code components in SvelteKit that you can publish directly to npm But I am getting ahead of myself Let S look at the steps in more detail Setup your projectTo get started run npm init svelte next my app I would recommend to select the following skeleton projecttypescriptprettiereslintas they should make your live easier especially when working in teams There is one more package you need to add by running npm i D sveltetsxin your my app folder Now you should be set to start with your first changes Good first adaptionsI have developed a mental list of things that I want to do right in the beginning as I tend to forget them when I jump into the thick of things The first thing I take care of is to make some adaptions to the package json Specifically I make sure that the package name is correct had some upsis there It also makes sense to add a namespace I created a svackages organisation for all my svelte packages Other good things to add are the fields repository bugs and license To finish off this part I do a rudimentary documentation in the README md of how my code should work This step is important as it will be the info shown on npm as soon as you publish Ideally I will already add REPL url where my future package will be easy to try out Add your codeThe next part should be the easiest Add all the code that you want to publish in src lib To make it easier on yourself you can use the src routes folder to test out your package This is also a nice way of documenting your package and possibly even publishing it as a standalone site Publish itThe last few steps to get your library published are actually pretty easy run npm run package to generate your packageMake sure that you are logged into npm npm login the last thing to do is to run npm publish package hopefully you have two factor authentication and need to put in your code as well Now you have successfully published your first package with SvelteKit Happy coding and I hope you have learned something Linksrepos with my svelte packagesset focus action on npmset focus action repl 2022-02-10 11:03:11
海外TECH DEV Community My Django Journey https://dev.to/calebcheptumo/my-django-journey-2bpk My Django JourneyIntroductionWhen you are in your twenties especially when you are a technology enthusiast you get plenty of advice notable advice it is problem solving hence very helpful But if you are in you twenties especially when you ae someone who wok in a web development related agency there is a challenge that those advice might not work for the reason it seems to work initially Feel free to question what people tell you and in return challenge yourself by trying different things because in the long un what matters is understanding why something works or doesn t work for you when it comes down to it In the end you come to realize that the advice you got form other people didn t impact you in one way or another Why I choose DjangoI started out as a Django beginner and still one today Being a developer you can never term yourself as an expert because there is a continuous release of updates of your specified stack and new languages Django has a handful benefits that s why I went with it First of all Django is an open source framework which provides an easy and scalable way to create website and web apps in no time Also Django is easy to learn and work with because it is a python framework and since python is a much stable language hence Django inherits a lot of key basics of python therefore a prerequisite of learning Django is having the basic fundamental of python Moreover it is has a huge community support This is because of its availability on GitHub with k contributors For instance you encounter a problem in your Django project and head over to stack overflow for a solution The chances are the problem is already solved by other Django developers in the community and you will get the solution How I startedWhen I discovered Django documentation I was eager and yearning to lean more I love how this documentation is statured In that the first part is about request and response part two entail models and the admin site part three consist of views and handling templates part four has forms and generic views part five deals with testing part six constitute static files while the last part seven is all about customizing the admin site I am impressed how simple and educative this tutorial is If you want to dig into Django without having to go through a lot of hassles on tutorial books online look no further because you are home The following are great resources that helped me become a better Django developer The book that I used was Django for beginner build website with python and Django The YouTube channel for Django tutorials This channel has very helpful videos covering all sorts of topics related to Django Dennis Ivy it s one of my favorites It really enlightened me on the structure of Django its architecture and files handling and functionality Watching his videos gave me a clear picture since it outlines right from the basics fundamentals with side projects to put your knowledge into practice First projectI really enjoy learning new things and I cant get enough of that My first project was a Crud application to implement restful Api which is based on Model View Template MVT that revolves around create retrieve update and delete operations Deployment will be the final step on Heroku but that will be in another blog all together Since my project was to create a Crud application the following are the steps in summary Create a Django projectdjango admin startproject crudwhere crud is the project name Create an apppython manage py startapp apiwhere api is the app name Register the app created in the settings pyIn the app create modelCreate necessary routing and serialization Register the model created in the admin pyMake migrations and migratepython manage py makemigrationspython manage py migrateCreate a super userpython manage py createsuperuserNavigate to the root directory of your project and run the projectpython manage py runserverClick to open on your browser Log in to add some dummy data Go to postman to add data to get request from the client and testing the ApiSo these are the steps I followed creating my first Django project with the help of YouTube tutorial I mention earlier I can confidently say this was my best approach of understanding the framework I may not be an expert yet but I can develop something with the help of Django Thank you for reading I d love to help out more people with Django as much as I can Please don t hesitate to reach out to me if you have any questions or concerns Here is the link for the full article 2022-02-10 11:02:52
海外TECH DEV Community How to add animations to your NativeBase App https://dev.to/nativebase/how-to-add-animations-to-your-nativebase-app-58mn How to add animations to your NativeBase AppIntroductionWhat is the difference between a “Good app and a “Great app When I think about this question a few things come to mind But the one thing that most users will notice and remember is Interaction Animations So in this tutorial we will share with you how to add animations to your NativeBase app using Reanimated What are We CreatingWe will create a Todo app and add interaction animations to it to enhance the user experience To make our Todo app lively and enjoyable we will use the three animations highlighted below Add a small rotate the button on click Change the background color of the completed item when clicked Animating removing items from the list by swiping the item left Implementing Individual AnimationsRotation import Animated useSharedValue useAnimatedStyle withTiming useDerivedValue interpolate withRepeat from react native reanimated const animation useSharedValue const rotation useDerivedValue gt return interpolate animation value const buttonRotation useAnimatedStyle gt return transform rotate rotation value deg const startAnimation gt animation value withRepeat withTiming duration true const buttonRotation useAnimatedStyle gt return transform rotate rotation value deg JSX for button lt TouchableWithoutFeedback onPress gt if inputValue addItem inputValue setInputValue onPressIn startAnimation gt lt Animated View style height width backgroundColor colors primary borderRadius alignItems center justifyContent center paddingHorizontal buttonRotation gt lt Text color white textAlign center fontSize md justifyContent center gt Add Task lt Text gt lt Animated View gt lt TouchableWithoutFeedback gt Rotation can act as the base for tons of cool interactions We used useSharedValue hook from the reanimated library to share the value between the react native UI thread and animation thread To get the transformed shared value if one of the underlying shared value change we have used the useDerivedValue hook We then used the useAniamtedStyle hook to make the association between the shared values and the view properties of add button By clicking on the button the start animation function is called This changes the shared value and all the subsequent changes occur based on the shared value used in animations The video below demonstrates what it looks like Changing of background color on click We inserted this animation to show that a certain task is pending We are changing the background color as shown below to denote the completion of the task Here we are changing the backgroundColor property of the view with some delay animation const colors useTheme const progress useDerivedValue gt return props item isCompleted withTiming duration withTiming duration const rContainreStyle useAnimatedStyle gt const backgroundColor interpolateColor progress value white colors muted return backgroundColor JSX lt Pressable onPress gt props handleStatusChange props itemI gt lt PanGestureHandler onGestureEvent gestureMethod gt lt Animated View style styles containreStyle rContainreStyle gt lt Text fontSize lg px color coolGray gt props item title lt Text gt lt Animated View gt lt PanGestureHandler gt lt Pressable gt useTheme hook offered by NativeBase and allows you to tap into the theming system provided by NativeBase The video below demonstrates this animation Removing the card ️We used this animation to show that once we complete a task we just simply slide the card left With one swipe the card is removed Using PanGestureHandler from react native gesture handler to capture touch event and based on the swipe value assigned we animated the translateX marginVertical opacity and height properties of view import PanGestureHandler from react native gesture handler const SCREENWIDTH Dimensions get window width const TRANSLATEXTHRESHOLD SCREENWIDTH const translateX useSharedValue const MARGIN useSharedValue const CONTAINERHEIGHT useSharedValue const OPACITY useSharedValue const gestureMethod useAnimatedGestureHandler onStart event ctx gt onActive event ctx gt translateX value event translationX onEnd event ctx gt const isDismissed translateX value lt TRANSLATEXTHRESHOLD if isDismissed translateX value withTiming SCREENWIDTH CONTAINERHEIGHT value withTiming MARGIN value withTiming OPACITY value withTiming else translateX value withTiming const rContainreStyle useAnimatedStyle gt const backgroundColor interpolateColor progress value white colors muted return transform translateX translateX value height CONTAINERHEIGHT value opacity OPACITY value marginVertical MARGIN value backgroundColor JSX lt Pressable onPress gt props handleStatusChange props itemI gt lt PanGestureHandler onGestureEvent gestureMethod gt lt Animated View style styles containreStyle rContainreStyle gt lt Text fontSize lg px color coolGray gt props item title lt Text gt lt Animated View gt lt PanGestureHandler gt lt Pressable gt The video below demonstrates the animation ConclusionAnimation plays a very pivotal role in enhancing the overall user experience of any application The experience of a simple application can be improved ten folds by the use of simple animations For achieving that outcome React animated plays an important role NativeBase being an awesome Library offered such a variety to use components and Pseudo props that helped in reducing the code complexity and improving the code quality With the use of NativeBase what we can achieve is something great The experience of using apps essentials in everyday life like the ToDo application can be enhanced incredibly using animations from NativeBase 2022-02-10 11:02:17
Apple AppleInsider - Frontpage News Microsoft announces new App Store pledges, except for Xbox https://appleinsider.com/articles/22/02/10/microsoft-announces-new-app-store-pledges-except-for-xbox?utm_medium=rss Microsoft announces new App Store pledges except for XboxMicrosoft has announced a series of pledges to do with App Store and fair dealing with developers but won t apply major ones to its Xbox store As governments around the world put pressure on Apple and Google over regulating their platforms Microsoft has announced what it calls a principled approach to app stores Specifically done to adapt ahead of regulation Microsoft says its principles address its growing role and responsibility in the market since its acquisition of Activision Blizzard Too much friction exists today between creators and gamers says Microsoft in a blog post app store policies and practices on mobile devices restrict what and how creators can offer games and what and how gamers can play them Read more 2022-02-10 11:16:12
金融 RSS FILE - 日本証券業協会 新規公開に際して行う株券の個人顧客への配分状況 https://www.jsda.or.jp/shiryoshitsu/toukei/shinkikoukai/index.html 新規公開 2022-02-10 13:00:00
ニュース BBC News - Home Ukraine-Russia crisis: Stakes are very high, Boris Johnson says https://www.bbc.co.uk/news/uk-60326142?at_medium=RSS&at_campaign=KARANGA diplomacy 2022-02-10 11:37:45
ニュース BBC News - Home Johnson broke law over No 10 parties, says ex-PM Sir John Major https://www.bbc.co.uk/news/uk-politics-60331189?at_medium=RSS&at_campaign=KARANGA johnson 2022-02-10 11:44:59
ニュース BBC News - Home Met Police: Dame Cressida Dick says she has no intention of quitting https://www.bbc.co.uk/news/uk-england-london-60319838?at_medium=RSS&at_campaign=KARANGA report 2022-02-10 11:39:40
ニュース BBC News - Home Wales' First Minister tests positive for Covid https://www.bbc.co.uk/news/uk-wales-politics-60332828?at_medium=RSS&at_campaign=KARANGA covid 2022-02-10 11:28:18
ニュース BBC News - Home Betty Davis: 'Godmother of Funk' dies aged 77 https://www.bbc.co.uk/news/entertainment-arts-60330415?at_medium=RSS&at_campaign=KARANGA kravitz 2022-02-10 11:23:02
ニュース BBC News - Home Leatherhead restaurant Beluga apologises over 'offensive' dress code https://www.bbc.co.uk/news/uk-england-surrey-60330410?at_medium=RSS&at_campaign=KARANGA clothing 2022-02-10 11:31:43
ニュース BBC News - Home Ireland captain Sexton to miss France game https://www.bbc.co.uk/sport/rugby-union/60331602?at_medium=RSS&at_campaign=KARANGA france 2022-02-10 11:08:48
ビジネス ダイヤモンド・オンライン - 新着記事 来週(2/14~18)の日経平均株価の予想レンジは、 2万7000~2万8500円! 「決算発表のピーク通過」や 「FOMCの議事要旨」により、株価見直しの動きに期待 - 来週の日経平均株価の予想レンジを発表! https://diamond.jp/articles/-/296065 2022-02-10 20:50:00
ビジネス 不景気.com アンジェスの21年12月期は156億円の赤字、売上6400万円 - 不景気.com https://www.fukeiki.com/2022/02/anges-2021-loss.html 医薬品開発 2022-02-10 11:08:28
北海道 北海道新聞 IH女子日本、1時間の氷上練習 格上に「勝ちを意識して」 https://www.hokkaido-np.co.jp/article/644429/ 試合会場 2022-02-10 20:14:00
北海道 北海道新聞 大阪万博、パナや吉本が出展へ 2025年、民間パビリオン https://www.hokkaido-np.co.jp/article/644425/ 大阪万博 2022-02-10 20:10:00
北海道 北海道新聞 「らうす」「うらうす」似てるよね 羅臼、浦臼両町が交流会 https://www.hokkaido-np.co.jp/article/644420/ 根室管内 2022-02-10 20:05:00
ビジネス 東洋経済オンライン 「学校内の居場所」失いかけた人に舞い降りた奇蹟 漫画「君は放課後インソムニア」第1集・第7話 | 君は放課後インソムニア | 東洋経済オンライン https://toyokeizai.net/articles/-/504229?utm_source=rss&utm_medium=http&utm_campaign=link_back 富士山さんは思春期 2022-02-10 20:30:00
海外TECH reddit 自民党の二之湯智さん(国家公安委員長)「国政選挙前に京都で金を配ったが買収はしていない」 https://www.reddit.com/r/newsokuexp/comments/sp4ezf/自民党の二之湯智さん国家公安委員長国政選挙前に京都で金を配ったが買収はしていない/ ornewsokuexplinkcomments 2022-02-10 11:23:31

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)