text:
Q: Composite key on table where primary key is also foreign key? I have table item_image:
create table item_image
(
    item_id bigint        not null
        constraint item_image_pk
            primary key
        constraint item_image_item_fk
            references item,
    location  varchar(1000) not null,
    path      varchar(1000) not null,
    file_name varchar(200)  not null
);

And mapped it to entity:
@Entity
@Table(name = "item_image", schema = "public")
public class ItemImageEntity implements Serializable {

    @Id
    @OneToOne
    @JoinColumn(name = "item_id")
    private ItemEntity item;

    private String location;
    private String path;
    private String fileName;

    // getters and setters
}

My item entity has:
@OneToOne(mappedBy = "item")
private ItemImageEntity profileImage;

in it, the postgress table does not contain refference to this item_image, only vice versa.
When i try to run the app i get:

@EnableJpaRepositories declared on
JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: This class [ItemImageEntity] does
not define an IdClass

Why do i need to define IdClass and How? Since i have only 1 primary key.
Thanks for help!

A: *

*It's issue that you want to add primary key of entity without real primary key, hibernate can't identify itemEntity. (Do you have item_id field?)

*About @IdClass - Hibernate can't identify class as field and think that you can use inner fields as primary key.


text:
Q: How can an OCaml module export a field defined in a dependent module? I have a decomposition where module A defines a structure type, and exports a field of this type which is defined as a value in module B:
a.ml:
type t = {
  x : int
}

let b = B.a

b.ml:
open A (* to avoid fully qualifying fields of a *)
let a : t = {
  x = 1;
}

Circular dependence is avoided, since B only depends on type declarations (not values) in A.
a.mli:
type t = {
  x : int
}

val b : t

As far as I know, this should be kosher. But the compiler errors out with this:
File "a.ml", line 1, characters 0-1:
Error: The implementation a.ml does not match the interface a.cmi:
       Values do not match: val b : A.t is not included in val b : t

This is all particularly obtuse, of course, because it is unclear which val b is interpreted as having type t and which has type A.t (and to which A--the interface definition or the module definition--this refers).
I'm assuming there is some arcane rule (along the lines of the "structure fields must be referenced by fully module-qualified name when the module is not opened" semantics which bite every OCaml neophyte at some point), but I am so far at a loss.

A: Modules in the microscope are more subtle than it appears
(If your eyes glaze over at some point, skip to the second section.)
Let's see what would happen if you put everything in the same file. This should be possible since separate computation units do not increase the power of the type system. (Note: use separate directories for this and for any test with files a.* and b.*, otherwise the compiler will see the compilation units A and B which may be confusing.)
module A = (struct
    type t = { x : int }
    let b = B.a
  end : sig
    type t = { x : int }
    val b : t
  end)
module B = (struct
    let a : A.t = { A.x = 1 }
  end : sig
    val a : A.t
  end)

Oh, well, this can't work. It's obvious that B is not defined here. We need to be more precise about the dependency chain: define the interface of A first, then the interface of B, then the implementations of B and A.
module type Asig = sig
    type t = { x : int }
    type u = int
    val b : t
  end
module B = (struct
    let a : Asig.t = { Asig.x = 1 }
  end : sig
    val a : Asig.t
  end)
module A = (struct
    type t = { x : int }
    let b = B.a
  end : Asig)

Well, no.
File "d.ml", line 7, characters 12-18:
Error: Unbound type constructor Asig.t

You see, Asig is a signature. A signature is a specification of a module, and no more; there is no calculus of signatures in Ocaml. You cannot refer to fields of a signature. You can only refer to fields of a module. When you write A.t, this refers to the type field named t of the module A.
In Ocaml, it is fairly rare for this subtlety to arise. But you tried poking at a corner of the language, and this is what's lurking there.
So what's going on then when there are two compilation units? A closer model is to see A as a functor which takes a module B as an argument. The required signature for B is the one described in the interface file b.mli. Similarly, B is a function which takes a module A whose signature is given in a.mli as an argument. Oh, wait, it's a bit more involved: A appears in the signature of B, so the interface of B is really defining a functor that takes an A and produces a B, so to speak.
module type Asig = sig
    type t = { x : int }
    type u = int
    val b : t
  end
module type Bsig = functor(A : Asig) -> sig
    val a : A.t
  end
module B = (functor(A : Asig) -> (struct
    let a : A.t = { A.x = 1 }
  end) : Bsig)
module A = functor(B : Bsig) -> (struct
    type t = { x : int }
    let b = B.a
  end : Asig)

And here, when defining A, we run into a problem: we don't have an A yet, to pass as an argument to B. (Barring recursive modules, of course, but here we're trying to see why we can't get by without them.)
Defining a generative type is a side effect
The fundamental sticking point is that type t = {x : int} is a generative type definition. If this fragment appears twice in a program, two different types are defined. (Ocaml takes steps and forbids you to define two types with the same name in the same module, except at the toplevel.)
In fact, as we've seen above, type t = {x : int} in a module implementation is a generative type definition. It means "define a new type, called d, which is a record type with the fields …". That same syntax can appear in a module interface, but there it has a different meaning: there, it means "the module defines a type t which is a record type …".
Since defining a generative type twice creates two distinct types, the particular generative type that is defined by A cannot be fully described by the specification of the module A (its signature). Hence any part of the program that uses this generative type is really using the implementation of A and not just its specification.
When you get down to it, defining a generative type it is a form of side effect. This side effect happens at compile time or at program initialization time (the distinction between these two only appears when you start looking at functors, which I shall not do here.) So it is important to keep track of when this side effect happens: it happens when the module A is defined (compiled or loaded).
So, to express this more concretely: the type definition type t = {x : int} in the module A is compiled into "let t be type #1729, a fresh type which is a record type with a field …". (A fresh type means one that is different from any type that has ever been defined before.). The definition of B defines a to have the type #1729.
Since the module B depends on the module A, A must be loaded before B. But the implementation of A clearly uses the implementation of B. The two are mutually recursive. Ocaml's error message is a little confusing, but you are indeed outstepping the bounds of the language.

A:
(and to which A--the interface definition or the module definition--this refers).

A refers to the whole module A. With the normal build procedure it would refer to the implementation in a.ml contrained by signature in a.mli. But if you are playing tricks moving cmi's around and such - you are on your own :)

As far as I know, this should be kosher.

I personally qualify this issue as circular dependency and would stay strongly against structuring the code in such a way. IMHO it causes more problems and head-scratching, than solving real issues. E.g. moving shared type definitions to type.ml and be done with it is what comes first to mind. What is your original problem that leads to such structuring?

redpajama_set_name: RedPajamaStackExchange


text:
Q: TideSDK app on Mac I developed an app via TideSDK on OSX. I have a .app and It is working on OSX. However, you know it cannot work on linux or windows. I want to run my app on linux or windows. How can I do that?

A: In short, you package for each platform. As you are aware mac apps do not run on Windows and it is the same with TideSDK since you are creating something native for each platform.
TideSDK must be installed on each platform to create an executable and bundle for it.
To generate an installer for each system, you need to run commands on each system (windows / linux 32bit / linux 64bit) using tidebuilder.py on the command line.
We will have more to speak about concerning packaging quite soon that will make the task of building and distributing your apps easier. Stay tuned for updates !!


text:
Q: Whats wrong with the curly braces why it didn't work? import java.util.Scanner;
public class ATM {
static Scanner console = new Scanner(System.in);

public static void main(String[] args) {

    int Account01 = 3000;
    int Account02 = 2000;
    int Account03 = 1000;
    String username;
    int pin, transaction, counter=1, menu, chooseAccount;
    int withdraw_amount, deposited_amount, transfer_amount, transfer_account = 0;

    do{
        System.out.print("Enter username: ");
        username = console.next();

        System.out.print("Enter PIN: ");
        pin = console.nextInt();

        if ((username.equalsIgnoreCase("Account01")) && (pin == 1234 ))
        {
            System.out.println("PIN Accepted");
            System.out.println("\n\nSelect a menu:");
            System.out.println("[1] Balance Inquiry\n[2] Withdrawal\n[3] Deposit\n[4] Transfer Amount");
            System.out.print("\nEnter your choice: ");
            menu = console.nextInt();
            do{
                if (menu == 1)
                {
                    System.out.print("\n\nBALANCE INQUIRY");
                    System.out.print("\nYour Current Balance is: " + Account01);
                }

                else if (menu ==2)
                {
                    do{
                        System.out.print("\n\nWITHDRAWAL");
                        System.out.print("\nEnter amount: ");
                        withdraw_amount = console.nextInt();
                        if(((withdraw_amount % 100) == 0) && ( (withdraw_amount >= 200) &&
                                (withdraw_amount <= Account01) && (withdraw_amount <= 10000) ))
                        {
                            Account01 = Account01 - withdraw_amount;
                            break;
                        }
                        // error catching
                        if(counter<3)
                            System.out.println("Error: Incorrect amount!\n");
                        else{
                            System.out.println("Card has been captured!");
                            break;
                        }
                        counter++;
                    }while(counter<=3);

                }

                else if (menu == 3)
                {
                    do
                    {
                        System.out.print("\n\nDEPOSIT");
                        System.out.print("\nEnter amount: ");
                        deposited_amount = console.nextInt();
                        if( ((deposited_amount % 100) == 0) && (deposited_amount <= 10000) )
                        {
                            Account01 = Account01 + deposited_amount;
                            break;
                        }
                        // error catching
                        if(counter < 3)
                            System.out.println("Error: Incorrect amount.\n");
                        else
                        {
                            System.out.println("Card has been captured.");
                            break;
                        }
                        counter++;
                    }while(counter <= 3);
                }

                else if (menu == 4)
                {

                    do{
                        System.out.print("\n\nTRANSFER PAYMENT");
                        System.out.print("\nEnter amount: ");
                        transfer_amount = console.nextInt();
                        System.out.print("[1] account01\n[2] account02\n[3] account03\n");
                        System.out.print("Chose account: ");
                        chooseAccount = console.nextInt();
                        if(chooseAccount == 1)
                        {
                            transfer_account = Account01;
                        }
                        else if(chooseAccount == 2)
                        {
                            transfer_account = Account02;
                        }
                        else if(chooseAccount == 3)
                        {
                            transfer_account = Account03;
                        }
                        else System.out.println("invalid number entered.");

                        if( ((transfer_amount % 100) == 0) && (transfer_amount <= 10000) )
                        {
                            Account01 = Account01 - transfer_amount;
                            transfer_account = transfer_account + transfer_amount;
                            break;
                        }
                        // error catching
                        if(counter < 3)
                            System.out.println("Error: Incorrect amount.\n");
                        else
                        {
                            System.out.println("Card has been captured.");
                            break;
                        }
                        counter++;
                    }while(counter <= 3);
                }

                System.out.println("\n\n\nDo you want another transaction?\nType [1] if YES. Type [2] if NO");
                System.out.print("\nEnter your choice: ");
                transaction = console.nextInt();
                if (transaction == 1)
                {
                    System.out.println("\n\nSelect a menu:");
                    System.out.println("[1] Balance Inquiry\n[2] Withdrawal\n[3] Deposit\n[4] Transfer Amount");
                    System.out.print("\nEnter your choice: ");
                    menu = console.nextInt();
                    do{
                        if (menu == 1)
                        {
                            System.out.print("\n\nBALANCE INQUIRY");
                            System.out.print("\nYour Current Balance is: " + Account01);
                        }

                        else if (menu ==2)
                        {
                            do{
                                System.out.print("\n\nWITHDRAWAL");
                                System.out.print("\nEnter amount: ");
                                withdraw_amount = console.nextInt();
                                if(((withdraw_amount % 100) == 0) && ( (withdraw_amount >= 200) &&
                                        (withdraw_amount <= Account01) && (withdraw_amount <= 10000) ))
                                {
                                    Account01 = Account01 - withdraw_amount;
                                    break;
                                }
                                // error catching
                                if(counter<3)
                                    System.out.println("Error: Incorrect amount!\n");
                                else{
                                    System.out.println("Card has been captured!");
                                    break;
                                }
                                counter++;
                            }while(counter<=3);
                        }

                        else if (menu == 3)
                        {
                            do
                            {
                                System.out.print("\n\nDEPOSIT");
                                System.out.print("\nEnter amount: ");
                                deposited_amount = console.nextInt();
                                if( ((deposited_amount % 100) == 0) && (deposited_amount <= 10000) )
                                {
                                    Account01 = Account01 + deposited_amount;
                                    break;
                                }
                                // error catching
                                if(counter < 3)
                                    System.out.println("Error: Incorrect amount.\n");
                                else
                                {
                                    System.out.println("Card has been captured.");
                                    break;
                                }
                                counter++;
                            }while(counter <= 3);
                        }

                        else if (menu == 4)
                        {

                            do{
                                System.out.print("\n\nTRANSFER PAYMENT");
                                System.out.print("\nEnter amount: ");
                                transfer_amount = console.nextInt();
                                System.out.print("[1] account01\n[2] account02\n[3] account03\n");
                                System.out.print("Chose account: ");
                                chooseAccount = console.nextInt();
                                if(chooseAccount == 1)
                                {
                                    transfer_account = Account01;
                                }
                                else if(chooseAccount == 2)
                                {
                                    transfer_account = Account02;
                                }
                                else if(chooseAccount == 3)
                                {
                                    transfer_account = Account03;
                                }
                                else System.out.println("invalid number entered.");

                                if( ((transfer_amount % 100) == 0) && (transfer_amount <= 10000) )
                                {
                                    Account01 = Account01 - transfer_amount;
                                    transfer_account = transfer_account + transfer_amount;
                                    break;
                                }
                                // error catching
                                if(counter < 3)
                                    System.out.println("Error: Incorrect amount.\n");
                                else
                                {
                                    System.out.println("Card has been captured.");
                                    break;
                                }
                                counter++;
                            }while(counter <= 3);
                        }
                else
                {
                    System.out.println("\nThank You!!!\nGood Bye!!!");
                }
                break;

            }while((menu >= 1) && (menu <= 4));
            break;
        }

        else if ((username.equalsIgnoreCase("Account02")) && (pin == 4321))
        {
            System.out.println("PIN Accepted");
            System.out.println("\n\nSelect a menu:");
            System.out.println("[1] Balance Inquiry\n[2] Withdrawal\n[3] Deposit\n[4] Transfer Amount");
            System.out.print("\nEnter your choice: ");
            menu = console.nextInt();
            do{
                if (menu == 1)
                {
                    System.out.print("\n\nBALANCE INQUIRY");
                    System.out.print("\nYour Current Balance is: " + Account02);
                }

                else if (menu ==2)
                {
                    do{
                        System.out.print("\n\nWITHDRAWAL");
                        System.out.print("\nEnter amount: ");
                        withdraw_amount = console.nextInt();
                        if(((withdraw_amount % 100) == 0) && ( (withdraw_amount >= 200) &&
                                (withdraw_amount <= Account02) && (withdraw_amount <= 10000) ))
                        {
                            Account02 = Account02 - withdraw_amount;
                            break;
                        }
                        // error catching
                        if(counter<3)
                            System.out.println("Error: Incorrect amount!\n");
                        else{
                            System.out.println("Card has been captured!");
                            break;
                        }
                        counter++;
                    }while(counter<=3);

                }

                else if (menu == 3)
                {
                    do
                    {
                        System.out.print("\n\nDEPOSIT");
                        System.out.print("\nEnter amount: ");
                        deposited_amount = console.nextInt();
                        if( ((deposited_amount % 100) == 0) && (deposited_amount <= 10000) )
                        {
                            Account02 = Account02 + deposited_amount;
                            break;
                        }
                        // error catching
                        if(counter < 3)
                            System.out.println("Error: Incorrect amount.\n");
                        else
                        {
                            System.out.println("Card has been captured.");
                            break;
                        }
                        counter++;
                    }while(counter <= 3);
                }

                else if (menu == 4)
                {

                    do{
                        System.out.print("\n\nTRANSFER PAYMENT");
                        System.out.print("\nEnter amount: ");
                        transfer_amount = console.nextInt();
                        System.out.print("[1] account01\n[2] account02\n[3] account03\n");
                        System.out.print("Chose account: ");
                        chooseAccount = console.nextInt();
                        if(chooseAccount == 1)
                        {
                            transfer_account = Account01;
                        }
                        else if(chooseAccount == 2)
                        {
                            transfer_account = Account02;
                        }
                        else if(chooseAccount == 3)
                        {
                            transfer_account = Account03;
                        }
                        else System.out.println("invalid number entered.");

                        if( ((transfer_amount % 100) == 0) && (transfer_amount <= 10000) )
                        {
                            Account02 = Account02 - transfer_amount;
                            transfer_account = transfer_account + transfer_amount;
                            break;
                        }
                        // error catching
                        if(counter < 3)
                            System.out.println("Error: Incorrect amount.\n");
                        else
                        {
                            System.out.println("Card has been captured.");
                            break;
                        }
                        counter++;
                    }while(counter <= 3);
                }

                System.out.println("\n\n\nDo you want another transaction?\nType [1] if YES. Type [2] if NO");
                System.out.print("\nEnter your choice: ");
                transaction = console.nextInt();
                if (transaction == 1)
                {
                    System.out.println("\n\nSelect a menu:");
                    System.out.println("[1] Balance Inquiry\n[2] Withdrawal\n[3] Deposit\n[4] Transfer Amount");
                    System.out.print("\nEnter your choice: ");
                    menu = console.nextInt();
                    do{
                        if (menu == 1)
                        {
                            System.out.print("\n\nBALANCE INQUIRY");
                            System.out.print("\nYour Current Balance is: " + Account02);
                        }

                        else if (menu ==2)
                        {
                            do{
                                System.out.print("\n\nWITHDRAWAL");
                                System.out.print("\nEnter amount: ");
                                withdraw_amount = console.nextInt();
                                if(((withdraw_amount % 100) == 0) && ( (withdraw_amount >= 200) &&
                                        (withdraw_amount <= Account02) && (withdraw_amount <= 10000) ))
                                {
                                    Account02 = Account02 - withdraw_amount;
                                    break;
                                }
                                // error catching
                                if(counter<3)
                                    System.out.println("Error: Incorrect amount!\n");
                                else{
                                    System.out.println("Card has been captured!");
                                    break;
                                }
                                counter++;
                            }while(counter<=3);

                        }

                        else if (menu == 3)
                        {
                            do
                            {
                                System.out.print("\n\nDEPOSIT");
                                System.out.print("\nEnter amount: ");
                                deposited_amount = console.nextInt();
                                if( ((deposited_amount % 100) == 0) && (deposited_amount <= 10000) )
                                {
                                    Account02 = Account02 + deposited_amount;
                                    break;
                                }
                                // error catching
                                if(counter < 3)
                                    System.out.println("Error: Incorrect amount.\n");
                                else
                                {
                                    System.out.println("Card has been captured.");
                                    break;
                                }
                                counter++;
                            }while(counter <= 3);
                        }

                        else if (menu == 4)
                        {

                            do{
                                System.out.print("\n\nTRANSFER PAYMENT");
                                System.out.print("\nEnter amount: ");
                                transfer_amount = console.nextInt();
                                System.out.print("[1] account01\n[2] account02\n[3] account03\n");
                                System.out.print("Chose account: ");
                                chooseAccount = console.nextInt();
                                if(chooseAccount == 1)
                                {
                                    transfer_account = Account01;
                                }
                                else if(chooseAccount == 2)
                                {
                                    transfer_account = Account02;
                                }
                                else if(chooseAccount == 3)
                                {
                                    transfer_account = Account03;
                                }
                                else System.out.println("invalid number entered.");

                                if( ((transfer_amount % 100) == 0) && (transfer_amount <= 10000) )
                                {
                                    Account02 = Account02 - transfer_amount;
                                    transfer_account = transfer_account + transfer_amount;
                                    break;
                                }
                                // error catching
                                if(counter < 3)
                                    System.out.println("Error: Incorrect amount.\n");
                                else
                                {
                                    System.out.println("Card has been captured.");
                                    break;
                                }
                                counter++;
                            }while(counter <= 3);
                }
                else
                {
                    System.out.println("\nThank You!!!\nGood Bye!!!");
                }
                break;

            }while((menu >= 1) && (menu <= 4));
            break;
        }

        else if ((username.equalsIgnoreCase("Account03")) && (pin == 5555))
        {
            System.out.println("PIN Accepted");
            System.out.println("\n\nSelect a menu:");
            System.out.println("[1] Balance Inquiry\n[2] Withdrawal\n[3] Deposit\n[4] Transfer Amount");
            System.out.print("\nEnter your choice: ");
            menu = console.nextInt();
            do{
                if (menu == 1)
                {
                    System.out.print("\n\nBALANCE INQUIRY");
                    System.out.print("\nYour Current Balance is: " + Account03);
                }

                else if (menu ==2)
                {
                    do{
                        System.out.print("\n\nWITHDRAWAL");
                        System.out.print("\nEnter amount: ");
                        withdraw_amount = console.nextInt();
                        if(((withdraw_amount % 100) == 0) && ( (withdraw_amount >= 200) &&
                                (withdraw_amount <= Account03) && (withdraw_amount <= 10000) ))
                        {
                            Account03 = Account03 - withdraw_amount;
                            break;
                        }
                        // error catching
                        if(counter<3)
                            System.out.println("Error: Incorrect amount!\n");
                        else{
                            System.out.println("Card has been captured!");
                            break;
                        }
                        counter++;
                    }while(counter<=3);

                }

                else if (menu == 3)
                {
                    do
                    {
                        System.out.print("\n\nDEPOSIT");
                        System.out.print("\nEnter amount: ");
                        deposited_amount = console.nextInt();
                        if( ((deposited_amount % 100) == 0) && (deposited_amount <= 10000) )
                        {
                            Account03 = Account03 + deposited_amount;
                            break;
                        }
                        // error catching
                        if(counter < 3)
                            System.out.println("Error: Incorrect amount.\n");
                        else
                        {
                            System.out.println("Card has been captured.");
                            break;
                        }
                        counter++;
                    }while(counter <= 3);
                }

                else if (menu == 4)
                {

                    do{
                        System.out.print("\n\nTRANSFER PAYMENT");
                        System.out.print("\nEnter amount: ");
                        transfer_amount = console.nextInt();
                        System.out.print("[1] account01\n[2] account02\n[3] account03\n");
                        System.out.print("Chose account: ");
                        chooseAccount = console.nextInt();
                        if(chooseAccount == 1)
                        {
                            transfer_account = Account01;
                        }
                        else if(chooseAccount == 2)
                        {
                            transfer_account = Account02;
                        }
                        else if(chooseAccount == 3)
                        {
                            transfer_account = Account03;
                        }
                        else System.out.println("invalid number entered.");

                        if( ((transfer_amount % 100) == 0) && (transfer_amount <= 10000) )
                        {
                            Account03 = Account03 - transfer_amount;
                            transfer_account = transfer_account + transfer_amount;
                            break;
                        }
                        // error catching
                        if(counter < 3)
                            System.out.println("Error: Incorrect amount.\n");
                        else
                        {
                            System.out.println("Card has been captured.");
                            break;
                        }
                        counter++;
                    }while(counter <= 3);
                }

                System.out.println("\n\n\nDo you want another transaction?\nType [1] if YES. Type [2] if NO");
                System.out.print("\nEnter your choice: ");
                transaction = console.nextInt();
                if (transaction == 1)
                {
                    System.out.println("\n\nSelect a menu:");
                    System.out.println("[1] Balance Inquiry\n[2] Withdrawal\n[3] Deposit\n[4] Transfer Amount");
                    System.out.print("\nEnter your choice: ");
                    menu = console.nextInt();
                    do{
                        if (menu == 1)
                        {
                            System.out.print("\n\nBALANCE INQUIRY");
                            System.out.print("\nYour Current Balance is: " + Account03);
                        }

                        else if (menu ==2)
                        {
                            do{
                                System.out.print("\n\nWITHDRAWAL");
                                System.out.print("\nEnter amount: ");
                                withdraw_amount = console.nextInt();
                                if(((withdraw_amount % 100) == 0) && ( (withdraw_amount >= 200) &&
                                        (withdraw_amount <= Account03) && (withdraw_amount <= 10000) ))
                                {
                                    Account03 = Account03 - withdraw_amount;
                                    break;
                                }
                                // error catching
                                if(counter<3)
                                    System.out.println("Error: Incorrect amount!\n");
                                else{
                                    System.out.println("Card has been captured!");
                                    break;
                                }
                                counter++;
                            }while(counter<=3);

                        }

                        else if (menu == 3)
                        {
                            do
                            {
                                System.out.print("\n\nDEPOSIT");
                                System.out.print("\nEnter amount: ");
                                deposited_amount = console.nextInt();
                                if( ((deposited_amount % 100) == 0) && (deposited_amount <= 10000) )
                                {
                                    Account03 = Account03 + deposited_amount;
                                    break;
                                }
                                // error catching
                                if(counter < 3)
                                    System.out.println("Error: Incorrect amount.\n");
                                else
                                {
                                    System.out.println("Card has been captured.");
                                    break;
                                }
                                counter++;
                            }while(counter <= 3);
                        }

                        else if (menu == 4)
                        {

                            do{
                                System.out.print("\n\nTRANSFER PAYMENT");
                                System.out.print("\nEnter amount: ");
                                transfer_amount = console.nextInt();
                                System.out.print("[1] account01\n[2] account02\n[3] account03\n");
                                System.out.print("Chose account: ");
                                chooseAccount = console.nextInt();
                                if(chooseAccount == 1)
                                {
                                    transfer_account = Account01;
                                }
                                else if(chooseAccount == 2)
                                {
                                    transfer_account = Account02;
                                }
                                else if(chooseAccount == 3)
                                {
                                    transfer_account = Account03;
                                }
                                else System.out.println("invalid number entered.");

                                if( ((transfer_amount % 100) == 0) && (transfer_amount <= 10000) )
                                {
                                    Account03 = Account03 - transfer_amount;
                                    transfer_account = transfer_account + transfer_amount;
                                    break;
                                }
                                // error catching
                                if(counter < 3)
                                    System.out.println("Error: Incorrect amount.\n");
                                else
                                {
                                    System.out.println("Card has been captured.");
                                    break;
                                }
                                counter++;
                            }while(counter <= 3);
                }
                else
                {
                    System.out.println("\nThank You!!!\nGood Bye!!!");
                }
                break;

            }while((menu >= 1) && (menu <= 4));
            break;
        }

        else if ((username.equalsIgnoreCase("x")) && (pin == 0000))
        {
            System.out.println("Program will be terminated!");
            break;
        }
        // error catching
        if(counter<3)
            System.out.println("Error: Incorrect username or password.\n");
        else{
            System.out.println("Card has been captured!");
            System.out.println("\n\nDo you want to continue?\nType [1] if YES. Type [2] if NO ");
            System.out.print("Enter your choice: ");
            transaction = console.nextInt();
            if (transaction == 1)
            {
                System.out.println("\n\nInsert your card.");
                System.out.print("\nEnter username: ");
                username = console.next();

                System.out.print("Enter PIN: ");
                pin = console.nextInt();

            }
            else
            {
                System.out.println("\nThank You!!!\nGood Bye!!!");
            }
            break;
        }

        counter++;
    }while(counter<=3);
}

}
I'm making an atm machine program. What wrong with my program why it didn't work? Any suggestions guys? I really need to work this out though, I need it tom! :(

A: Your code won't compile, because you used a do{}while loop which has a general form:
do {
 statement(s)
} while (expression);

and you didn't add a expression part in three of them (from a beginning of code) .
You write statements without expressions.
I don't know your code, but it is enough to add:
                        }while(true);
                    }
                }while(true);
            }
        }while(true);
    }
}

to compile it.
However you should seriously think about dividing your code between multiple classes and methods, because it is very hard to read and maintain (as you probably know).


text:
Q: I cannot get structure members in auto-completion or tooltips I want autocomplete or company to work with C code and I need structure context level autocomplete i.e if I have a struct:
typefdef struct HOST_ {

    IP4_ADDRESS     ip4;
    IP6_ADDRESS     ip6;
    MAC_ADDRESS     mac;
} HOST;

... and then I have code:
HOST host;

host->

Then if I hit tab then I should get a drop down menu giving me all the (and only the) three options.
This is what I did:
(defun my-tab-del-commands(key-map)
  "This function sets the <tab> and <backspace> keymaps according to the special commands
that I have set. This needs to be set per mode keymap where it is needed. We cannot
use the global keymap because that would override command completion in minibuffer"

  ;; Set TAB in  major-mode keymap to "tab-to-tab" stop
  ;; Use tab2tab stop and not just add +4 spaces (tab stop defined by tag-stop-list)
  (define-key key-map (kbd "<tab>")     'tab-to-tab-stop)

  ;; Define Key for <backtab>
  (define-key key-map (kbd "<S-tab>")   'backward-move-to-tab-stop)
  (define-key key-map (kbd "<backtab>") 'backward-move-to-tab-stop)

  ;; Define C-tab as my-indent-system
  (define-key key-map (kbd "<C-tab>")   'my-indent-system)
  ;; Also provide a duplicate "\C-ci" in case C-TAB is overridden by any minor mode
  (define-key emacs-lisp-mode-map "\C-ci"   'my-indent-system)

  ;; Shift backspace moves by one tab stop till no more whitespace
  (define-key key-map (kbd "<S-backspace>") 'backspace-whitespace-to-tab-stop)

  ;; Alt backspace is c-hungry-delete-backwards
  (define-key key-map (kbd "<M-backspace>") 'c-hungry-delete-backwards)
  )

;; Simple Backend of semantic with ede as project manager
;; Lets try semantic (CDET) backend for now only.
;; Later learn clang or rtags or other big stuff to handle the whole project
(defun backend:semantic-ede ()
  "Setup for semantic-mode with ede as project management.
Simple stuff for starters"

  (semantic-mode 1)

  (global-semanticdb-minor-mode 1)
  (global-semantic-idle-scheduler-mode 1)
  (setq-mode-local c-mode semanticdb-find-default-throttle
                   '(project unloaded system recursive))
  (semantic-add-system-include my-lp-build-path)
  (semanticdb-enable-gnu-global-databases 'c-mode t)
  (semanticdb-enable-gnu-global-databases 'c++-mode t)

  (require 'ede)
  (global-ede-mode)

  (let ((makefile (format "%s/Makefile" my-mp-source-path)))
    (when (file-exists-p makefile)
      (ede-cpp-root-project "openflow" :file makefile)))
  )

;; There are two "schools of thought" of intelligent autocomplete
;; (a) auto-complete package and (b) company package.

;; This is auto-complete
(defun completion:auto-complete ()
  "Setup auto-complete with triggers. We still need to hook with C mode"

  ;; Then autocomplete
  (require 'auto-complete)
  (require 'auto-complete-config)
  (global-auto-complete-mode t)

  ;; auto complete mod
  ;; should be loaded after yasnippet so that they can work together

  (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
  (ac-config-default)

  (add-hook 'auto-complete-mode-hook 'ac-common-setup)

  ;; set the trigger key so that it can work together with yasnippet on tab key,
  ;; if the word exists in yasnippet, pressing tab will cause yasnippet to
  ;; activate, otherwise, auto-complete will
  (ac-set-trigger-key "TAB")
  (ac-set-trigger-key "<tab>")
  (global-auto-complete-mode t)

)

(defun my-smart-c-auto-complete()
  ;; Now tie up autocomplete with semantic
  ;; Later hook it up to c-mode-hook via c-mode-config func
  (require 'auto-complete-c-headers)
  (add-to-list 'ac-sources 'ac-source-words-in-same-mode-buffers)
  (add-to-list 'ac-sources 'ac-source-dictionary)
  (add-to-list 'ac-sources 'ac-source-abbrev)

  (add-to-list 'ac-sources 'ac-source-semantic)
  (add-to-list 'ac-sources 'ac-source-c-headers)
)

;; This is company
(defun completion:company ()
    "Setup comany mode"
    (require 'company)
    (add-hook 'after-init-hook 'global-company-mode)
)

(defun tab-side-story ()
  (interactive)

  ;; First load and init Yasnippet - This sets the TAB first to Ysnippet
  ;; This will work on LISP & SHELL SCRIPTS also

  ;; (require 'yasnippet)
  ;; (yas-global-mode 1)

  ;; Second, use whatever completion mechanism you wanna use auto-complete or company
  ;; This will work on LISP also!
  ;;(completion:auto-complete)
  (completion:company)

  ;; Then this function sets tab command
  (my-tab-del-commands c-mode-base-map)

)

;; Completion mechanism needs a backend
(backend:semantic-ede)
(tab-side-story)

;; define My Great C style with linux as the parent style (choose google if you wish)
(c-add-style "my-great-c-style"
             '("linux"              ; use linux as parent style
               (indent-tabs-mode . nil)     ; tabs are spaces
               (c-syntactic-indentation . t)    ; auto-syntax
               (c-syntactic-indentation-in-macros . t) ; ditto for macros
               (c-tab-always-indent . nil) ; Otherwise our complex TAB will not work!
               (tab-width   .  4)           ; if there is a <tab> expand to 4 spaces
               (backward-delete-function . nil)     ; DO NOT expand tabs when deleting
               (c-continued-statement-offset . 4))) ;continued statement offset 4

(defun my-c-mode-config ()
  (c-set-style "my-great-c-style")
  (when (= emacs-major-version 23)
    (gtags-mode 1))
   (when (= emacs-major-version 24)
    (tab-side-story)
    ;; (my-smart-c-auto-complete)
    (ggtags-mode 1)
    (setq ggtags-update-on-save nil))
  (electric-indent-mode)
  (setq c-basic-offset   4)
  (setq c-tab-always-indent nil))

;; Needs to be hooked - do it here instead of common area
(add-hook 'c-mode-hook 'my-c-mode-config)

Sorry for the very long code but most of them are my comments and notes jotted down so far less "code" than it seems. In this I have set it for company mode though I have auto-complete.
Both are not working! Something is clashing with something.


text:
Q: Why check_icmp plugin from centreon isn't working? I am trying to create a custom command in centreon like
 $USER1$/check_icmp -H $HOSTADDRESS$

however before that I just want to test this plugin (that comes with centreon) in my console. For that I write
 ./check_icmp 127.0.0.1

and, for some reason I have a Segmentation fault error.
However yesterday I have tried this command and got
./check_icmp 127.0.0.1
OK - 127.0.0.1 rta 0.033ms lost 0%|rta=0.033ms;200.000;500.000;0;
rtmax=0.054ms;;;; rtmin=0.023ms;;;; pl=0%;40;80;0;100

When I screen my plugins in centreon they appear in red for some reason (maybe due to the s flag)

What might be wrong?


text:
Q: How to source from online cpp open source like github from Rstudio? I am trying to source code that exists on an online repository by:
Rcpp::sourceCpp(
 url("https://github.com/slwu89/MCMC/blob/master/adaptMCMC_source.cpp")
)

I'm encounter this issue:

Error in dirname(file) : a character vector argument expected

A: Just use R's download.file():
library(Rcpp)
remurl <- "https://github.com/slwu89/MCMC/blob/master/adaptMCMC_source.cpp"
locfile <- "/tmp/mcmc.cpp"
download.file(url=remurl, destfile=locfile)
sourceCpp(locfile)   # dozens of error for _this_ file

Edit Here is a better way with two important fixes:

*

*You need a different URL. The one you list will download the html page.  But you want raw source code, which in this case is https://raw.githubusercontent.com/slwu89/MCMC/master/adaptMCMC_source.cpp

*You can create a simple helper function which takes the url, creates a tempfile with extension .cpp (hey, that argument once was my patch to base R ;-) and then returns that file name.

See below:
u2f <- function(url) {
   tf <- tempfile()
   download.file(url, tf, quiet=TRUE)
   tf
}
library(Rcpp)
url <- "https://raw.githubusercontent.com/slwu89/MCMC/master/adaptMCMC_source.cpp"
sourceCpp( u2f( url ) )

and that compiles fine (albeit with warnings about signed/unsigned comparison).


text:
Q: How do I create dropdown with checkbox by bootstrap multiselect? I am working on MVC 5, there is have

  @Html.DropDownListFor(model => model.ShowAdConfigIDs, ViewData["Services"] as List<SelectListItem>, "Select", new { @id = "DDLServiceCate", @class = "form-control " })

I want to do bootstrap multiselect dropdown with checkbox. For, I have tried:

<script src="~/Scripts/bootstrap-multiselect.js"></script>
<link href="~/css/bootstrap-multiselect.css" rel="stylesheet" />

<script type="text/javascript">
    $(function () {
        $('[id*=DDLServiceCate]').multiselect({
            includeSelectAllOption: true
        });
    });
</script>

But after implementing this, look like below image.

But actually I want look like below image showing.

How can I do this ?

A: You can use this plugin.
Multiple Select (MultiSelect)
This is the working fiddle.
Here is a working sample

<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('#lstFruits').multiselect({
            includeSelectAllOption: true
        });

        $('#btnSelected').click(function () {
            var selected = $("#lstFruits option:selected");
            var message = "";
            selected.each(function () {
                message += $(this).text() + " " + $(this).val() + "\n";
            });
            alert(message);
        });
    });
</script>

<body>
    <select id="lstFruits" multiple="multiple">
        <option value="1">Mango</option>
        <option value="2">Apple</option>
        <option value="3">Banana</option>
        <option value="4">Guava</option>
        <option value="5">Orange</option>
    </select>
    <input type="button" id="btnSelected" value="Get Selected" />
</body>

</html>

A: I have done,

<script src="~/Scripts/bootstrap-multiselect.js"></script>
    <link href="~/css/bootstrap-multiselect.css" rel="stylesheet" />

<script type="text/javascript">
  $(function () {
        $('[id*=DDLServiceCate]').multiselect({
            includeSelectAllOption: true, buttonWidth: '200px'
        });
    });
</script>

And Inside drowpdown I have added '@multiple = "multiple"'

@Html.DropDownListFor(model => model.ShowAdConfigIDs, ViewData["Services"] as List<SelectListItem>, "None selected ", new { @id = "DDLServiceCate", @class = "form-control", @multiple = "multiple" })

Now showing checkboxes inside drowpdownlistfor.


text:
Q: Read/Write users properties I would like to know if is possible read/write data from/to azure active directory ad by Javascript.
I read that there are REST services on Azure but the main issue is generate the token to talk with that and it seems that JS library doesn't exist for that.

A: Yes, there is such service. It is called Windows Azure Active Directory Graph API.
It is REST based and one can authenticate via OAuth to use it. Please note that currently the Resource Owner Password Flow is not supported in WAAD, but the regular token based authentication is. What you will need is:

*

*Get an overview of the Graph API here.

*Create an application inside Azure AD so that you get an application credentials to use with the Graph API (tutorial here)

*Find some good JavaScript library that can generate OAuth headers (you can start here).

UPDATE
Actually you can't query the graph API from JavaScript as there is not CORS support for it. The only CORS supported services are Azure Mobile Services and Azure Storage. Which makes the use of a middle tier "service proxy" inevitable.
The only "JavaScript" stuff that will work with WAAD (Windows Azure AD) is the developer preview of ADAL for Windows Store.
As for where to keep OAuth key and secret everyone shall use their imagination. I never mentioned neither suggested to keep these on the client.


text:
Q: Why Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Application' not found I have a Laravel/Homestead project that is finally working locally.  Now I'm trying to port it over to HostGator and can't get it running due to titled error.  I've tried all the suggested solutions to no avail.  Including:
composer require laravel/laravel
composer dump-autoload
composer install --no-scripts
composer update
composer update --no-scripts

Nothing works.  Same error.  If this is a clue, I also tried
php artisan clear-compiled

and get response of

Could not open input file: artisan

I'm about ready to give up on Laravel/Homestead.  I've spent countless hours on this framework with nothing but problems to show for it.  Would not recommend it to anybody.
You can see the error yourself here:
http://www.tekknow.net/MedAverter/medaverter/
Any suggestions before I throw in the towel?

A: For the artisan file, the artisan file is not required through includes, you have it in your root project, which is created when you create your Laravel project. Here is the file.
So you need to have that file in your project.
For the missing class, you try to require laravel/laravel but that is not the correct dependency. Again that github repo is a shell for a project, to have Laravel features you need to base of laravel/laravel and include laravel/framework.
Hope this clears up some confusing and can get you on the right track. Secondly you shouldn't port it over, but simply cloning your project and running composer install should be sufficient.

A: The problem turned out to be two issues.
1. The wrong version of PHP was running.  If I ssh'ed into the hostgator server and did
php -v

It showed PHP 5.6.30 even though I had selected Php 7.1 in the cPanel PHP Selector.  If I did
tekknow.net/phpinfo.php

it would say I was using 7.1.  Called up HostGator tech support and they were able to change it to PHP 7.3.13.
Now if I do:
php artisan clear cache

I no longer get the error about

Parse error: syntax error, unexpected '?' in
  /home1/sl1k7f3j/public_html/medaverter/bootstrap/app.php on line 15

which was an error caused by a version of php that doesn't support the ?? operator.

*The second problem was a lack of memory issue.  If I did
composer update
It would start to work but would fail in about 30 seconds with

Fatal error: Out of memory (allocated 709623808) (tried to allocate
  34187559 bytes) in
  phar:///opt/cpanel/composer/bin/composer/src/Composer/Json/JsonFile.php
  on line 270

The HostGator tech rep could not figure out why that was happening but I got around that issue by manually uploading my local vendor folder to the host server.
Now when I go to http://tekknow.net/medaverter/ it works!


text:
Q: Sqitch - single plan row, multiple sql files I'm looking to move to sqitch, but my team likes their migrations as multiple files. That is, for example, if we create a foreign key and create an index in the same jira ticket, we like PROJ-123-create-fk.sql and PROJ-123-create-index.sql.
I'd like to keep a single row in the sqitch.plan file, so that each jira ticket corresponds to a single row.
Basically, short of adding lines to sqitch.plan, can I do this? Is there a way to "include" other sql files from a master one? Something like
PROJ-123-main.sql
\include PROJ-123-create-fk.sql
\include PROJ-123-create-index.sql

Thanks so much!

A: The \ir psql directive solved this for me.
in PROJ-123-deploy.sql
\ir PROJ-123-create-fk.sql
\ir PROJ-123-create-index.sql

If the fk and index sql files are in the same directory, they will be executed.

A: Since you want to store it as a single line in the plan file, it doesn't quite match, but I will explain the method we use below. Maybe there are parts that you want to use in it.
There is a similar situation in my team, but we use sqitch tags. Each version of our application corresponds to a subtask. And each task corresponds to a tag. We create sql files as many as the number of subtasks. Then we combine them in a tag that we created with the name of the main task. In our CI/CD pipeline that we use for the database, we also provide the transition between versions with tags. I wanted to add this method here in case anyone prefers to use a similar structure.

Simple example;
Let's have v2.0 of our application installed and a new table and an index are required for v2.1
We create two subtasks named create table and create index under the main task named v2.1
We create two sql files;
app_v2.1_table_create.sql to create a table, app_v2.1_index_create.sql to create an index.
After that, we create a sqitch tag called v2.1. Notice it has the same name as the main task.


text:
Q: state are being updated before reducer is update the state I'm using userReducer to manage user state across the app but while updating the state using reducer the state is updates before reducer is able to update it.
Inspect
here you can see that the previous state variable is updated to new value in payload.
store.js
import { compose, applyMiddleware } from "redux";
import { legacy_createStore as createStore } from "redux";

import { logger } from "redux-logger";
import { rootReducer } from "./rootReducer";

export const store = createStore(rootReducer,applyMiddleware(logger));

rootReducer.js
import { combineReducers } from "redux";
import { postReducer } from "./posts/posts.reducer";
import { userReducer } from "./user/user.reducer";

export const rootReducer = combineReducers({
  post: postReducer,
  user:userReducer
});

userReducer
import { User_Action_Types } from "./user.types";

const INITIAL_STATE = {
  data: {
  _id: "",
  name: "",
  email: "",
  password: "",
},
};

export const userReducer = (state = INITIAL_STATE, action) => {
  const { type, payload } = action;
  console.log({ action, state });
  switch (type) {
    case User_Action_Types.SetUser: {
      state.data = payload;
      return state;
    }
    case User_Action_Types.ResetUser: {
      return INITIAL_STATE;
    }

    default:
      return state;
  }
};

I tried to change actions then reinstalled the modules but nothing worked.
Please help to fix the issue.

A: current your mutating state return new state in reducer
case User_Action_Types.SetUser: {

      return {
             ...state,
             data: payload
      };
    }


text:
Q: .NET Core website shutting down unexpectedly I've got a .NET Core website hosted by IONOS on Windows which seemingly shuts down unexpectedly at random.
I'm logging the following events as well as all incoming requests:

*

*IHostApplicationLifetime.ApplicationStarted

*IHostApplicationLifetime.ApplicationStopping

*IHostApplicationLifetime.ApplicationStopped

As a result, I can see that my website restarts after receiving the following request:
http://127.0.0.1:37065/iisintegration

I've got no idea which process is behind this request, however given it uses 127.0.0.1 as the IP address, it must be local to the server.
Does anyone know anything about requests to iisintegration? Is it part of the ASP.NET Core stack? Any idea who might be sending such request? Could it be specific to IONOS? (their support is unhelpful).
Maybe relevant, here's the content of my web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MyApplication.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

I don't think it's related to IIS idle timeout: one request would be served successfully, then the next second I would see the application stopping.


text:
Q: requests_html returns black     Python 3.8.2 (default, Apr  8 2020, 14:31:25)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from requests_html import HTMLSession
>>> session = HTMLSession()
>>> r = session.get('https://www.sahibinden.com/ilan/emlak-konut-gunluk-kiralik-holiday-business-suit-lux-otel-konforunda-suit-daireler-803346031/detay')
>>> r.html.find("#classifiedId")
[]

I ran this code but the output is empty. I tried r.html.render() but result didn't change. I also tried finding it with xpath but still no result. How can I fix that?

A: The site needs that you specify User-Agent and a cookie named "s3IssGuY1". If this cookie needs to be changed over time (and when) I don't know, but you can change it accordingly (from Firefox/Chrome developer tools):
import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0'}
url = 'https://www.sahibinden.com/ilan/emlak-konut-gunluk-kiralik-holiday-business-suit-lux-otel-konforunda-suit-daireler-803346031/detay'
cookies = {'s3IssGuY1': 'A_Lne-ByAQAAWJ_crjFYgFyVj0loVQQA3jwlYwVTH-vnpfLSbIkEJkwRS9NDAVX4a-mcuNvjwH8AADQwAAAAAA=='}
soup = BeautifulSoup(requests.get(url, headers=headers, cookies=cookies).content, 'html.parser')

for st, sp in zip(soup.select('.classifiedInfoList strong'), soup.select('.classifiedInfoList span')):
    print('{:<30} {}'.format(st.get_text(strip=True), sp.get_text(strip=True)))

Prints:
İlan No                        803346031
İlan Tarihi                    23 Haziran 2020
Emlak Tipi                     Günlük Kiralık Daire
m² (Brüt)                      35
m² (Net)                       30
Oda Sayısı                     Stüdyo (1+0)
Bulunduğu Kat                  5
Kat Sayısı                     5
Isıtma                         Merkezi
Banyo Sayısı                   1
Site İçerisinde                Hayır
Kimden                         Emlak Ofisinden

A: If the browser does not require you to open or not, you can use selenium to open your system browser and be able to access the element directly.
first:
you need to install chrome or firefox driver
second:
need to install selenium in your python with pip
third:
in your texteditor or ide write these code
from selenium import webdriver
from time import sleep

driver = webdriver.FireFox(executable_path="your driver path in your pc or laptop")
driver.get("your url")

sleep(10)

elem = driver.find_element_by_xpath("use xpath here")

print(elem.text)

driver.close()


text:
Q: Most frequent value (mode) by group I am trying to find the most frequent value by group. In the following example dataframe:
df<-data.frame(a=c(1,1,1,1,2,2,2,3,3),b=c(2,2,1,2,3,3,1,1,2))
> df
  a b
1 1 2
2 1 2
3 1 1
4 1 2
5 2 3
6 2 3
7 2 1
8 3 1
9 3 2

I would like to add a column 'c' which has the most occurring value in 'b' when its values are grouped by 'a'. I would like the following output:
> df
  a b c
1 1 2 2
2 1 2 2
3 1 1 2
4 1 2 2
5 2 3 3
6 2 3 3
7 2 1 3
8 3 1 1
9 3 2 1

I tried using table and tapply but didn't get it right. Is there a fast way to do that?
Thanks!

A: We could get the 'Mode' of 'b' grouped by 'a' using ave
 Mode <- function(x) {
 ux <- unique(x)
 ux[which.max(tabulate(match(x, ux)))]
}

df$c <-  with(df, ave(b, a, FUN=Mode))
df$c
#[1] 2 2 2 2 3 3 3 1 1

Or using data.table
library(data.table)
setDT(df)[, c:= Mode(b), by=a][]

A: Building on Davids comments your solution is the following:
Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

library(dplyr)
df %>% group_by(a) %>% mutate(c=Mode(b))

Notice though that for the tie when df$a is 3 then the mode for b is 1.

A: Here is a base R method that uses table to calculate a cross tab, max.col to find the mode per group, and rep together with rle to fill in the mode across groups.
# calculate a cross tab, frequencies by group
myTab <- table(df$a, df$b)
# repeat the mode for each group, as calculated by colnames(myTab)[max.col(myTab)]
# repeating by the number of times the group ID is observed
df$c <- rep(colnames(myTab)[max.col(myTab)], rle(df$a)$length)

df
  a b c
1 1 2 2
2 1 2 2
3 1 1 2
4 1 2 2
5 2 3 3
6 2 3 3
7 2 1 3
8 3 1 2
9 3 2 2

Note that this assumes the data has been sorted by group. Also, the default of max.col is to break ties (mulitple modes) at random. If you want the first or last value to be the mode, you can set this using the ties.method argument.


text:
Q: Customise email before sending I am recoding a friend's artist/client booking system.  I have little experience in programming, enough understanding to hack my way through and google has been a great help!
I've spent the last 3 days reading and searching... Havn't found anything on that... Maybe I'not using the proper terms....
Here's what I want to do.
I use Google Script and google spreadsheet.  1 row contains all the information about a specific contract.

*

*I want to be able to use a menu item to generate the contract (completed)

*Open 2 browser window

*

*one to display the Contract PDF file  ( completed )

*one for a GMAIL New email

*

*with the contract pdf attached  ( completed )

*generated email body  from selected row in the spreadsheet( completed )

*be able to customize the generated email text before
sending it. Adding attachements...

This is what I'm stucked at.  I use

MailApp.sendEmail('xxx@yyy.com', 'transfer email as pdf : body
  & attachment', 'see attachment', {attachments:[body_to_send]});

It send's the email ok, with attachement and generated body and all... but no way to edit the email before sending...
Is that possible with google script?

A: Explore the UiApp class in Google Apps Script. UiApp
You could build a simple UI where the user can enter additional content and upload files, which can then be appended to the email before sending.
It doesn't look like Apps Script supports creating email drafts, which would also provide a way for you to edit emails before sending them.  (Sending an email to yourself with a fancy way to reference the ultimate recipient is another possibility using the native Gmail UI.)
Is this in the direction you were thinking?

A: The last step of your process can be achieved using a Google Doc template in which you can add whatever you want to improve presentation.
From there you get an html version of your doc and use it as a html body in your mail.
If you need more details about html import you'll find it easily on this forum and on the issue tracker.
You could also run this code from a document bound script in a sidebar which would be visually more convenient. (see my recent posts about mailmerge).


text:
Q: Workflow to send email to user once "assigned to" field is set by manager I'm trying to create a workflow that as a step will email the user that gets set in the field "assigned to" on a task list. This will not be set by the creator, it will be set after the item is created.
Most solutions I've found reference using a "wait for field change in current item" step but in SP 2013 you can only have "equal" rather than setting it to "is not null" and have to select a user which we won't know who the user is.
The last comment in this thread seems promising but I'm having no luck with it? This thread also seems like a decent idea, but my "assigned to" field will not be populated to start with and I'm having no luck comparing null fields to each other.
Has anyone had any experience building a workflow like this?
UPDATE
Here's what I was able to get working in my environment.

Thanks!

A: If you want to pursue this approach could try this trick.  Create a dummy variable and set it equal to the Assigned To field but as a text string.  Then you are able to test the 'is empty' against the dummy variable and apply your logic whether to email or not.  It would give you some measure of control over what the user sees when they are assigned the task.
The solution in this thread has a bit more detail on the approach.
Quantifying "NULL" in Sharepoint Designer 2013

A: If you use a task list, then whenever a task is assigned to someone, an email is sent automatically to the assignee.
This behavior is configurable from list settings > advanced settings


text:
Q: Is there a way not to do Popup animation? In kivy popup, I see that I can control whether it would do the animation or not by declaring
popup.open(animation=False) or popup.dismiss(animation=False)
However, when I am not manually controlling the open and dismiss, I can't find a way to not do the animation.
Here is some code from ModalView,
which is a parent class for Popup
def dismiss(self, *largs, **kwargs):
    '''Close the view if it is open. If you really want to close the
    view, whatever the on_dismiss event returns, you can use the *force*
    argument:
    ::

        view = ModalView()
        view.dismiss(force=True)

    When the view is dismissed, it will be faded out before being
    removed from the parent. If you don't want animation, use::

        view.dismiss(animation=False)

    '''
    if self._window is None:
        return
    if self.dispatch('on_dismiss') is True:
        if kwargs.get('force', False) is not True:
            return
    if kwargs.get('animation', True):
        Animation(_anim_alpha=0., d=self._anim_duration).start(self)
    else:
        self._anim_alpha = 0
        self._real_remove_widget()

Like I have mentioned, I can do popup.dismiss(animation=False) to not run animation. However, I can't find a way to put a parameter in when I do auto dismiss(touching outside of the popup).
Is there a way to do so without touching ModalView source itself?

Summary: how do I not do animation when I auto dismiss a pop up?

A: I could solve this problem by inheriting dismiss() from ModalView
class PopupNoAnimation(Popup):
    def __init__(self, **kwargs):
        super(PopupNoAnimation, self).__init__(**kwargs)

    def dismiss(self, *largs, **kwargs):
        if self._window is None:
            return
        if self.dispatch('on_dismiss') is True:
            if kwargs.get('force', False) is not True:
                return

        self._anim_alpha = 0
        self._real_remove_widget()

Now, dismiss doesn't create an Animation object, which results in no animation on dismiss.


text:
Q: Front-end form submission not creating post I'm trying to use a front end form to create a post. I've been trying for a while now but I the post is not created. I'm using the code below, i'm not sure if i've forgot something.
<?php Starkers_Utilities::get_template_parts( array( 'parts/shared/html-header','parts/shared/header') ); ?>

<?php
function ty_front_end_form() {
?>
    <?php

    if($_POST){
        ty_save_post_data();
    }

}

function ty_save_post_data() {

    if ( empty($_POST) || !wp_verify_nonce($_POST['name_of_nonce_field'],'name_of_my_action') )
    {
       print 'Sorry, your nonce did not verify.';
       exit;

    }else{

        // Do some minor form validation to make sure there is content
        if (isset ($_POST['title'])) {
            $title =  $_POST['title'];
        } else {
            echo 'Please enter a title';
            exit;
        }
        if (isset ($_POST['description'])) {
            $description = $_POST['description'];
        } else {
            echo 'Please enter the content';
            exit;
        }

        if(isset($_POST['post_tags'])){
        $tags = $_POST['post_tags'];
        }else{
        $tags = "";
        }

        // Add the content of the form to $post as an array
        $post = array(
            'post_title' => wp_strip_all_tags( $title ),
            'post_content' => $description,
            'post_category' => $_POST['cat'],
            'tags_input' => $tags,
            'post_status' => 'publish',
            'post_type' => $_POST['post-type']
        );
        wp_insert_post($post);

        $location = home_url();

        echo "<meta http-equiv='refresh' content='0;url=$location' />"; exit;
    } // end IF

}
?>

<form id="custom-post-type" name="custom-post-type" method="post" action="">

Post Title

    <input type="text" id="title" value="" tabindex="1" size="20" name="title" />

<input type="submit" value="Publish" tabindex="6" id="submit" name="submit" />

    <?php wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ); ?>

</form>

<?php Starkers_Utilities::get_template_parts( array( 'parts/shared/footer','parts/shared/html-footer') ); ?>


text:
Q: Adding a total to data table footer row I want to add sum (total)of a column to a footer row. I tried the following code and I didn't get any result.
$(document).ready(function() {
    // SUM PLUGIN
    jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
        return this.flatten().reduce( function ( a, b ) {
            if ( typeof a === 'string' ) {
                a = a.replace(/[^\d.-]/g, '') * 1;
            }
            if ( typeof b === 'string' ) {
                b = b.replace(/[^\d.-]/g, '') * 1;
            }

            return a + b;
        }, 0 );
    } );

    $('#userTable1').DataTable({
        "footerCallback": function () {
            var api = this.api(),
                columns = [7,8,9,10,11,12]; // Add columns here

            for (var i = 0; i < columns.length; i++) {
                $('tfoot th').eq(columns[i]).html('Total: ' + api.column(columns[i], {filter: 'applied'}).data().sum() + '
');
                $('tfoot th').eq(columns[i]).append('Page: ' + api.column(columns[i], { filter: 'applied', page: 'current' }).data().sum());
            }
        }
    });
});

</script>

        Total:
        <?php ?>


text:
Q: Renaming arrays of varying sizes In Step 1, I find what type of data exists in Database.
In step 2, I retrieve all data from Database and try to store into arrays of varying sizes
1. Accessing data from MongoDB
    mong <- mongo(collection = "mycollection", db = "dbname", url = "mongodb://localhost")

    agg_df <- mong$aggregate('[{ "$group" :
                          { "_id" : "$tagname",
                            "number_records" : { "$sum" : 1}
                          }
                      }]')

    print(agg_df)

OUTPUT:
                _id         number_records
      1         raees            100
      2   DearZindagi            100
      3           FAN            100
      4           DDD             21

NOTE: Step 1 output indicates that there are 4 types of categories with records of 100,100,100,21 each.
2. From STEP 1, I need to create 4 arrays consisting of 1 column and varying nos. of rows(100,100,100,21) and give names to those array as Raees,DearZindagi,FAN,DDD
     Dataset <- mong$find('{}','{"text":1}')
     Dataset$text <- sapply(Dataset$text,function(row) iconv(row, "latin1", "ASCII", sub=""))
     typeof(Dataset$text)
     > [1] "character"

3. The arrays and their sizes(in rows) to be created is dependent on output of Step 1. There would never be a case where the output of step 1 would be more than 15 rows.
How should i do this?.

*The split function would splits the Dataset into arrays, how shall i rename these arrays:
rows <- nrow(agg_df)
for (i in 1:rows){
array<- split(Dataset$text, rep(1:rows, c(agg_df[i,2])))
}


text:
Q: Is there any way to see the mongo results in a better format? Is there any way to see the mongo results in a better format, like we are using \G in the sql ?

A: There is no way to enable vertical printing like what you would see in \G in MySQL.  In the context that view is less useful, since MongoDB is a document store and can have nested documents and the like.
You can print out the results of a query in pretty printing, by adding a .pretty() to the query:
db.test.find().pretty()

Which will return the results in a expanded document view, which may be helpful.

A: In addition to @Andre solution,
in case you want to get only one element. You can use findOne function. It pretty prints that document.
db.test.findOne()

Also you can use toArray over a cursor. Though its a memory hog, but for small number of results its fine and pretty prints,
db.test.find({...}).toArray()


text:
Q: How do I attach event handlers using jQuery only to newly added elements? There are objects where I have attached some events to.
After some point, I create some more of those items and I want them also to be attached to the same events.
If select elements using a jQuery selector and attach the handler to the event, the older object will have the same handler attached multiple times to their event.
What's the proper way of doing this?

A: Perhaps you should consider adding the handlers with live instead. This way, you declare the handler once and it remains in effect for all matching elements, now and in the future.
If for some reason this is not acceptable, a quick and dirty solution would be (example for the click handler):
$(".elements").unbind("click").bind("click", function () {
    // ...
});

A much better solution (again, without live) would be the hasEventListener plugin. Read the documentation, or play with its sandbox on JSFiddle.

A: I would go like this about it:
$(".element").unbind("click").live("click", function () {
// ...
});

and by that you unbind older 'click' event handlers and bind old and new ones only once with live.

A: The easiest way would be to use .live() to keep your handlers binded for existing and any possible future elements that match given selector.

A: Use a namespace for your events, like so:
$('a').bind('click.customNS', function(){...})
and then, whenever you create a new element, unbind all of your namespaces events, and rebind, like so:
$('a').unbind('click.customNS');
$('a').bind('click.customNS', function(){...});

alternatively, use .live('click', function(){..});, which will automatically "bind" events to any newly created element, matchin your jQuery selector. This does not work on non-CSS compliant selectors, though. (jQuery special parent-selectors, for instance)


text:
Q: How can I use the new GWT MVP framework? I need a tutorial for the new GWT MVP framework which is presented here.
The description Google gives is a little bit short for me. What are the meanings of — and how do I use — the following?

*

*Activities

*Places

*Eventbus

*ClientFactory

*PlaceHistoryMapper

*ActivityMapper

Also, where are the models in this new framework?

A: Places
These are classes that encode information about where your program has navigated.  You might make a Place that means, "I'm on the home screen," and another one that means "I'm editing the user with id 52384.  I think a better name for these would be PlaceTags, because they are not actually a place themselves - they just indicate where your program is.  The URL is hooked to Places in a PlaceHistoryMapper, in which you can say, "hey, #home should generate a HomeScreenPlace and #edituser:52384 should generate a EditUserPlace (maybe constructed with a field you set to 52384).
Activities
These start and stop your code.  Each Activity has a start method that is called when appropriate.  You determine what "when appropriate" means by making an ActivityMapper, which has a function called getActivity.  getActivity accepts a Place, and you have to decide which Activity to return.  If the Place is whatever you've coded to mean "I'm on the home screen," you might return a HomeScreenActivity, and if the Place means "I'm editing the client with id 523584," you might return a EditClientActivity.  You can add methods or a constructor to an activity to pass in an id like 523584.
EventBus
This is an object the different parts of your program use to communicate.  If you don't want to, you don't need to know very much about it - you can just plug it in where indicated in Google's documentation (that you linked to)
ClientFactory
This is a centralized object whose only responsibility is making other objects.  You can also skip this concept if you want to simplify things - you'll just be missing out on the central organization of your objects.  The advantage is that if you want to switch them out later for, say, a mobile version, or a mocked-up-for-testing version, you can do so all at once within a single place and the rest of your program doesn't have to change at all.  You can also reuse the same objects easily when coordinating from a central place, so you don't have to re-create the whole main screen every time someone goes to #home.
Your Actual Program
All this stuff is just for navigation.  Your models, views, and presenters are all set up in each Activitys start() method, which the framework calls when your app should navigate to a new place.  In the start method you should start up your presenter (usually using a new instance) and start up your display (usually reusing an instance - the client factory is good for this).  When you've created your display, you let the framework know by setting it as the widget for the AcceptsOneWidget that the framework passed into your start method.
This is incomplete, but a good supplement to the docs you mentioned: http://code.google.com/intl/de-DE/webtoolkit/doc/latest/DevGuideMvpActivitiesAndPlaces.html

A: I would also recommend you to carefully listen to the Google I/O presentations, they are a golden key to understand the GWT philosophy:
http://www.google.com/events/io/2010/
http://www.google.com/events/io/2009/
Specially these ones (try to keep a more holistic view of the MVP framework). They do not talk about the real GWT implementation but they give you basic knowledge of MVP. I still am an 8 months noob, so from noob to noob :)
Ray Ryan's overview of the MVP paradigm. Great resource (it was an enlightening for me).
http://www.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
http://www.google.com/events/io/2010/sessions/architecting-production-gwt.html
Daniel Danilatos's testing for GWT. Here you will understand why all the fuzz for MVP!
http://www.google.com/events/io/2010/sessions/gwt-continuous-build-testing.html


text:
Q: python: using tempfile as a pipe TL;DR: how to get two INDEPENDENT file objects/descriptors of a tempfile (with no visible name)?
I have lots of data and need to pass to a command to process, i.e.
tmp = tempfile.SpooledTemporaryFile()
p = subprocess.Popen(['command'], stdin=subprocess.PIPE, stdout=tmp)
for d in get_data():
    p.stdin.write(d)

In this way, I cannot read tmp before p complete. I tried to get another descriptor of tmp, but seems impossible. os.dup doesn't help because the descriptor returned is just a reference.
NOTE: I cannot use subprcess.PIPE to stdout, because that may deadlock the process. I also don't want to use another thread to read as I want to keep the code simple.
Thanks.


text:
Q: Unable to download multiple files with this python script This script uses beautiful soup to parse all pdf documents on a particular page of a web site.  The script successfully downloads one file but will not download all the files that are returned.  I need help making this download all pdf documents that I have parsed.
I have done research but have found no answers
import requests
from bs4 import BeautifulSoup
import html5lib
import lxml

#RFP_Import = ('http://www.staffordmsd.org/cms/One.aspx?    portalId=895956&pageId=1606144')
RFP_Import =     ('http://www.staffordmsd.org/departments/business_operations/bids_and_proposals')
place_hoder = ('http://www.staffordmsd.org')

def get_pdf_links():
    r = requests.get(RFP_Import)
    soup= BeautifulSoup(r.content, 'html5lib')
    links = soup.find_all('a')
    pdf_links = [place_hoder + link['href'] for link in links if     link['href'].endswith('pdf')]
    return pdf_links

def download_pdf_links (pdf_links):
    for link in pdf_links:
        file_name = link.split("/")[-1]
        print ("Downloading file:%s"%file_name)
        r = requests.get(link, stream = True)
        with open(file_name, 'wb') as f:
            for chunk in r.iter_content(chunk_size = 1024*1024):
                if chunk:
                    f.write(chunk)
        print ('%s downloaded!\n'%file_name)
        print ('all RFPs downloaded!')
        return

if __name__ == "__main__":
        pdf_links = get_pdf_links()
        download_pdf_links(pdf_links)

Successfully downloads first pdf document and then stops.
import requests
from bs4 import BeautifulSoup
import html5lib
import lxml

#RFP_Import = ('http://www.staffordmsd.org/cms/One.aspx?       portalId=895956&pageId=1606144')
RFP_Import =     ('http://www.staffordmsd.org/departments/business_operations/bids_and_proposals')
place_hoder = ('http://www.staffordmsd.org')

def get_pdf_links():
    r = requests.get(RFP_Import)
    soup= BeautifulSoup(r.content, 'html5lib')
    links = soup.find_all('a')
    pdf_links = [place_hoder + link['href'] for link in links if     link['href'].endswith('pdf')]
return pdf_links

def download_pdf_links (pdf_links):
    for link in pdf_links:
        file_name = link.split("/")[-1]
        print ("Downloading file:%s"%file_name)
        r = requests.get(link, stream = True)
        with open(file_name, 'wb') as f:
            for chunk in r.iter_content(chunk_size = 1024*1024):
                if chunk:
                    f.write(chunk)
        print ('%s downloaded!\n'%file_name)
        print ('all RFPs downloaded!')
        return

if __name__ == "__main__":
        pdf_links = get_pdf_links()
        download_pdf_links(pdf_links)

A: Inside download_pdf_links(), return is misaligned. It should be aligned with for. Otherwise, it is part of the for cycle and the function terminates after the first iteration.
This is probably also true for print ('all RFPs downloaded!'). I guess you want that printed out at the end of the for cycle, after you have been through all links.

A: In download_pdf_link you are using return inside your loop, which will return after the first iteration of the loop and stop downloading files. You need to return after the loop finishes by putting it on the same indentation as the start of the loop like this:
def download_pdf_links (pdf_links):
    for link in pdf_links:
        file_name = link.split("/")[-1]
        print ("Downloading file:%s"%file_name)
        r = requests.get(link, stream = True)
        with open(file_name, 'wb') as f:
            for chunk in r.iter_content(chunk_size = 1024*1024):
                if chunk:
                    f.write(chunk)
        print ('%s downloaded!\n'%file_name)
    # Un-indented so it happens after the loop finishes.
    print ('all RFPs downloaded!')
    return


text:
Q: Is my proof valid? Let W1,W2 be subspaces finite-dim, IPS V with T1,T2 orthogonal projections on W1,W2. Show that T1T2=T0 iff W1 perp W2. Is this a good proof?  I'm most concerned about the very last line.. does what I show actually imply what I say it does?

A: Yes this is valid. However, to be very clear you should say "If $\langle x, T_1 T_2 y \rangle = 0$ for every possible $x \in W_1$ for a given $y$, then $T_1T_2y$ must also be $0$. Therefore, if $T_1T_2y = 0$ for every possible $y \in W_2$, we must furthermore have $T_1T_2 = T_0$."
I think the confusion you had was going from the inner product = 0 to the RHS = 0. In general, if you have an inner product of 0 with one vector, then you are orthogonal to that vector. But if you have an inner product of 0 with every vector, then you must be orthogonal to the entire space. The only vector orthogonal to the entire space and still in that space is the 0 vector.


text:
Q: Finding elements in SQL statement list I'm looking at SQL statements as strings and want to count the number of elements in the largest list in the SQL query. For example, the following string would have a max count of 5:
"select id from table where language in (\"ENGLISH\", \"SPANISH\", \"german\") and id in (1,2,3,4,5);"

Does anyone know how to do this using regex? It's tricky because the contents of the list might be integers, strings, or tuples. The best I've been able to come up with is the following:
Use https://regex101.com/r/iNOxuO/1 to first match all lists in the string. Then, for each of those matches, run https://regex101.com/r/kowtrV/1 to match and count each element in the list.
The problem I'm having is that there are a few edge cases (the last two lines in the first link) that are escaping me.
Thanks!

A: One way would be to write some separate expressions for your edge cases, then use alternation, and then you'll be adding a counter. The start core expression would be something as simple as:
(?<=\(|,)[^,]+?(?=\)|,)

Demo 1
Then, when you write those others, imagine
 some other expression 1

and
  some other expression 2

You would join them with logical ORs:
some other expression 1| some other expression 2|(?<=\(|,)[^,]+?(?=\)|,)

You'll figure it out which expression has to be prior. It is just time-consuming to write all those expressions.


text:
Q: How can I update the text dynamically without refresh the page? I am using Shopify template. Under Ajaxify.js.liquid, I had been modified the codes according to this solution from prevent the cart modal ajax from opening after adding a product.
Currently I want to build something like redmart. When you hit add cart, it will show the number of item selected. I can get call the amount of item when I hit add cart, but need to refresh the page in order to work. I tried to modify Ajaxify.js.liquid but no luck that I couldn't find specific variant_id for each item when I hit the add cart button.
Once again, I want to build something like redmart that the cart button will show number of item that had been added to cart.
In product collection page, each product has "add to cart" button below. Above that button, I had added item quantity for each product.
Product-grid-item.liquid (Add cart button)
<form action="/cart/add" method="post" enctype="multipart/form-data" id="addToCartForm">
        <select name="id" id="productSelect" class="product-variants">
          {% for variant in product.variants %}
            {% if variant.available %}

              <option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} data-sku="{{ variant.sku }}" value="{{ variant.id }}">{{ variant.title }} - {{ variant.price | money_with_currency }}</option>

            {% else %}
              <option disabled="disabled">
                {{ variant.title }} - {{ 'products.product.sold_out' | t }}
              </option>
            {% endif %}
          {% endfor %}
        </select>

 {% for variant in product.variants %}
    {% if variant.available %}

        Variant id: {{ variant.id }}

        {% for item in cart.items %}
          {% if item.variant_id == variant.id %}
                Item amount: {{ item.quantity }}
          {% endif %}
        {% endfor %}
    {% endif %}
{% endfor %}

        {% if settings.product_quantity_enable %}
          {{ 'products.product.quantity' | t }}
          <input type="number" id="quantity" name="quantity" value="1" min="1" class="quantity-selector">
        {% endif %}

        <button type="submit" name="add" id="addToCart" class="btn">

          {{ 'products.product.add_to_cart' | t }}
        </button>
        {% if settings.product_quantity_message %}

        {% endif %}
</form>

I want to update "#item-cart-quantity" dynamically, but I am having problem in Ajaxify.js.liquid which I could not get item's variant id from the specific item I added to.


text:
Q: How to pass a method name to actionListner I need your help in passing the proper method to the button actionListner. I am having a button in a datatable. The button code is below:
<h:commandButton id="submitButton" value="View" actionListener="#{bcd.showDatailDialog}" >
<f:setPropertyActionListener value="#{c}" target="#{bcd.selectedRequest}"/>
</h:commandButton>

Based on the value of the #{c.documentType} which is displayed in the datatable, it will decide which method to be used in the actionListner.
The showDatailDialog method code is:
public String showDatailDialog(String sdoc) {

private String methodName;

try {

if (sdoc.equalsIgnoreCase("CE")) {

mthodName="#{bcd.BCESS}";

}
else
{
mthodName="#{bcd.BSSES}";
}

        } catch (Exception e) {
            System.err.print(e);
            e.printStackTrace();
        }
return methodName;
    }

Now when I click on the button, it showed me an error:
<ActionListenerImpl> <processAction> javax.el.MethodNotFoundException: //C:/../JDeveloper/../XXX.war/jsf/Search.jsf @91,89 action="#{bcd.showDetailDialog}": Method not found: rfc.Bean3@355f70.showDetailDialog()

A: You're approaching this problem wrongly. The actionListener (and action) attributes must represent a method expression, not a value expression. Right now you're treating it as if it were a value expression returning a method expression. This isn't going to work.
Just let it invoke a real method which in turn delegates further to the desired method.
<h:dataTable ... var="item">
   ...
   <h:commandButton ... action="#{bean.action(item)}" />

public void action(Item item) {
    if (item.getType() == Type.FOO) { // It's of course an enum.
        oneMethod(item);
    } else {
        otherMethod(item);
    }
}

See also:

*

*How can I pass selected row to commandLink inside dataTable?

*Is it possible to use EL conditional operator in action attribute?

*Differences between action and actionListener

A: showDatailDialog method in your code expects one String parameter, so just use it like this
actionListener="#{bcd.showDatailDialog(c.documentType)}"


text:
Q: Facebook OAuth Get Business Manager Id I am struggling to get the business manager id, via facebook oauth of business manager account.I also have standard access api
Api::init(APP_ID, APP_SECRET, $access_token);
$fbUser = new Business('me');
$business_manager = $fbUser->read();

The above code don't return the business id.
Can anyone tell me how to fetch the business id??
Thanks,
Ronak Shah

A: The list of Businesses a user has access to can be retrieved by calling /<API VERSION>/<USER ID>/businesses
This endpoint is currently documented here:
https://developers.facebook.com/docs/marketing-api/businessmanager#read
With the reference doc here:
https://developers.facebook.com/docs/graph-api/reference/user/businesses/


text:
Q: Scheduler Expression How can I write an Quartz Scheduler Expression to create a trigger that fires every 5 minutes between 15:30 and 15:55 in one simple expression case? Is that possible? or should I create more than one trigger, and register both of them to run the same job?

A: I believe this is the easiest (but not necessarily most elegant) way to achieve this:
0 30,35,40,45,50,55 15 * * ?


text:
Q: How to add UserControl to ListView on Windows Forms? I'm trying to make it so, for each item on a List<> , a usercontrol gets inserted into a ListView.
I tried doing the following but it didn't work:
foreach (var item in MyList)
            {
                UserControl1= new UserControl(parameter);
                listView1.Items.Add(UserControl1);
            }

However, it marks an error:

Error CS1503  Argument 1: cannot convert from
'UserCOntrol' to 'string'

What am I doing wrong? What can I do to solve this problem?
Thank you for your time!
Edit: this is what I have on my usercontrol
This is my UserControl
Edit 2: my code looks like this now:
foreach (var item in MyList)
            {
                FlowLayoutPanel.Controls.Add(new UserControl(parameter));
            }

A: I'd recommend using a FlowLayoutPanel, instead of list view, as the list view does not add UserControls.
e.g.
flowLayoutPanel.Controls.Add(new UserControl());