# All# python# wedfg# scope variable# interview# lexical environment# javascript# #algorithm# hoisting# good# print# java# coding shortcut# competitive coding# shorthand# loop tricks# sample# #c# gambling# primitives# algoritms# arrow-functions# javascriptintro# usefullinks# technical round# project# beetroot# reverse# array# copy# collection# test# i am printing hello world# #class# #js# #interview# map# lodash# scoping# async# prime numbers# python journey# weather app# easy way to remove duplicates# # #javascript# pho# possible ways of calculator app# var a = 10 function f(){ console.log(a) } f(); console.log(a);# gg# bank# as# palindrome# hello world basic intro# #python# pattern program# nodejs# key# concept of var, let and const# #helloworld# please give better ans# php# hello world# code review# string# d# javascript functions# fusionauth# c++# helloworld# hello, world# forloop# slice# adding two numbers# diamond# @python3# #python3# arraylistcourceimplemetnation# cpp# work# auto screenshot# #dsa# #recursion# #array# #java# bday# int number; : this line declares a variable to store the integer input the user# game# woocommerce# some testing publish# ios

Latest from community today

<?php

namespace Bmimd\Controllers;

use WP_Error;

class WoocommerceController {
    public static function init() {
        self::comunicate_paused_subscriptions_to_front_api();
    }

    private static function comunicate_paused_subscriptions_to_front_api() {
        add_action( 'send_data_to_api_action', [self::class, 'send_data_to_api_handler'] );
        add_action( 'woocommerce_subscription_status_updated', [ self::class, 'notify_front_api_about_subscription_paused' ], 10, 3 );
    }

    public static function send_data_to_api_handler( $args ) {
        /**
         * Get the endpoint and data.
         */
        $email  = $args[ 'email' ];
        $body   = $args[ 'body' ];

        /**
         * Call the api.
         */
        $response = self::notify_front_api( $email, $body ); 

        /**
         * If response is not wp error then return.
         */
        if( true === $response ){
            return;
        }
        
        /**
         * Check for errors.
         */
        if( is_wp_error( $response ) ){
            /**
             * Get the error code.
             */
            $error_code = $response->get_error_code();

            /**
             * Do not keep trying if the errors was not due a connection problem.
             */
            if( 'http_request_failed' !== $error_code ){
                return;
            }
        }
    
        /**
         * Try to resend the data again using an exponential backoff strategy.
         *
         * Get the attempt number.
         */
        $attempts = $args['attempts'] ?? 0;

        /**
         * Define the new retry time.
         * 
         * Retry after 1 minute, then 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 ,etc
         */
        $retry_time = time() + ( 60 * ( 2 ** $attempts ) );

        /**
         * Stop attempting if the attempts are 10 or more (roughly 17 hours).
         */
        if( $attempts < 10 ){
            /**
             * Update attempts.
             */
            $args['attempts']++;

            as_schedule_single_action( $retry_time, 'send_data_to_api_action', [ 'args' => $args ] );
        }
    }

    private static function notify_front_api( string $email, array $body ): bool|WP_Error {    
        /**
         * Get the api endpoint.
         */
        $api_url = 'https://api2.frontapp.com/contacts/alt:email:' . $email;
        $api_key = 'my-api-key';
        
        /**
         * Prepare the args.
         */
        $args = [
            'body'    => wp_json_encode( $body ),
            'headers' => [
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $api_key,
            ],
            'method'  => 'PATCH',
        ];

        /**
         * Send the request.
         */
        $response = wp_remote_request( $api_url, $args );

        /**
         * Check for errors.
         */
        if( is_wp_error( $response ) ) {
            $error_code     = $response->get_error_code();
            $error_message  = 'Error notifying Front API: ' . $response->get_error_message();

            /**
             * Log the incident.
             */
            error_log( $error_message );

             /**
              * Rerturn a wp error.
              */
            return new \WP_Error( $error_code, $error_message );
        }

        /**
         * Get the response code.
         */
        $response_code = wp_remote_retrieve_response_code( $response );
        if( $response_code !== 204 ) {
            /**
             * Get the error message.
             */
            $response_body = wp_remote_retrieve_body( $response );
            $error_message = 'Unexpected response code: ' . $response_code . ' with message: ' . $response_body;

            /**
             * Log the incident.
             */
            error_log( $error_message );
            return new \WP_Error( 'api_error', $error_message );
        }

        /**
         * Return true on success.
         */
        return true;        
    }

    public static function notify_front_api_about_subscription_paused( $subscription, $new_status, $old_status ) {
        /**
         * Check if the new status is 'on-hold' or 'paused'.
         */
        if ( $new_status !== 'on-hold' ) {
            return;
        }

        /**
         * Get user data.
         */
        $user_id    = $subscription->get_user_id();
        $user_info  = get_userdata( $user_id );
        $email      = $user_info->user_email;

        /**
         * Return if we can't get user's email.
         */
        if( !$email || !is_email( $email ) ){
            return;
        }       
        
        /**
         * Prepare the data to send.
         */
        $args =[
            'email' => $email,
            'body'  => [
                'custom_fields'     => [
                    'subscribed'    => 'false'
                ],
            ]
        ];

        /**
         * Call the function that makes the API request.
         */
        as_enqueue_async_action( 'send_data_to_api_action', [ 'args' => $args ] );
    }
}
enum GameLevel {
  easy = 'easy',
  hard = 'hard',
}

interface IGameObjects {
  mobs: number;
  health: number;
  supplies: number;
}
function generateMap(Objects: IGameObjects) {
  console.log(JSON.stringify(Objects));
}

function generateMapByLevel(level: GameLevel) {
  if (level === GameLevel.easy) {
    generateMap({
      mobs: 10,
      health: 100,
      supplies: 20,
    });
  } else if (level === GameLevel.hard) {
    generateMap({
      mobs: 20,
      health: 50,
      supplies: 10,
    });
  }
}

generateMapByLevel(GameLevel.easy);
public class AutoScreenShot extends javax.swing.JFrame {
    protected Toolkit toolkit = Toolkit.getDefaultToolkit();
    protected Dimension dim = toolkit.getScreenSize();
    protected int resulationH = dim.height;
    protected int resulationW = dim.width;
    //...
    private static boolean isTray = false, flag = false, close = false, bnClick = false, activated = false;
    private int xx, yy;
    private static int counterN = 1;
    protected static String fileName = "";
    private String pathF = "";
    
    public AutoScreenShot() {
        initComponents();
    }
    
    public void loading(){
        int ww = 770;
        int hh = 610;
        ln.setBounds((resulationW / 2) - (ww / 2), (resulationH / 2) - (hh / 2), ww, hh );
        ln.setResizable(false);
        //ln.setUndecorated(true);
        //ln.getContentPane().setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
        ln.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
        
        //...
        MaxLengthDocument txt1 = new MaxLengthDocument(10, MaxLengthDocument.IGNORE);
        MaxLengthDocument txt2 = new MaxLengthDocument(6, MaxLengthDocument.NUMBER);
        fNameTxt.setDocument(txt1);
        fCounterStartTxt.setDocument(txt2);
        fNameTxt.setText("Pic");
        fCounterStartTxt.setText("000001");
        fCounterLb.setText("000001");
        //...
        listener();
        //...
        bnStartPic.setVisible(false);
        bnPausePic.setVisible(false);
        //...
        try
        {
            ln.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Pic/icon.png")));
        }catch(Exception e)
        {
            System.out.println("error 4-1 in load icon Pic...!" + e.getMessage());
        }

        ln.setVisible(true);
        fNameTxt.requestFocus();
        fNameTxt.selectAll();
    }
  
    private void StartApp(){
        System.out.println("Start..");
        
                try
                {
                    fileName = fNameTxt.getText();
                    try 
                    {
                        errLb.setText("");
                        //...folder & file
                        JFileChooser fc = new JFileChooser(pathF);
                        fc.setDialogTitle("Select your Folder ");
                        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                        //...
                        if  (0 == fc.showOpenDialog(fc))
                        {
                            pathF = fc.getSelectedFile().getPath()+"\\";
                            pathLb.setText(pathF);
                        }
                        //...
                    } catch (Exception e) {
                        System.out.println("error in Select Folder!");    
                    }

                    if (!pathF.equals("") && !pathF.equals("C:\\\\"))
                    {
                        //...
                        GlobalScreen.registerNativeHook();
                        GlobalScreen.addNativeKeyListener(new NativeKeyListener()
                        {

                            @Override
                            public void nativeKeyTyped(NativeKeyEvent nativeEvent)
                            {
                            }

                            @Override
                            public void nativeKeyReleased(NativeKeyEvent nativeEvent)
                            {
                            }

                            @Override
                            public void nativeKeyPressed(NativeKeyEvent nativeEvent)
                            {
                                int a = nativeEvent.getKeyCode();
                                if (flag && a == 3639 && activated)
                                {
                                    flag = false;
                                    //...
                                    try 
                                    {
                                        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
                                        ImageIO.write(image, "png", new File(pathF + fileName + " " + String.format("%06d", counterN++) + ".png"));
                                    } catch (Exception ex) {
                                        System.out.println("Error in create file..");
                                    }
                                    System.out.println("ScreenShot Get "+ fileName + " " + fCounterLb.getText());

                                }
                                //...
                                if (close && a == 62)
                                {
                                    close = false;
                                    ln.setVisible(true);
                                    isTray = false;
                                }

                                //...
                                if (nativeEvent.getKeyCode()==3613)
                                    flag = true;
                                if (nativeEvent.getKeyCode()==29)
                                    close = true;

                            }
                        });
                    }else
                    {
                        bnStartPic.setVisible(true);
                        bnPausePic.setVisible(false);
                        activated = false;
                    }
                
                }catch(Exception e)
                {
                    System.out.println("Error..");
                }
//            }
//        });
    }
    
           
}
public class bday {

    public static void main(String[] args) {
      String name = "Afsara"; // Replace with the actual name
  
      // Sorting Hat announcement
      System.out.println("*Sorting Hat placed upon head dramatically* The Sorting Hat deliberates... \n");
      try {
        Thread.sleep(1500); 
      } catch (InterruptedException e) {
        System.out.println("Merlin's beard! A rogue Snitch just interrupted the ceremony! But fear not, the feast awaits!\n");
      }
      System.out.println("Ah, finally! Happy Birthday, Dr. " + name + ", a true " + getHouse() + "!"); 
    
      String message;
      if (Math.random() > 0.5) { 
        message = "\nIt is rumored that Dr. " + name + " possesses a hidden talent for " 
               + getMagicalSkill() + ". Perhaps a trip to Diagon Alley is in order?";
      } else {
        message = "So "+name + ", on this momentous occasion, you are hereby granted one wish! Just be careful what you ask for, you might just get a Boggart in your birthday cake!";
      }
      
      System.out.println(message);
      System.out.println("\nMay your birthday be filled with delicious Pumpkin Juice, exciting Quidditch matches (avoid rogue Bludgers!), and of course, the company of loved ones. Happy Birthday, " + "brooo" + "!");
    }
  
    public static String getHouse() {
      String[] houses = {"Gryffindor", "Ravenclaw", "Hufflepuff", "Slytherin"}; //try running again :b
      return houses[(int) (Math.random() * houses.length)];
    }
  
    public static String getMagicalSkill() {
      String[] skills = {"Herbology mastery", "Potion brewing proficiency", "Transfiguration brilliance", "Parseltongue (be careful who you talk to!)"};
      return skills[(int) (Math.random() * skills.length)];
    }
  }
  
<?php

function distributeTask(int $m, int $n): int {
    if ($n > 0) {
        return intdiv($m, $n); // Используем функцию intdiv для получения целой части от деления
    } else {
        // Генерируем исключение, если количество сотрудников равно нулю, чтобы избежать деления на ноль
        throw new Exception("Количество сотрудников должно быть больше нуля.");
    }
}

// Окно для использования функции
$m = 1800; // Общее количество задач
$n = 10;   // Количество сотрудников

try {
    $tasksPerEmployee = distributeTask($m, $n);
    echo "Каждый сотрудник получит $tasksPerEmployee задач(и).";
} catch (Exception $e) {
    echo "Ошибка: " . $e->getMessage();
}

?>
import java.util.Scanner;

public class nQueens {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        printNqueens(new int[n][n], "", 0);
    }
    public static boolean isSafe(int [][] chess, int row, int col){
        for(int i = row - 1, j = col ; i >= 0; i--){
            if(chess[i][j] == 1){
                return false;
            }
        }
        for(int i = row - 1, j = col + 1; i >=0 && j < chess.length; i--, j++){
            if(chess[i][j] == 1){
                return false;
            }
        }
        for(int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--){
            if(chess[i][j] == 1){
                return false;
            }
        }
        return true;
    }
    public static void printNqueens(int[][] chess, String pos, int row){
        if(row == chess.length){
            System.out.println(pos + ".");
            return;
        }
        for(int col = 0; col < chess.length; col++){
            if(isSafe(chess, row, col)){
                chess[row][col] = 1;
                printNqueens(chess, pos + row + "-" + col + ", ", row + 1);
                chess[row][col] = 0;
            }
        }
    }
}

Featured content