Category: Web

Web development is the work involved in developing a website for the Internet (World Wide Web) or an intranet (a private network).[1] Web development can range from developing a simple single static page of plain text to complex web applications, electronic businesses, and social network services. A more comprehensive list of tasks to which Web development commonly refers, may include Web engineering, Web design, Web content development, client liaison, client-side/server-side scripting, Web server and network security configuration, and e-commerce development.

  • VS Code for Laravel Development

    VS Code for Laravel Development

    VS Code for Laravel Development

    VS Code is one of the best editors available to developers now, no doubt about it, I always wanted to have such an editor which would support 4/5 languages. Changing your editor or IDE for each language is cumbersome, many of us work on the front-end and backend simultaneously, VSCode solves this problem you can write most of the programming languages available to you.

    Using a single editor or IDE helps you long-term, you get to know the keyboard shortcuts, you save all your snippets in one place, you remember the menu, icons, and other visual stuff, and you find everything easily. Finally, it makes you smarter and gives you a boost in your productivity. Productivity is all you need in software development. Always cut the tools and things you don’t need, you want to complete your tasks efficiently, never use multiple tools for the same task, and never learn sublime and vs code together, learn either of them.

    Laravel is one of the best frameworks for web development, I”‘m pretty sure no other web framework will get this close very soon. Working on a Laravel project in VS Code is pretty fun, it supports most of the things you need and if you install a few more extensions you will do damn good.

    If you need more support for your Laravel projects try https://github.com/barryvdh/laravel-ide-helper
    Just run

    composer require --dev barryvdh/laravel-ide-helper
    
    php artisan ide-helper:generate
    

    You now have the most accurate autocompletion in your VS Code.

    Useful extensions for PHP and Laravel

    Spread the love
  • MySQL RANGE Partition

    MySQL RANGE Partition

    MySQL RANGE Partition

    When partition doesn’t help

    • A lot of relations in the table.
    • A small table and won’t grow in the future.
    • Don’t use a partition unless you have 1M rows.

    It’s tempting to believe that partition will solve performance problems. But it is so often wrong. Partitioning splits up one table into several smaller tables. But table size is rarely a performance issue. Instead, I/O time and indexes are the issues.

    What is Partitioning?

    Partitioning is a physical database design technique that many data modelers and DBAs are quite familiar with. Although partitioning can be used to accomplish a number of various objectives, the main goal is to reduce the amount of data read for particular SQL operations so that overall response time is reduced.

    1. Horizontal Partitioning – this form of partitioning segments table rows so that distinct groups of physical row-based datasets are formed that can be addressed individually (one partition) or collectively (one-to-all partitions). All columns defined to a table are found in each set of partitions so no actual table attributes are missing. An example of horizontal partitioning might be a table that contains ten years worth of historical invoice data being partitioned into ten distinct partitions, where each partition contains a single year’s worth of data
      1. Range – this partitioning mode allows a DBA to specify various ranges for which data is assigned. For example, a DBA may create a partitioned table that is segmented by three partitions that contain data for the 1980’s, 1990’s, and everything beyond and including the year 2000.
      2. Hash – this partitioning mode allows a DBA to separate data based on a computed hash key that is defined on one or more table columns, with the end goal being an equal distribution of values among partitions. For example, a DBA may create a partitioned table that has ten partitions that are based on the table’s primary key.
      3. Key – a special form of Hash where MySQL guarantees even distribution of data through a system-generated hash key.
      4. List – this partitioning mode allows a DBA to segment data based on a pre-defined list of values that the DBA specifies. For example, a DBA may create a partitioned table that contains three partitions based on the years 2004, 2005, and 2006.
      5. Composite – this final partitioning mode allows a DBA to perform sub-partitioning where a table is initially partitioned by, for example range partitioning, but then each partition is segmented even further by another method (for example, hash).
    2. Vertical Partitioning – this partitioning scheme is traditionally used to reduce the width of a target table by splitting a table vertically so that only certain columns are included in a particular dataset, with each partition including all rows. An example of vertical partitioning might be a table that contains a number of very wide text or BLOB columns that aren’t addressed often being broken into two tables that has the most referenced columns in one table and the seldom-referenced text or BLOB data in another.

    Why the Range partition is the best choice in my case

    CREATE TABLE `HISTORY` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `symbol` varchar(16) NOT NULL,
      `open` float DEFAULT NULL,
      `high` float DEFAULT NULL,
      `low` float DEFAULT NULL,
      `close` float DEFAULT NULL,
      `volume` double DEFAULT '0',
      `exchange` varchar(8) NOT NULL,
      `timestamp` int(16) NOT NULL DEFAULT '0',
      `date` varchar(16) DEFAULT NULL,
      `update_date_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `symbol` (`symbol`),
      KEY `exchange` (`exchange`),
      KEY `timestamp` (`timestamp`)
    ) ENGINE=InnoDB AUTO_INCREMENT=144753037 DEFAULT CHARSET=utf8;

    My table structure is very simple. We will store Citigroup Inc daily stock data. Example dataset in CSV.
    Since I have another 30K different company stock data like Citygroup and my total rows of this table is 128,947,460 at this moment. A Range partition is perfect in this case.

    I will partition the table by year, like all the 2018 data in a partition called ‘p_2018’ and for the year 2019 it is ‘p_2019’.

    My primary key is ID which is AUTO_INCREMENT. I have to find the ID of the first trading day of the next year 2019 (1st January), then I can create a partition for all 2018 data. ID 56839003 is the first trading of the year 2019.

    PARTITION p_2018 VALUES less than (56839003)

    Now p_2018 has all the data from 2018, we can create another partition for 2019, 2020, and so on.

    How my existing SQL query gonna affected

    None of your SQL needs to be changed.
    But you can take advantage of the partition by adding your partition name in your SQL SELECT, INSERT queries.

    SELECT * FROM  `HISTORY` PARTITION (`p_2018`) WHERE  `symbol`='C';

    PARTITION SQLs

    SHOW PARTITION

    SHOW CREATE TABLE HISTORY

    ADD PARTITION

    ALTER TABLE `HISTORY` 
    
    PARTITION BY RANGE(`id`) 
    
    (
    
     PARTITION p_2018 VALUES less than (56839003),
    
     PARTITION p_2019 VALUES less than (61466903),
    
     PARTITION p_others VALUES LESS THAN MAXVALUE
    
    );

    DROP PARTITION

    ALTER TABLE t1 DISCARD PARTITION p_2018, p_2019 TABLESPACE;

    DELETE PARTITION

    All partitions

    ALTER TABLE t1 REMOVE PARTITIONING;

    One Partition

    ALTER TABLE t1 DROP PARTITION p_2018, p_2019;

    IMPORT PARTITION

    Import Tablespace Partition

    ALTER TABLE t1 IMPORT PARTITION p_2018, p_2019 TABLESPACE;

    REORGANIZE PARTITION

    ALTER TABLE SIGNALS 
    REORGANIZE PARTITION p_others INTO (
        PARTITION p_2018 VALUES less than (91466903),
        PARTITION p_2019 VALUES LESS THAN MAXVALUE
    );

    SELECT PARTITION

    Rows of each partition using information_schema

    SELECT PARTITION_ORDINAL_POSITION, TABLE_ROWS, PARTITION_METHOD FROM informatio_schema.PARTITIONS WHERE TABLE_SCHEMA = 'table' AND TABLE_NAME = 'HISTORY';

    Few things to remember

    • Duplicate your database before you try any partitions.
    • You have to find your partition method. RANGE partition may not be suitable in your case.
    • Run the same query before and after the partition and compare the time it takes.

    Spread the love
  • Decode Apple Receipt

    Decode Apple Receipt

    Decode Apple Receipt

    Verify with the server-side click here

    /**
     * ***********************************************************************
     *  SMINRANA CONFIDENTIAL
     *   __________________
     *
     * Copyright 2020  SMINRANA
     * All Rights Reserved.
     *
     * NOTICE:  All information contained herein is, and remains
     * the property of SMINRANA and its suppliers,
     * if any.  The intellectual and technical concepts contained
     * herein are proprietary to SMINRANA
     * and its suppliers and may be covered by U.S. and Foreign Patents,
     * patents in process, and are protected by trade secret or copyright law.
     * Dissemination of this information or reproduction of this material
     * is strictly forbidden unless prior written permission is obtained
     * from SMINRANA.
     * www.sminrana.com
     *
     */
    
    import SwiftUI
    import StoreKit
    import Combine
    
    class AppStorageManager: NSObject, ObservableObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
    
        @AppStorage("username") var username: String = ""
        @AppStorage("password") var password: String = ""
        
        override init() {
            super.init()
            
            SKPaymentQueue.default().add(self)
        }
        
        @Published var products = [SKProduct]()
        
        func getProdcut(indetifiers: [String]) {
            print("Start requesting products ...")
            let request = SKProductsRequest(productIdentifiers: Set(indetifiers))
            request.delegate = self
            request.start()
        }
        
    
        // SKProductsRequestDelegate
    
        func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
            print("Did receive response \(response.products)")
                    
            if !response.products.isEmpty {
                for fetchedProduct in response.products {
                    DispatchQueue.main.async {
                        self.products.append(fetchedProduct)
                    }
                }
            }
            
            for invalidIdentifier in response.invalidProductIdentifiers {
                print("Invalid identifiers found: \(invalidIdentifier)")
            }
        }
        
        func request(_ request: SKRequest, didFailWithError error: Error) {
            print("Request did fail: \(error)")
        }
        
    
        // Transaction
        
        @Published var transactionState: SKPaymentTransactionState?
        
        func purchaseProduct(product: SKProduct) {
            if SKPaymentQueue.canMakePayments() {
                let payment = SKPayment(product: product)
                SKPaymentQueue.default().add(payment)
            } else {
                print("User can't make payment.")
            }
        }
    
        func restorePurchase() {
            SKPaymentQueue.default().restoreCompletedTransactions()
        }
        
        struct PaymentReceiptResponseModel: Codable {
            var status: Int
            var email: String?
            var password: String?
            var message: String?
        }
        
        // SKPaymentTransactionObserver
    
    
        // This gets called when transaction purchased by user
        func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
            for transaction in transactions {
                switch transaction.transactionState {
                case .purchasing:
                    self.transactionState = .purchasing
                case .purchased:
                    print("===============Purchased================")
                    UserDefaults.standard.setValue(true, forKey: transaction.payment.productIdentifier)
    
                    if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
                        FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
    
                        do {
                            let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
                            let receiptString = receiptData.base64EncodedString(options: [])
                            
                           // Send receiptString to server for further verification
                        }
                        catch { print("Couldn't read receipt data with error: " + error.localizedDescription) }
                    }
    
                case .restored:
                    UserDefaults.standard.setValue(true, forKey: transaction.payment.productIdentifier)
    
                    queue.finishTransaction(transaction)
                    print("==================RESTORED State=============")
                    self.transactionState = .restored
                case .failed, .deferred:
                    print("Payment Queue Error: \(String(describing: transaction.error))")
                    queue.finishTransaction(transaction)
                    self.transactionState = .failed
                default:
                    print(">>>> something else")
                    queue.finishTransaction(transaction)
                }
            }
        }
        
        // This gets called when a transaction restored by user
        func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
            print("===============Restored================")
            if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
                FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
    
                do {
                    let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
                    let receiptString = receiptData.base64EncodedString(options: [])
                    
                    // Send receiptString to server for further verification
                }
                catch { print("Couldn't read receipt data with error: " + error.localizedDescription) }
            }
        }
        
      
    }
    
    Spread the love