Q:

bind: "nsupdate -l" failed with status "update failed: REFUSED"

I just switched to bind 9.9.5 dynamic DNS feature with semi-automatic manage of DNSSEC entries, the whole process went good and my zone files were updated well, but now I can't update or add entries via nsupdate tool.
The /etc/bind/named.conf.local:
// 1
view "localhost_view" {

    allow-query-on { 127.0.0.1; };
    allow-query { localhost_acl; };
    match-clients { localhost_acl; };

    zone "somehost.tld" {
            type master;
            file "/etc/bind/db.somehost.tld_10";
    };

    zone "168.192.in-addr.arpa" {
            type master;
            notify no;
            file "/etc/bind/db.192.168.10";
    };

    // formerly named.conf.default-zones

        zone "." {
                type hint;
                file "/etc/bind/db.root";
        };

        zone "localhost" {
                type master;
                file "/etc/bind/db.local";
        };

        zone "127.in-addr.arpa" {
                type master;
                file "/etc/bind/db.127";
        };

        zone "0.in-addr.arpa" {
                type master;
                file "/etc/bind/db.0";
        };

        zone "255.in-addr.arpa" {
                type master;
                file "/etc/bind/db.255";
        };

    // formerly zones.rfc1918

        zone "10.in-addr.arpa"      { type master; file "/etc/bind/db.empty"; };
        zone "16.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "17.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "18.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "19.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "20.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "21.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "22.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "23.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "24.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "25.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "26.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "27.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "28.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "29.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "30.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "31.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };

};

// 2
view "internal_10_view" {

    allow-query-on { 192.168.10.1; };
    allow-query { internal_10_acl; };
    match-clients { internal_10_acl; };

    zone "somehost.tld" {
            type master;
            file "/etc/bind/db.somehost.tld_10";
    };

    zone "168.192.in-addr.arpa" {
            type master;
            notify no;
            file "/etc/bind/db.192.168.10";
    };

    // formerly named.conf.default-zones

        zone "." {
                type hint;
                file "/etc/bind/db.root";
        };

        zone "localhost" {
                type master;
                file "/etc/bind/db.local";
        };

        zone "127.in-addr.arpa" {
                type master;
                file "/etc/bind/db.127";
        };

        zone "0.in-addr.arpa" {
                type master;
                file "/etc/bind/db.0";
        };

        zone "255.in-addr.arpa" {
                type master;
                file "/etc/bind/db.255";
        };

    // formerly zones.rfc1918

        zone "10.in-addr.arpa"      { type master; file "/etc/bind/db.empty"; };
        zone "16.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "17.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "18.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "19.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "20.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "21.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "22.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "23.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "24.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "25.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "26.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "27.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "28.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "29.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "30.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "31.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };

};

// 3
view "internal_150_view" {

        allow-query-on { 192.168.150.1; };
        allow-query { internal_150_acl; };
    match-clients { internal_150_acl; };

    zone "somehost.tld" {
            type master;
            file "/etc/bind/db.somehost.tld_150";
    };

    zone "168.192.in-addr.arpa" {
            type master;
            notify no;
            file "/etc/bind/db.192.168.150";
    };

    // formerly named.conf.default-zones

        zone "." {
                type hint;
                file "/etc/bind/db.root";
        };

        zone "localhost" {
                type master;
                file "/etc/bind/db.local";
        };

        zone "127.in-addr.arpa" {
                type master;
                file "/etc/bind/db.127";
        };

        zone "0.in-addr.arpa" {
                type master;
                file "/etc/bind/db.0";
        };

        zone "255.in-addr.arpa" {
                type master;
                file "/etc/bind/db.255";
        };

    // formerly zones.rfc1918

        zone "10.in-addr.arpa"      { type master; file "/etc/bind/db.empty"; };
        zone "16.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "17.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "18.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "19.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "20.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "21.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "22.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "23.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "24.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "25.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "26.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "27.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "28.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "29.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "30.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "31.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };

};

// 4
view "vpn_view" {

    allow-query-on { 192.168.200.1; };
    allow-query { vpn_acl; };
    match-clients { vpn_acl; };

    zone "somehost.tld" {
        type master;
        file "/etc/bind/db.somehost.tld_vpn";
    };

    // formerly named.conf.default-zones

        zone "." {
                type hint;
                file "/etc/bind/db.root";
        };

        zone "localhost" {
                type master;
                file "/etc/bind/db.local";
        };

        zone "127.in-addr.arpa" {
                type master;
                file "/etc/bind/db.127";
        };

        zone "0.in-addr.arpa" {
                type master;
                file "/etc/bind/db.0";
        };

        zone "255.in-addr.arpa" {
                type master;
                file "/etc/bind/db.255";
        };

    // formerly zones.rfc1918

        zone "10.in-addr.arpa"      { type master; file "/etc/bind/db.empty"; };
        zone "16.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "17.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "18.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "19.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "20.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "21.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "22.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "23.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "24.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "25.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "26.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "27.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "28.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "29.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "30.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "32.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };

};

// 5
view "global_view" {

    allow-query-on { 1.2.3.4; };
//  match-clients { any; !localhost_acl; !internal_10_acl; !internal_150_acl; !vpn_acl; };
    recursion no;

    zone "somehost.tld" {

        type master;

        update-policy local;
        auto-dnssec maintain;

        file "/etc/bind/db.somehost.tld_global";

        key-directory "/etc/bind/keys";

    };

    zone "26/4.3.2.1.in-addr.arpa" IN {
        type master;
        file "/etc/bind/db.rev";
    };

    // formerly named.conf.default-zones

        zone "." {
                type hint;
                file "/etc/bind/db.root";
        };

        zone "localhost" {
                type master;
                file "/etc/bind/db.local";
        };

        zone "127.in-addr.arpa" {
                type master;
                file "/etc/bind/db.127";
        };

        zone "0.in-addr.arpa" {
                type master;
                file "/etc/bind/db.0";
        };

        zone "255.in-addr.arpa" {
                type master;
                file "/etc/bind/db.255";
        };

    // formerly zones.rfc1918

        zone "10.in-addr.arpa"      { type master; file "/etc/bind/db.empty"; };
        zone "16.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "17.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "18.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "19.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "20.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "21.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "22.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "23.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "24.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "25.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "26.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "27.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "28.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "29.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "30.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };
        zone "32.172.in-addr.arpa"  { type master; file "/etc/bind/db.empty"; };

};

ACLs:
acl localhost_acl {
        127.0.0.0/8;
};

acl internal_10_acl {
        192.168.10.0/24;
};

acl internal_150_acl {
        192.168.150.0/24;
};

acl vpn_acl {
        192.168.200.2;
        192.168.200.5;
};

So the update-policy local; is here, /var/run/named/session.key is successfully generated and user bind readable, but when I perform the add command via nsupdate -l (as root), I always get the update failed: REFUSED error (here with debug messages):
root@somehost:/etc/bind# nsupdate -l -v -D
setup_system()
Creating key...
namefromtext
keycreate
reset_system()
user_interaction()
> ttl 46000
do_next_command()
> zone somehost.tld.
do_next_command()
> update add whatever.somehost.tld. A 1.1.1.1
do_next_command()
evaluate_update()
update_addordelete()
> send
do_next_command()
start_update()
send_update()
Sending update to 127.0.0.1#53
show_message()
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:  15363
;; flags:; ZONE: 1, PREREQ: 0, UPDATE: 1, ADDITIONAL: 1
;; ZONE SECTION:
;somehost.tld.                      IN      SOA

;; UPDATE SECTION:
whatever.somehost.tld.  46000   IN      A       1.1.1.1

;; TSIG PSEUDOSECTION:
local-ddns.             0       ANY     TSIG    hmac-sha256. 1446539060 300 32 r2lt18dGihGnJepoUjvIKx8l5BPMohNJvsLoO+WQiBE                                                                         = 15363 NOERROR 0

update_completed()
tsig verification successful
show_message()

Reply from update query:
;; ->>HEADER<<- opcode: UPDATE, status: REFUSED, id:  15363
;; flags: qr ra; ZONE: 1, PREREQ: 0, UPDATE: 0, ADDITIONAL: 1
;; ZONE SECTION:
;somehost.tld.                      IN      SOA

;; TSIG PSEUDOSECTION:
local-ddns.             0       ANY     TSIG    hmac-sha256. 1446539060 300 32 Cnh9Tgg5vhKngPRk2J8n0wiRzdBLlQrp0F0qmfUotN8                                                                         = 15363 NOERROR 0

done_update()
reset_system()
user_interaction()
> quit

It is some kind of permission issue? What's wrong?

A:

Finally figured it out. Thanks to @Håkan Lindqvist for inspiration.
These solutions are probably Debian/Ubuntu-specific and weren't tested in other distros.
1. FIRST SOLUTION
(Using update-policy local;).
You may actually use update-policy local; directive in /etc/bind/named.conf.local in each zone declaration you want, which restricts update requests from the internet or LAN for better security. In this case the key is generated automatically and nsupdate will use it if run with -l option.
Instead of server X.X.X.X command one should use local X.X.X.X. It accepts even public IP as argument if it is local to the system!
Note: the key is not world-readable, so use sudo.
Example:
me@somehost:~$ sudo nsupdate -l
> local 1.2.3.4
> zone somehost.tld
> update add something.somehost.tld. 86400 A 1.1.1.1
> send
> quit

2. SECOND SOLUTION
(Using ddns-confgen).
I have plenty of views (localhost_view, global_view etc.), some of which have common zones (somehost.tld in my example). If I want to dynamically update them, I should use server X.X.X.X command when do nsupdate. Therefore nsupdate will send an update request to the appropriate interface and the appropriate view will handle it.
update-policy local; is not suitable in this configuration because it forbids use of the server command in nsupdate. So it is needed to generate a DDNS key and specify it in all of the zones declarations, which should be dynamically updated by nsupdate. In the Debian universe there is a ddns-confgen command which simplifies this task a lot:
me@somehost:~$ ddns-confgen
# To activate this key, place the following in named.conf, and
# in a separate keyfile on the system or systems from which nsupdate
# will be run:
key "ddns-key" {
        algorithm hmac-sha256;
        secret "pXohPnPR7dyri9ADfDLtSz+lHw/QliISyiEe0wg0a14=";
};

# Then, in the "zone" statement for each zone you wish to dynamically
# update, place an "update-policy" statement granting update permission
# to this key.  For example, the following statement grants this key
# permission to update any name within the zone:
update-policy {
        grant ddns-key zonesub ANY;
};

# After the keyfile has been placed, the following command will
# execute nsupdate using this key:
nsupdate -k <keyfile>

The output of this command is quite self-descriptive. It is needed to add key... snippet to the /etc/bind/named.conf and separate file with any name, and update-policy... snippet into each zone declaration, which will be managed by nsupdate.
To properly use nsupdate tool in multi-view BIND environment, it is needed to explicitly specify a server directive before executing any other command. So, for updating localhost_view's somehost.tld zone (considering key... snippet was saved to the /etc/bind/ddns-key.key) the commands are as follows (note the server 127.0.0.1):
me@somehost:~$ nsupdate -k /etc/bind/ddns-key.key
> server 127.0.0.1
> zone somehost.tld
> update add something.somehost.tld. 86400 A 1.1.1.1
> send
> quit

whereas to manipulate global_view's somehost.tld zone the commands are essentially the same, but with different server. In this case it is needed to use public IP (1.2.3.4 in my example):
me@somehost:~$ nsupdate -k /etc/bind/ddns-key.key
> server 1.2.3.4
> zone somehost.tld
> update add something.somehost.tld. 86400 A 1.1.1.1
> send
> quit

Therefore nsupdate sends a request to a proper interface (which may or may not be the local one) and a specific view works.


Q:

Configuring sendmail to forward mail for a specific domain to a specific mail server without using MX records?

I am new to sendmail and would like to configure sendmail to forward all mail for a specific email address to another internal mail server. I need it to ignore the MX records and only send it to the server I specify but am not sure which files to edit or how to configure the sendmail config. Is it sufficient to add the server to the /etc/hosts and the /etc/mail/local-host-names files?
Thanks in advance.

A:

EDIT: seems like you are talking about mail aliases.
Look into /etc/aliases or /etc/mail/aliases. After editing that file, run newaliases

I do not believe that Sendmail has transport map capabilities, at least not that i know of.
The feature you are looking for is available in Postfix out of the box. Not sure how much this answer would help you though...
There used to be a package called redhat-switchmail that kind of accomplished that, but I am not sure if it is still available, or if its even compatible with your system.
/etc/mail/local-host-names is just for that... local host names... the domains your sendmail server accepts mail for.
What exactly you want to accomplish with /etc/hosts I am not sure...
Depending on your configuration and version of your Sendmail, you need to edit /etc/mail/sendmail.mc and then "make it" into /etc/mail/sendmail.cf. On older versions, you edit /etc/mail/sendmail.cf, but i do not suggest you touch either one of those files if you do not know what you are doing. They are pretty cryptic, to say the least.


Q:

Java - JFrame, JPanel and Components Won't show

I have this activity that includes GUI. This activity includes inputting the length and width, x and y (location of the shape in the canvas) and the button which chooses the shape, rectangle or circle. After clicking the button, it then accept the length, width, x and y inside the textfield.
After fiddling with the GUI code manually, the JPanels and JFrames won't show even after setting the size, just pure blank.
I was expecting to put the canvas on the left and the labels, textfields and buttons on the right. What am I doing wrong? I'm still at the early part of the program just aesthetic. Thank you.
public class Problem02{
    Problem02(){
        JFrame framer = new JFrame("Problem 02");
        framer.setLayout(new FlowLayout());
        framer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel LPanel = new  JPanel();
        JPanel RPanel = new JPanel();
        Canvas canvasses = new Canvas();Label XLabel = new Label("X");
        JLabel YLabel = new JLabel("Y");
        JLabel WidthLabel = new JLabel("Width");
        JLabel LengthLabel = new JLabel("Length");
        JButton RectangleButton = new JButton("Rectangle");
        JButton CircleButton = new JButton("Circle");
        JTextField XText = new JTextField("");
        JTextField YText = new JTextField("");
        JTextField WidthText = new JTextField("");
        JTextField LengthText = new JTextField("");

        framer.add(LPanel, BorderLayout.WEST);
        framer.add(RPanel, BorderLayout.EAST);
        LPanel.add(canvasses);
        RPanel.add(XLabel);
        RPanel.add(XText);
        RPanel.add(YLabel);
        RPanel.add(YText);
        RPanel.add(WidthLabel);
        RPanel.add(WidthText);
        RPanel.add(LengthLabel);
        RPanel.add(LengthText);
        RPanel.add(RectangleButton);
        RPanel.add(CircleButton);

        framer.setSize(500,500);
        framer.setTitle("Problem 02");
        framer.setVisible(true);
    }
    public static void main(String[] args) {
     new Problem02();

    }

    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowOpened(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowClosing(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowClosed(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowIconified(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowDeiconified(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowActivated(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void windowDeactivated(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

A:

You're extending from JFrame PLUS you're using a JFrame variable (framer)... you add all the components to the variable, but you don't show framer, you show this.
Do not extend JFrame, an change the last lines to
    framer.setSize(500,500);
    framer.setTitle("Problem 02");
    framer.setVisible(true);

Plus, PLEASE, stick to naming conventions: lowercase letters for variables, you even trick StackOverflows text highlighting parser ;-)


Q:

Why responsive panels are not one beside another by default?

I am using the adaptive theme with panels, mini panels, panels everywhere, and AT Panels Everywhere. My site default template is of at panels everywhere.
I built a 5 column mini panel for the footer. I assigned for each column only one thing: menu, or a logo, or "powered by drupal".
When I am using the builder layout for the mini panel, and build 5 column - every thing works fine, and I have 5 column one beside another, in only one row. (although, I am trying to avoid the builder and use only AT layouts).
But, If I am using the "AT responsive panel - 4,5,6 column" for the mini panel layout, the result is that my footer has two rows: top row is with 2 panels and bottom row is with 3 panels. it  looks like the blocks or something are too big, and the AT layout is just being responsive.
I tried to solve that and make it one row, and add to each panel a class, and made them very narrow. but that didn't work, and I still have 2 rows, even though the panels are very narrow and can feat perfectly in one row (5 columns).
How can I make sure that every panel will use 20% of it's layout (when possible), and all will be presented in one row, 5 columns side by side?
Here is the problem:

Here is the footer code:
The footer is still in two rows, and looks like that:

What causing the AT mini panel to think it has no room, and need to change the layout?

A:

I finally found the solution. AT is printing the following css code :
.five-5x20 > .panel-row {
    clear: none;
}

so, I adjust all the code to be:
#panel-footer .five-5x20 > .panel-row {
    float: left ;
    display: block;
    width: auto;
    clear: none;
}

the clear: none fix the proble, and now the float: left is working.
@Marcel Thanks for all the help


Q:

ember simple auth invalidate other user

I'm new to ember-simple-auth and I need some help.
Say, there are 3 users, User A is Admin, User B and C are User. User C somehow able to hack User B's account and currently is logged in as User B. User B asked User A to reset his password.
I want to invalidate User C's session (who is currently logged in as User B) after User A reset User B's password.
I'm thinking of saving each user's session in a database and every time the user logs out, the session in database is also removed.

A:

Just delete or reset the user's token on the server side. The next time they make a request with the old token they'd receive a 401 and will be logged out.


Q:

PHP based Telegram bot InlineKeyboardMarkup not working

Trying to create inline buttons for my Telegram bot. this is the request I'm sending and for some reason I don't get the buttons but only the text "Inline Keyboard"
Here is my code
$args = [
    'chat_id' => $this->chat_id,
    'parse_mode' => 'HTML',
    'text' => 'Inline Keyboard',
    'reply_markup' => [
        'inline_keyboard' => [
            [
                [
                    'text' => 'Try me',
                ]
            ]
        ]
    ]
];

$send = $this->api_url . "/sendmessage?" . http_build_query($args);
file_get_contents($send);

A:

Found the problem, You must use exactly one of the optional fields .. 'text' field is not enough


Q:

win32 message loop - should I break or return?

I'm wondering what the correct return value for a windows message loop is. So far I've used the following:
case WM_LBUTTONDOWN: // left mouse button pressed.
    if (condition == true )
    {
        do_something();
    }
break;

but I've seen also things like:
if (IDC_BUTTON == LOWORD(wParam) && BN_CLICKED == HIWORD(wParam))
{
    do_something();
    return true;
}
break;

which one is correct? Should I return true? or should I break? Does it matter?
EDIT does it depend whether I'm interacting with a button press or a mouse movement?

A:

The return value is documented on MSDN, as part of the documentation for each message. For example, the documentation for WM_LBUTTONDOWN states that

If an application processes this message, it should return zero.

For other messages, the return value might be more meaningful. You should always read the documentation, never guess.


Q:

Is it possible to change the Tabbar Item text/Icon on the fly while app is running?

Is it possible to change the Tabbar Item text/icon on the fly while app is running?
For example the name of the item on the tabbar is Item1. I want to programmatically change it to 'ItemX' while the app is being used.
Many Thanks,
-Code

A:

how to set individual tabbaritem icons in uitabbarcontroller in cocoa


Q:

Does 青龙 not really mean Green Dragon?

People at the Hebei museum, and my friends, and Baidu http://baike.baidu.com/view/606163.htm all agree that 青龙白虎 means "Dragon and White Tiger."  (I capitalize because these name specific folk animals.) When I asked at the museum whether it means the dragon is green they could not see why I would ask that.  So I suppose 青龙 is a traditional name that just means dragon and not green.
Can anyone here tell me if that is right? And can anyone explain a reason for it?  Or is it just the kind of thing can happen with traditional names in any culture?
Actually, on line a lot of people translate it as Azure Dragon.  I know 青 has several more meanings than the western green/grun/vert.  So maybe just plain Dragon is not a good translation of 青龙.  But I do not know.

A:

青龙 should be translated as 'Azure (or Green/Blue) Dragon', that is the accepted translation for the mythological context. (Check some dictionaries, Pleco or CEDICT, they all use Azure Dragon, Wikipedia, and this Wiki article on the Four Symbols, too.)
Why would 青 mean nothing here? You can argue if it is blue, green or azure, but it is a color. Perhaps the people who translated 青龙白虎 as 'Dragon and White Tiger' just got confused about the different equivalents of 青 (blue, green, black) and left it out.
If Wikipedia is not authoritative for you, you can try a site colon search on Google with site:edu 青龙 . This will search for 青龙 on the websites of American universities. You can see that most of these sources will give the translation as either Blue, Green or Azure Dragon.
If you are still looking for some evidence, there are some books written on (or inspired by) Chinese mythology with the title bearing your expression:

A:

Drunken Master's explanation is plausible and makes sense: 青 may have been left out from the translation due to the fact that it could have 3 or 4 color meanings (it is preferable to omit a word when in doubt of its meaning, specially if it risks changing the whole title's meaning).
However, I just wanted to add that the title may indirectly refer to other thing:

青 may also mean young (from 青年 qīngnián = youth), and actually according to a Chinese Characters Roots book, the original meaning of the character was:

"the color when things began to grow"

Therefore, again and indirectly, it cannot only represent youth, but ingenuity and being naïve as well.
opposing to the White Tiger (白虎), without any ambiguity, it may indirectly remind of the white hair of a wise old person.

So the title may reflect a deeper meaning than the direct one transmitted by the colors...
Edit
This idea gets particularly interesting because:

Dragons also symbolize masculinity and virility, Yang 陽 element

Which may refer to the young days of Tu Ming, the Taoist monk from the story, and as he evolves, the symbol that represents better his older self is the:

Tiger 虎: Known as the king of beasts, used as masculinity and valor symbol; fierce and decisive nature.

By this we can deduce the whole point of the book:

Tu advances not only in his practice, but also in his understanding of life and love as he falls under the spell of five unforgettable women unequaled in religious literature. In the exciting conclusion, he experiences an epiphany that redefines what it means to attain the highest knowledge.

I.e.: from a young viril Dragon, Tu Ming becomes a wise white old Tiger.


Q:

How to Update Group Price Programmatically Without Product Object Save

To save group price for the products, the following works for me.
$product->setData('group_price', $group_pricing_data);
$product->save();

However, it takes a while for mass updating products. The faster way to save only attributes via saveAttribute() does not seem to work on group price.
$product->setData('group_price', $group_pricing_data);
$product->getResource()->saveAttribute($product, 'group_price');

Is it because group_price is not EAV like the other attributes, and if so, is there any other way to just save only group pricing?

A:

As far as I know, you can't simply update group price data using saveAttribute because it has a custom backend model, catalog/product_attribute_backend_groupprice.
When you load and save a product object, group price's custom resource mode does the work to load and save the data accordingly. If you look at Mage_Catalog_Model_Resource_Product_Attribute_Backend_Groupprice_Abstract, you will see the methods Magento uses to load and save group price data.
Specifically, savePriceData shows how to save the data properly. If you want a fast group price update, you can mimic what's done here. Check how $data looks like, and you have a good place to start.


Q:

How can I use Sql to Order By This Statement?

How can I order the list 'widgets_spec by number of widgets?
select distinct
     m.p_c_id
    ,(select distinct '
' +convert(varchar,widgets) + '
 '
      from dbo.spec_master m2
          where m.p_c_id = m2.p_c_id and widgets is not null
          for xml path(''), type).value('.[1]', 'nvarchar(max)'
     ) as widgets_spec
from dbo.spec_master m
inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
inner join dbo.Varation v on v.varation_id = pv.varation_type_id
where v.varation_id  = 4
group by m.p_c_id

Right now output looks like:

10

12

15

8

When I want it to look like:

8

10

12

15

Thanks for your help.
EDIT: I'm trying to order the internal select statement that concatenates the values.

A:

You do not need both Distinct and Group By. You should use one or the other. In this case, I believe you have to use Group By for it to work.
Select m.p_c_id
    , (
        Select '
' + Cast( m2.num_of_lights As varchar(10)) + '
 '
        From dbo.spec_master As m2
        Where m.p_c_id = m2.p_c_id
            And m2.num_of_lights Is Not Null
        Group By m2.num_of_lights
        Order By m2.num_of_lights
        For Xml Path(''), type).value('.[1]', 'nvarchar(max)'
        ) As numLights_spec
From dbo.spec_master As m
    Inner Join dbo.ProductVaration As pv
        On pv.p_c_id = m.p_c_id
    Inner Join dbo.Varation As v
        On v.varation_id = pv.varation_type_id
Where v.varation_id  = 4
Group by m.p_c_id


Q:

php artisan migrate [PDOException] could not find driver

When I write command "php artisan migrate" from mysql connection,linux terminal gives this error :[PDOException] could not find driver.
When I add to
php.ini
extension=pdo.so
extension=pdo_mysql.so

,
error has changing like this:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/pdo_mysql.so' - /usr/lib/php5/20121212/pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0 PHP Warning: Module 'PDO' already loaded in Unknown on line 0

[PDOException]
could not find driver

How can we solve this issue?
Thanks

A:

Hi you need to install php pdo driver
 Open terminal
sudo apt-get install php5-mysql

Restart Apache server
sudo service apache2 restart


Q:

ionic retreive passed data from page to page

i am navigating from page to another page in ionic 5 and passing data as navigation parameters , it's already navigating correctly but i can't retreive the passed data in the details page .
HomePage.ts :
this.navCtrl.navigateRoot(['products', {item: 'data value'}]);

Products.ts (details page):
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-products',
  templateUrl: './products.page.html',
  styleUrls: ['./products.page.scss'],
})
export class ProductsPage implements OnInit {
  private activatedRoute: ActivatedRoute

  constructor() {
    this.sub = this.route.params.subscribe(params => {
      this.id = params.id;
  });
   }

  ngOnInit() {
 /*   this.activatedRoute.params.subscribe((params) => {
      console.log('Params: ', params);
    });
*/
  }

}

i got this error :
 "Property 'sub' does not exist on type 'ProductsPage'.",

A:

There are 2 options:
Option 1: NavController:
// Send Parameter
import { NavController } from '@ionic/angular';
import { NavigationExtras } from '@angular/router';
//...
constructor(public navCtrl: NavController) { }
//...
let navigationExtras: NavigationExtras = {
    queryParams: {
        currency: JSON.stringify(currency),
        refresh: refresh
    }
};
this.navCtrl.navigateForward(['page-slug'], true, navigationExtras);

-
// Receive Parameter
import { ActivatedRoute } from "@angular/router";
//...
constructor(private route: ActivatedRoute) {}
//...
this.route.queryParams.subscribe(params => {
    this.refresh = params["refresh"];
    this.currency = JSON.parse(params["currency"]);
});

Option 2: Router:
// Send Parameter
import { Router } from '@angular/router';
//...
constructor(private router: Router) {}

goToProductDetails(id) {
  this.router.navigate(['/product-details', id]);
}

-
// Receive Parameter
import { ActivatedRoute } from '@angular/router';
//...
id: any;
constructor(private route: ActivatedRoute) {}
//...
this.sub = this.route.params.subscribe(params => {
     this.id = params['id'];
});


Q:

Mocking Azure MobileServiceClient

I have a method I need to Unittest and I am stuck with mocking part of it.
private async void LoginCommandAsync()
    {

        .....

        CancellationToken ct;
        var result = await ClientAuthorizationService.CurrentClient.InvokeApiAsync(Constants.ApiConstants.AzureAuthMeData,
            null, HttpMethod.Get, null, ct);

        ....
    }

I tried to mock the Microsoft.WindowsAzure.MobileServices.MobileServiceClient using Moq. Unfortunatly I always get a System.InvalidCastException in the last code line
        var currentClient = new Mock<IMobileServiceClient>(MockBehavior.Loose);

        currentClient.Setup(x => x.InvokeApiAsync(Constants.ApiConstants.AzureAuthMeData,
            null, HttpMethod.Get, null, ct)).Returns(Task.FromResult(token));

        var disposableCurrentClient = currentClient.As<IDisposable>();

        ClientAuthorizationService.CurrentClient = (MobileServiceClient)disposableCurrentClient.Object;

MobileServiceClient inherits from IMobileServiceClient, IDisposable but no matter how I try to use/assign the mocked object... it does not work.
public class ClientAuthorizationService : IClientAuthorizationService
{
    public MobileServiceClient CurrentClient { get; set; }
    public ClientAuthorizationService()
    {
        CurrentClient = new MobileServiceClient(Constants.ApiConstants.ApplicationUrl);
    }
}

A:

Change ClientAuthorizationService.CurrentClient member/property from MobileServiceClient to IMobileServiceClient
public interface IClientAuthorizationService  {
    IMobileServiceClient CurrentClient { get; set; }
}

public class ClientAuthorizationService : IClientAuthorizationService {

    public ClientAuthorizationService() {
        CurrentClient = new MobileServiceClient(Constants.ApiConstants.ApplicationUrl);
    }

    public IMobileServiceClient CurrentClient { get; set; }
}

This will allow for a mock of the client to be assigned when testing as ClientAuthorizationService is now dependent on abstractions and not implementation concerns.
//....

var clientAuthorizationService = new Mock<IClientAuthorizationService>();

var currentClient = new Mock<IMobileServiceClient>();

currentClient
    .Setup(_ => _.InvokeApiAsync(It.IsAny<string>(), null, HttpMethod.Get, null, It.IsAny<CancellationToken>()))
    .ReturnsAsync(token);

clientAuthorizationService
    .Setup(_ => _.CurrentClient)
    .Returns(currentClient.Object);

//.....

Also it is advised not to use async void except for event handlers
So the code under test needs to be updated accordingly.
private async Task LoginCommandAsync() {

    //.....

    CancellationToken ct;
    var result = await ClientAuthorizationService.CurrentClient.InvokeApiAsync(Constants.ApiConstants.AzureAuthMeData,
        null, HttpMethod.Get, null, ct);

    //....
}


Q:

Valor-software/ngx-bootstrap put a component inside dynamically created content

I'm trying to use valor-software/ngx-bootstrap to create a dynamic tab but I want to put a component's selector inside the dynamically created tab content,
In the documentation example we have:
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'demo-tabs-dynamic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './dynamic.html'
})
export class DemoTabsDynamicComponent {
  tabs: any[] = [
    { title: 'Dynamic Title 1', content: 'Dynamic content 1' },
    { title: 'Dynamic Title 2', content: 'Dynamic content 2', disabled:
true },
    { title: 'Dynamic Title 3', content: 'Dynamic content 3',
removable: true }
  ];

  addNewTab(): void {
    const newTabIndex = this.tabs.length + 1;
    this.tabs.push({
      title: `Dynamic Title ${newTabIndex}`,
      content: `Dynamic content ${newTabIndex}`,
      disabled: false,
      removable: true
    });
  }

}

And I want to be able to do something like this:
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'demo-tabs-dynamic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './dynamic.html'
})
export class DemoTabsDynamicComponent {
  tabs: any[] = [
    { title: 'Dynamic Title 1', content: 'Dynamic content 1' },
    { title: 'Dynamic Title 2', content: 'Dynamic content 2', disabled:
true },
    { title: 'Dynamic Title 3', content: 'Dynamic content 3',
removable: true }
  ];

  addNewTab(): void {
    const newTabIndex = this.tabs.length + 1;
    this.tabs.push({
      title: `Dynamic Title ${newTabIndex}`,
      content: `<my-component></my-component>`, // Here is the change
      disabled: false,
      removable: true
    });
  }
}

Angular sanitizes the component selector to string Is there any workaround?

A:

Actually I took this approach that doesn't need to path any html in the content
 <tabset >
    <tab *ngFor="let tabz of mainMenuTab.tabs"
         [heading]="tabz.title"
         [active]="tabz.active"
         (select)="tabz.active = true"
         (deselect)="tabz.active = false"
         [disabled]="tabz.disabled"
         [removable]="tabz.removable"
         (removed)="removeTabHandler(tabz)"
         [customClass]="tabz.customClass">
            <div [ngSwitch]="tabz?.content">
               <app-employees-menu *ngSwitchCase="'employee'">
               </app-employees-menu>
               <app-inventories-menu *ngSwitchCase="'inventory'">
               </app-inventories-menu>
               <app-customers-menu *ngSwitchCase="'customer'">
               </app-customers-menu>
            </div>
    </tab>
 </tabset>

So basically I already put all the possible tabs that I may have and based on which one I need to be shown I'll pass the content which act as a switch and in the template there is a switchCase that shows the tab that match the switchCase.


Q:

How to redirect page to href link on click without page load using jQuery

I am trying to redirect my php page to another php page without page load.
And these jQuery methods i have tried
1.This returns me alert but not redirecting to the page

<!DOCTYPE html>

 <title>AJax</title>

Click Here

2.This method is redirecting to the page but its getting load

$('a').click(function (event)
{
   event.preventDefault();

   var url = $(this).attr('href');
   $.get(url, function(data) {
window.location.href="http://localhost:8001/Test/redirect.php"
    });

 });

I want a simple solution to redirect my page without getting load using jQuery and AJAX.
Guide me to achive this :)

A:

Your question is not very clear about what you want to achieve, but as I understood

You want to load data to a page without changing the page
You want to change the URL in the browser address bar without loading another page

If I'm right about your intention, then you have to

Use AJAX to get the data (like $.get(): https://api.jquery.com/jquery.get/)
Use window.history.pushstate() (more on this: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)

So, implementing it with your functions may look like this:
$('a').click(function (event) {
   event.preventDefault();

   var url = $(this).attr('href');

   $.get(url, function(data) {
     // alert(data);
      window.history.pushState('stateObject', 'New Title', '/newpage')

      // code to display/render your new page content
      // supposing data holds valid HTML
      document.getElementById('content-container').innerHTML = data
    });
 });

In a sense you would like to create a router that loads your data, so I would point you towards using a jQuery router: https://www.npmjs.com/package/jqueryrouter


Q:

Caesar Cipher Java Program can't shift more than 23

I'm creating a program to do a Caesar Cipher, which shifts the letters in a word one time when I hit enter, and prompts the user to shift again or quit.
It works until I get to 23 shifts, then it starts using non-letter symbols for some reason, and I'm not sure why this is happening.
Any suggestions? Here is the code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Cipher {

    public static void main(String[] args) {

        // encrypted text
        String ciphertext;

        // input from keyboard
        Scanner keyboard = new Scanner(System.in);

        if (args.length > 0) {
            ciphertext = "";
            try {
                Scanner inputFile = new Scanner(new File(args[0]));
                while (inputFile.hasNext())
                    ciphertext += inputFile.nextLine();
            } catch (IOException ioe) {
                System.out.println("File not found: " + args[0]);
                System.exit(-1);
            }
        } else {
            System.out.print("Please enter text--> ");
            ciphertext = keyboard.nextLine();
        }

        // -----------------------------------------------------------------

        int distance = 0;  // how far the ciphertext should be shifted
        String next = "";  // user input after viewing
        while (!next.equals("quit")) {
            String plaintext = "";
            distance += 1;
            for (int i = 0; i < ciphertext.length(); i++) {
                char shift = ciphertext.charAt(i);
                if (Character.isLetter(shift)) {
                    shift = (char) (ciphertext.charAt(i) - distance);
                    if (Character.isUpperCase(ciphertext.charAt(i))) {
                        if (shift > '0' && shift < 'A') {
                            shift = (char) (shift + 26);
                            plaintext += shift;
                        } else {
                            plaintext += shift;
                        }
                    }
                    if (Character.isLowerCase(ciphertext.charAt(i))) {
                        if (shift > '0' && shift < 'a' && ciphertext.charAt(i) < 't') {
                            shift = (char) (shift + 26);
                            plaintext += shift;
                        } else {
                            plaintext += shift;
                        }
                    }
                } else {
                    plaintext += shift;
                }
            }

            System.out.println(ciphertext);

            // At this point, plaintext is the shifted ciphertext.
            System.out.println("distance " + distance);
            System.out.println(plaintext);
            System.out.println("Press enter to see the next option,"
                    + "type 'quit' to quit.");
            next = keyboard.nextLine().trim();
        }
        System.out.println("Final shift distance was " + distance + " places");
    }
}

A:

How does the shifting in your method work? Well, it exploits the fact that a char can, in Java, also be viewed as an int, a simple number.
Because of that you can do stuff like this:
char c = 'A';                                 // Would print: A
int cAsValue = (int) c;                       // Would print: 65
int nextValue = cAsValue + 1;                 // Would print: 66
char nextValueAsCharacter = (char) nextValue; // Would print: B

or even that:
int first = (int) 'A';                // Would print: 65
int second = (int) 'D';               // Would print: 68
int third = first + second;           // Would print: 133
char thirdAsCharacter = (char) third; // Would not print anything meaningful

Okay, now that we know how we can interpret char as int, let us analyze why 65 represents the character A and why 133 is nothing meaningful.
The keyword here is UTF-16. Characters in Java are encoded in UTF-16 and there are tables that list all characters of that encoding with their specific decimal number, like here.
Here is a relevant excerpt:

This answers why 65 represents A and why 133 is nothing meaningful.

The reason why you experience strange results after some shifts is that the alphabet only has a size of 26 symbols.
I think you would expect that it starts all over again and a shifted by 26 is again a. But unfortunately your code is not smart enough, it simply takes the current character and adds the shift to it, like that:
char current = 'a';
int shift = 26;

int currentAsInt = (int) current;        // Would print: 97
int shifted = currentAsInt + shift;      // Would print: 123
char currentAfterShift = (char) shifted; // Would print: {

Compare that to the relevant part in the table:

So after z does not come a again but rather {.

So after the mystery was solved, let's now talk about how to fix it and make your code smarter.
You can simply check the bounds, like "if it is greater than the value for 'z' or smaller than 'a', then get it back again into the correct range". We can do so easily by using the modulo operator given by %. It divides a number by another and returns the remainder of the division.
Here is how we can use it:
char current = 'w';
int shift = 100;
int alphabetSize = 26; // Or alternatively ('z' - 'a')

int currentAsInt = (int) current;          // Would print: 119
int shiftInRange = shift % alphabetSize;   // Would print: 22
int shifted = currentAsInt + shiftInRange; // Would print: 141 (nothing meaningful)

// If exceeding the range then begin at 'a' again
int shiftCorrected = shifted;
if (shifted > 'z') {
    shiftCorrected -= alphabetSize; // Would print: 115
}

char currentAfterShift = (char) shiftCorrected; // Would print: s

So instead of shifting by 100 we only shift be the relevant part, 22. Imagine the character going three rounds through the whole alphabet because 100 / 26 ~ 3.85. After those three rounds we go the remaining 0.85 rounds which are 22 steps, the remainder after dividing 100 by 26. That is exactly what the % operator did for us.
After going that 22 steps we could still exceed the bound, but maximally by one round. We correct that by subtracting the alphabet size. So instead of going 22 steps, we go 22 - 26 = -4 steps which emulates "going 4 steps to the end of the alphabet, then starting at 'a' again and finally going 18 steps to 's'".


Q:

Firebase Rules to read Specific Leaf / Child Node from Parent Nodes

My firebase database looks like this
"students" : {
  "firebase_key_1" : {
    "Name" : "blah blah",
    "Address" : "blah blah",
    "Roll No" : "blah blah",
    "Marks" : {
        "Sub1" : "blah",
        "Sub2" : "blah",
        "Sub3" : "blah",
        "Total" : "Total",
    },
    "class" : "blah blah",
    "Transportation" : "blah blah",
    "Department" : "blah blah",
},
  "firebase_key_2" : {
    "Name" : "blah blah",
    "Address" : "blah blah",
    "Roll No" : "blah blah",
    "Marks" : {
        "Sub1" : "blah",
        "Sub2" : "blah",
        "Sub3" : "blah",
        "Total" : "Total",
    },
    "class" : "blah blah",
    "Transportation" : "blah blah",
    "Department" : "blah blah",
},
  "firebase_key_3" : {
    "Name" : "blah blah",
    "Address" : "blah blah",
    "Roll No" : "blah blah",
    "Marks" : {
        "Sub1" : "blah",
        "Sub2" : "blah",
        "Sub3" : "blah",
        "Total" : "Total",
    },
    "class" : "blah blah",
    "Transportation" : "blah blah",
    "Department" : "blah blah",
}
}

I am using rest api to retrieve the data from firebase. Restapi url looks like https://domain.firebaseio.com/students.json?orderby="Marks/Total"&startAt=400
I have already indexed the Total in students via firebase rules. I am getting Result along with extra data such as name, class, roll no.
I want the output to be
    "firebase_key_1" : {
    "Marks" : {
        "Sub1" : "blah",
        "Sub2" : "blah",
        "Sub3" : "blah",
        "Total" : "Total",
    }
},
"firebase_key_2" : {
    "Marks" : {
        "Sub1" : "blah",
        "Sub2" : "blah",
        "Sub3" : "blah",
        "Total" : "Total",
    }
},
"firebase_key_3" : {
    "Marks" : {
        "Sub1" : "blah",
        "Sub2" : "blah",
        "Sub3" : "blah",
        "Total" : "Total",
    }
}

Is there anyway to do this via RestAPi or Rules.
Is there any rules that we can define what nodes to be read for example
{
 "users":{
   "students":{
      ".read" : ["$firebaseKey/Marks"],
      ".write" : true,
   }
   }

So that i can use Rest api to retrieve the required values from parent node.
Any other suggestion to do this will be wonderful.
Thanks in Advance

A:

The Firebase Database always returns complete nodes. It's not possible to get a subset of each node that matches your query. Either the entire node is returned, or it is not returned.
Typically this type of request indicates that you've merged multiple types of data that you should separate. In your case, it looks like you should have two top-level collections: students and studentMarks. Under students you keep the properties for each student, keyed by their student ID. Under studentMarks you keep the marks for each student, again keyed by their student ID.
So:
"students" : {
  "firebase_key_1" : {
    "Name" : "blah blah",
    "Address" : "blah blah",
    "Roll No" : "blah blah",
    "class" : "blah blah",
    "Transportation" : "blah blah",
    "Department" : "blah blah",
  },
  "firebase_key_2" : {
    "Name" : "blah blah",
    "Address" : "blah blah",
    "Roll No" : "blah blah",
    "class" : "blah blah",
    "Transportation" : "blah blah",
    "Department" : "blah blah",
  },
  "firebase_key_3" : {
    "Name" : "blah blah",
    "Address" : "blah blah",
    "Roll No" : "blah blah",
    "class" : "blah blah",
    "Transportation" : "blah blah",
    "Department" : "blah blah",
  }
},
"studentMarks":
  "firebase_key_1" : {
    "Sub1" : "blah",
    "Sub2" : "blah",
    "Sub3" : "blah",
    "Total" : "Total",
  },
  "firebase_key_2" : {
    "Sub1" : "blah",
    "Sub2" : "blah",
    "Sub3" : "blah",
    "Total" : "Total",
  },
  "firebase_key_3" : {
    "Sub1" : "blah",
    "Sub2" : "blah",
    "Sub3" : "blah",
    "Total" : "Total",
  }
}

Since you're using the same key between students and studentMarks you can easily ready both sets of data for a user. But now you can also just read just the properties for each user, or just the marks for a set of users.


Q:

python regular expression to match strings

I want to parse a string, such as:
package: name='jp.tjkapp.droid1lwp' versionCode='2' versionName='1.1'
uses-permission:'android.permission.WRITE_APN_SETTINGS'
uses-permission:'android.permission.RECEIVE_BOOT_COMPLETED'
uses-permission:'android.permission.ACCESS_NETWORK_STATE'

I want to get:
string1: jp.tjkapp.droidllwp`

string2: 1.1

Because there are multiple uses-permission, I want to get permission as a list, contains:
WRITE_APN_SETTINGS, RECEIVE_BOOT_COMPLETED and ACCESS_NETWORK_STATE.
Could you help me write the python regular expression to get the strings I want?
Thanks.

A:

Assuming the code block you provided is one long string, here stored in a variable called input_string:
name = re.search(r"(?<=name\=\')[\w\.]+?(?=\')", input_string).group(0)
versionName = re.search(r"(?<=versionName\=\')\d+?\.\d+?(?=\')", input_string).group(0)
permissions = re.findall(r'(?<=android\.permission\.)[A-Z_]+(?=\')', input_string)

Explanation:
name

(?<=name\=\'): check ahead of the main string in order to return only strings that are preceded by name='.  The \ in front of = and ' serve to escape them so that the regex knows we're talking about the = string and not a regex command.  name=' is not also returned when we get the result, we just know that the results we get are all preceded by it.
[\w\.]+?: This is the main string we're searching for. \w means any alphanumeric character and underscore.  \. is an escaped period, so the regex knows we mean . and not the regex command represented by an unescaped period.  Putting these in [] means we're okay with anything we've stuck in brackets, so we're saying that we'll accept any alphanumeric character, _, or ..  + afterwords means at least one of the previous thing, meaning at least one (but possibly more) of [\w\.].  Finally, the ? means don't be greedy--we're telling the regex to get the smallest possible group that meets these specifications, since + could go on for an unlimited number of repeats of anything matched by [\w\.].
(?=\'): check behind the main string in order to return only strings that are followed by '.  The \ is also an escape, since otherwise regex or Python's string execution might misinterpret '.  This final ' is not returned with our results, we just know that in the original string, it followed any result we do end up getting.


Q:

How to call 2 stored procedures using mysqli

Bascially I have a form with 2 select dropdown boxes and I want to populate the selections with 2 stored procedures that returns all the values via php. However, it seems like only the first select box is getting populated while the second one is not.
I have tested both stored procedure and they work fine.

  Name

    <select class="form-control" name="pokemonName" style="width:30%;">
      <?php
        require_once '../database/connection.php';
        $sqlNames = "CALL sp_selectAllPokemonName";
        $names = $con->query($sqlNames);
        while ($name = $names->fetch_assoc()){
          echo "<option value= '".$name['pokemonName']."'>".$name['pokemonName']."</option>";
        }
      //  $names->close();
      //  $con->close();
      ?>
    </select>

  Hour

    <select class="form-control" name="hour" style="width:30%;">
      <?php
        // query doesn't work here
        require_once '../database/connection.php';
        $sqlHours = "CALL sp_selectAllHour";
        $hours = $con->query($sqlHours);
        while ($hour = $hours->fetch_assoc()){
          echo "<option value= '".$hour['Id']."'>".$hour['Id']."</option>";
        }
      ?>
    </select>

connection.php
<?php
    require 'credentials.php';
    include '../ChromePhp.php';
    // Create connection
    //$con = mysqli_connect($servername, $username, $password, $dbname); // Procedural
    $con = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($con->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
        ChromePhp::warn('something went wrong!');
    }
?>

A:

This is an excerpt from my PDO tutorial, but the principle is applicable to any API:

There is one thing about stored procedures any programmer stumbles upon at first: every stored procedure always returns one extra result set: one (or many) results with actual data and one just empty. Which means if you try to call a procedure and then proceed to another query, then "Cannot execute queries while other unbuffered queries are active" error will occur, because you have to clear that extra empty result first.

So you have to advance to that extra result set, using mysqli_next_result
Just a call to $con->next_result() should do the trick. Note that you have to call it only after fetching all the data from result set.


Q:

Tips for working with Pre-1000 A.D. Dates in JavaScript

I'm curious if anyone has any good solutions for accurately building dates prior to the year 1000 A.D. - particularly the years 1 - 100 AD.
For example, if I want to build a date for the start of the 1st millenium, I can't just do...
new Date(Date.UTC(1,0,1,0,0,0,0));

because it tries to be "smart" and assume that 1 is 1901, which gives me...
Sun Dec 31 1900 18:00:00 GMT-0600 (CST)

The same thing goes for the year 99...
new Date(Date.UTC(99,0,1,0,0,0,0));

which becomes
Thu Dec 31 1998 18:00:00 GMT-0600 (CST)

Thoughts?

A:

Have you tried using the setUTC... functions on a date object after its creation?
setUTCDate()
setUTCFullYear()
setUTCMonth()
setUTCHours()
setUTCMinutes()
setUTCSeconds()

A:

Here is the basic solution I came up with. If a date is prior to year 1000, I just add a 1000 to it while constructing the date, then use setUTCFullYear() afterwards.
if (year >= 0 && year < 1000) {
  var d = new Date(Date.UTC(year + 1000,mon,day,hour,min,sec,0));
  d.setUTCFullYear(d.getFullYear() - 1000);
  return d;
}

1000 may be overkill since I was only having problems with pre-100 dates... but, whatever.


Q:

how to load image from java project's resource/images folder?

I am developing a shopping cart in Sprng MVC from where seller can upload products image with its description. I am able to upload images to webapp/resources/images folder. now I have to load all these images to dashboard page (home page) when any user open my site. I am not able to load these images from this location.
In my jsp I am writing final code like this:

how can I add this folder to classpath so it'll be available. I am using Spring MVC and MAVEN.
Please let me know how to achieve this.

A:

With Expression Language (EL) in JSP:

A:

I am able to fix this problem:
Added the following resources declaration to Spring configuration
<resources mapping="/resources/**" location="/resources/" />

and in jsp
<img src="<c:url value="/resources/images/product1.jpg" />" alt="" />

Thanks guys for your all help, your direction really helped me to get the answer for this problem.


Q:

Adding columns to multiple dataframes in a list in R

Apologies in advance, this is going to be a long set-up to get to the question. Not sure how to ask it simpler.
I am trying to plot 20 nMDS plots in ggplot using this structure. https://chrischizinski.github.io/rstats/vegan-ggplot2/
I can do this very easily for 1 dataframe. But I am trying to use lapply to go through these operations on all 20 of them.
I am at this part in the link- I have not edited the following chunk to fit my code:
data.scores <- as.data.frame(scores(vare.mds))  #Using the scores function from vegan to extract the site scores and convert to a data.frame
data.scores$site <- rownames(data.scores)  # create a column of site names, from the rownames of data.scores
data.scores$grp <- grp  #  add the grp variable created earlier
head(data.scores)  #look at the data

I would like to restructure these so that these actions apply to all of the dataframes in my list.
This is sample data:
##SETTING UP DATA ###
Z<- structure(list(site = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L), .Label = c("AYUNGON", "BINDOY"), class = "factor"), reserve_status = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Inside", "Outside",
"TURF"), class = "factor"), year = c(2012L, 2012L, 2012L, 2012L,
2012L, 2014L, 2014L, 2014L, 2014L, 2014L, 2015L, 2015L, 2015L,
2015L, 2015L, 2016L, 2016L, 2016L, 2016L, 2016L, 2017L, 2017L,
2017L, 2017L), transect = structure(c(347L, 352L, 357L, 362L,
367L, 345L, 351L, 355L, 360L, 365L, 346L, 349L, 356L, 361L, 366L,
348L, 353L, 358L, 363L, 368L, 344L, 350L, 354L, 359L), .Label = c("ACML1A0317",
"ACML1A0515", "ACML1A0516", "ACML1B0317", "ACML1B0515", "ACML1B0516",
"ACML2A0317", "ACML2A0515", "ACML2A0516", "ACML2B0317", "ACML2B0515",
"ACML2B0516", "ACML3A0317", "ACML3A0515", "ACML3A0516", "ACML3B0317",
"ACML3B0515", "ACML3B0516", "ALTN1A0317", "ALTN1A0515", "ALTN1A0516",
"ALTN1B0317", "ALTN1B0515", "ALTN1B0516", "ALTN2A0317", "ALTN2A0515",
"ALTN2A0516", "ALTN2B0317", "ALTN2B0515", "ALTN2B0516", "ALTN3A0317",
"ALTN3A0515", "ALTN3A0516", "ALTN3B0317", "ALTN3B0515", "ALTN3B0516",
"ALTN4A0317", "ALTN4A0515", "ALTN4A0516", "ALTN5A0317", "ALTN5A0515",
"ALTN5A0516", "ALTN6A0317", "ALTN6A0515", "ALTN6A0516", "ALTN6B0317",
"ALTN6B0515", "ALTN6B0516", "BICU1F0616", "BICU1F1214", "BICU1R0616",
"BICU1R1214", "BICU2R0616", "BICU2R1214", "BICU3F0616", "BICU3F1214",
"BICU3R0616", "BICU3R1214", "BIHM1F0412", "BIHM1F0511", "BIHM1F0616",
"BIHM1F0813", "BIHM1F1214", "BIHM1R0412", "BIHM1R0511", "BIHM1R0616",
"BIHM1R0813", "BIHM2F0412", "BIHM2F0511", "BIHM2F0616", "BIHM2F0813",
"BIHM2F1214", "BIHM2R0412", "BIHM2R0511", "BIHM2R0616", "BIHM2R0813",
"BIHM2R1214", "BIHM3R0412", "BIHM3R0511", "BIHM3R0616", "BIHM3R0813",
"BIHM3R1214", "BIHM4F0412", "BIHM4F0511", "BIHM4F0616", "BIHM4F0813",
"BIHM4F1214", "BIHM4R0412", "BIHM4R0511", "BIHM4R0616", "BIHM4R0813",
"BIHM4R1214", "BIHM5F0412", "BIHM5F0511", "BIHM5F0616", "BIHM5F0813",
"BIHM5F1214", "BIHM5R0412", "BIHM5R0511", "BIHM5R0616", "BIHM5R0813",
"BIHM5R1214", "BIHM6R0412", "BIHM6R0511", "BIHM6R0616", "BIHM6R0813",
"BIHM6R1214", "CMER1A0216", "CMER1A0415", "CMER1A0617", "CMER2A0216",
"CMER2A0415", "CMER2A0617", "CMER2B0216", "CMER2B0415", "CMER2B0617",
"CMER3A0216", "CMER3A0415", "CMER3A0617", "CMER3B0216", "CMER3B0415",
"CMER3B0617", "CMER4A0216", "CMER4A0415", "CMER4A0617", "CMER4B0216",
"CMER4B0415", "CMER4B0617", "CMER5A0216", "CMER5A0415", "CMER5A0617",
"CMER6A0216", "CMER6A0415", "CMER6A0617", "CMER6B0216", "CMER6B0415",
"CMER6B0617", "CSAG1F0316", "CSAG1F0414", "CSAG1F0415", "CSAG1F0617",
"CSAG1F0812", "CSAG1R0316", "CSAG1R0414", "CSAG1R0415", "CSAG1R0812",
"CSAG2R0316", "CSAG2R0414", "CSAG2R0415", "CSAG2R0617", "CSAG2R0812",
"CSAG3F0316", "CSAG3F0414", "CSAG3F0415", "CSAG3F0617", "CSAG3F0812",
"CSAG3R0316", "CSAG3R0414", "CSAG3R0415", "CSAG3R0617", "CSAG3R0812",
"CSAG4R0316", "CSAG4R0414", "CSAG4R0415", "CSAG4R0812", "CSAG5F0316",
"CSAG5F0414", "CSAG5F0415", "CSAG5F0617", "CSAG5F0812", "CSAG5R0316",
"CSAG5R0414", "CSAG5R0415", "CSAG5R0812", "CSAG6F0316", "CSAG6F0414",
"CSAG6F0415", "CSAG6F0617", "CSAG6F0812", "CSAG6R0316", "CSAG6R0414",
"CSAG6R0415", "CSAG6R0617", "CSAG6R0812", "CTAG1A0615", "CTAG1A0617",
"CTAG1A0713", "CTAG1A0716", "CTAG1B0615", "CTAG1B0617", "CTAG1B0713",
"CTAG1B0716", "CTAG1F0511", "CTAG1F0512", "CTAG1R0511", "CTAG1R0512",
"CTAG2A0615", "CTAG2A0617", "CTAG2A0716", "CTAG3A0615", "CTAG3A0617",
"CTAG3A0716", "CTAG3B0615", "CTAG3B0617", "CTAG3B0716", "CTCL1A0615",
"CTCL1A0617", "CTCL1A0716", "CTCL1B0615", "CTCL1B0617", "CTCL1B0716",
"CTCL1F0511", "CTCL1F0512", "CTCL1F0713", "CTCL1R0511", "CTCL1R0512",
"CTCL1R0713", "CTCL2A0615", "CTCL2A0617", "CTCL2A0716", "CTCL2B0615",
"CTCL2B0617", "CTCL2B0716", "CTCL2F0511", "CTCL2F0512", "CTCL2F0713",
"CTCL2R0511", "CTCL2R0512", "CTCL2R0713", "CTCL3A0615", "CTCL3A0617",
"CTCL3A0716", "CTCL3R0511", "CTCL3R0512", "CTCL3R0713", "CTCL4R0511",
"CTCL4R0512", "CTCL4R0713", "CTCL5A0615", "CTCL5A0617", "CTCL5A0716",
"CTCL5F0511", "CTCL5F0512", "CTCL5F0713", "CTCL5R0511", "CTCL5R0512",
"CTCL5R0713", "CTCL6A0615", "CTCL6A0617", "CTCL6A0716", "CTCL6B0615",
"CTCL6B0617", "CTCL6B0716", "CTCL6F0511", "CTCL6F0512", "CTCL6F0713",
"CTCL6R0511", "CTCL6R0512", "CTSN1A0615", "CTSN1A0617", "CTSN1A0716",
"CTSN1B0615", "CTSN1B0617", "CTSN1B0716", "CTSN2A0615", "CTSN2A0617",
"CTSN2A0716", "CTSN3A0615", "CTSN3A0617", "CTSN3A0716", "CTSN3B0615",
"CTSN3B0617", "CTSN3B0716", "MLBV1A0516", "MLBV1A0715", "MLBV1A0717",
"MLBV1B0516", "MLBV1B0715", "MLBV1B0717", "MLBV2A0516", "MLBV2A0715",
"MLBV2A0717", "MLBV3A0516", "MLBV3A0715", "MLBV3A0717", "MLBV3B0516",
"MLBV3B0715", "MLBV3B0717", "MLBV4A0516", "MLBV4A0715", "MLBV4A0717",
"MLBV4B0516", "MLBV4B0715", "MLBV4B0717", "MLBV5A0516", "MLBV5A0715",
"MLBV5A0717", "MLBV5B0516", "MLBV5B0715", "MLBV5B0717", "MLBV6A0516",
"MLBV6A0715", "MLBV6A0717", "MLCB1A0315", "MLCB1A0416", "MLCB1A0717",
"MLCB1B0315", "MLCB1B0416", "MLCB1B0717", "MLCB2A0315", "MLCB2A0416",
"MLCB2A0717", "MLCB3A0315", "MLCB3A0416", "MLCB3A0717", "MLCB3B0315",
"MLCB3B0416", "MLCB3B0717", "MLCB4A0315", "MLCB4A0416", "MLCB4A0717",
"MLCB4B0315", "MLCB4B0416", "MLCB4B0717", "MLCB5A0315", "MLCB5A0416",
"MLCB5A0717", "MLCB5B0315", "MLCB5B0416", "MLCB5B0717", "MLCB6A0315",
"MLCB6A0416", "MLCB6A0717","NAYU1F0417", "NAYU1F0514", "NAYU1F0515", "NAYU1F0712", "NAYU1F0816", "NAYU1R0417", "NAYU1R0514", "NAYU1R0515",
"NAYU1R0712", "NAYU1R0816", "NAYU2F0417", "NAYU2F0514", "NAYU2F0515",
"NAYU2F0712", "NAYU2F0816", "NAYU2R0415", "NAYU2R0417", "NAYU2R0514",
"NAYU2R0712", "NAYU2R0816", "NAYU3F0417", "NAYU3F0514", "NAYU3F0515",
"NAYU3F0712", "NAYU3F0816", "NAYU3R0417", "NAYU3R0514", "NAYU3R0515",
"NAYU3R0712", "NAYU3R0816", "NAYU4R0417", "NAYU4R0514", "NAYU4R0515",
"NAYU4R0712", "NAYU4R0816", "NAYU5F0417", "NAYU5F0514", "NAYU5F0515",
"NAYU5F0712", "NAYU5F0816", "NAYU5R0417", "NAYU5R0514", "NAYU5R0515",
"NAYU5R0712", "NAYU5R0816", "NAYU6R0514", "NAYU6R0515", "NAYU6R0712",
"NAYU6R0816"), class = "factor"),
    Abudefduf.bengalensis = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
    12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24), Abudefduf.sexfasciatus = c(25,
    26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
    13, 14, 15, 16), Abudefduf.sordidus = c(17, 18, 19, 20, 21, 22, 23,
    24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8), Abudefduf.vaigiensis = c(9,
10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)), row.names = c(NA, 24L), class = "data.frame")

df1<- matrix(data = c(1:32), nrow = 8, ncol = 4)
df2<- matrix(data = c(1:32), nrow = 8, ncol = 4)
df3<- matrix(data = c(1:16), nrow = 4, ncol = 4)
df4<- matrix(data = c(1:16), nrow = 4, ncol = 4)
Y<- list(df1, df2, df3, df4)

#NDMS, sqrt transformation, Bray default. Have to use pre-transformed data.
Y.nmds<- lapply(Y, metaMDS)

Now to Plot:
Y.nmds
data.scores.Y<- lapply(Y.nmds, as.data.frame(scores)) #Using the scores function from vegan to extract the site scores and convert to a data.frame- **this works.**

So now I have something that looks like this:
[[1]]
   value.NMDS1   value.NMDS2
1 -0.225596839  3.205973e-09
2 -0.135301170 -2.518875e-09
3 -0.062437097 -1.622530e-09
4 -0.002401206 -8.839924e-10
5  0.047920139 -2.649592e-10
6  0.090708349  2.614043e-10
7  0.127537199  7.144582e-10
8  0.159570625  1.108521e-09

[[2]]
   value.NMDS1   value.NMDS2
1 -0.225596839  3.205973e-09
2 -0.135301170 -2.518875e-09
3 -0.062437097 -1.622530e-09
4 -0.002401206 -8.839924e-10
5  0.047920139 -2.649592e-10
6  0.090708349  2.614043e-10
7  0.127537199  7.144582e-10
8  0.159570625  1.108521e-09

and I would like to use lapply to add columns to the above datascores dataframes, the data should come from the names in "Z" :
data.scores.Y$reserve<- lapply(data.scores.Y, function(x){ transform(x)<- Z$reserve_status})  # create a column of reserve status, from the rownames of Z - **DOESN'T WORK.**
data.scores.Y$year <- factor(Z$B_A) #create column of years-how I would do it for one dataframe
head(data.scores.Y)
```

to create something that looks like this (note I got rid of some rows):

```
[1]
   value.NMDS1   value.NMDS2   reserve    year
1 -0.225596839  3.205973e-09  inside     before
2 -0.135301170 -2.518875e-09  outside    before
3 -0.062437097 -1.622530e-09  inside     after
4 -0.002401206 -8.839924e-10  outside    after
5 0.047920139 -2.649592e-10   outside    after

[[2]]
    value.NMDS1  value.NMDS2   reserve    year
1 -0.225596839  3.205973e-09   inside     before
2 -0.135301170 -2.518875e-09   outside    before
3 -0.062437097 -1.622530e-09  inside     after
4  -0.002401206 -8.839924e-10   outside    after

I think once I get past this problem, I am able to get through the plotting. I have googled a lot of different solutions, but none seem to fully answer this question, or I can't figure out how to adapt those responses.
Thank you in advance. Syntax isn't my strong suit.

A:

Based on the comments, 'Y' is created as a list from splitting the 'Z' by the 'site' column
Y <- split(Z, Z$site)
Y.nmds <- lapply(Y, function(x) metaMDS(x[-(1:4)]))

Now, we can use Map to loop over the corresponding list elements of 'Y.nmds' with 'Y' to create the columns
lst1 <- Map(function(nmd, dat, site) {

         dat1 <- as.data.frame(scores(nmd))
         transform(dat1, site = site,
                         reserve_status = dat$reserve_status,
                         year = dat$year)

          }, Y.nmds, Y, names(Y))

-output
lst1
#$AYUNGON
#        NMDS1        NMDS2    site reserve_status year
#1  -0.5405524 -0.208839893 AYUNGON         Inside 2012
#2  -0.4679394 -0.127144729 AYUNGON         Inside 2012
#3  -0.4470720 -0.035047840 AYUNGON         Inside 2012
#4  -0.3723951 -0.004604424 AYUNGON         Inside 2012
#5  -0.3527766  0.062692135 AYUNGON         Inside 2012
#6  -0.3214464  0.117212445 AYUNGON         Inside 2014
#7  -0.2585269  0.118163340 AYUNGON         Inside 2014
#8  -0.2434562  0.173341542 AYUNGON         Inside 2014
#9   0.8334110 -0.008478317 AYUNGON         Inside 2014
#10  0.6918728 -0.048824777 AYUNGON         Inside 2014
#11  0.5889373  0.008377321 AYUNGON         Inside 2015
#12  0.4882185 -0.028821935 AYUNGON         Inside 2015
#13  0.4017254 -0.018024867 AYUNGON         Inside 2015

#$BINDOY
#        NMDS1         NMDS2   site reserve_status year
#14 -0.4973781  0.0312765162 BINDOY         Inside 2015
#15 -0.4901276 -0.0008288276 BINDOY         Inside 2015
#16 -0.4816021 -0.0282379296 BINDOY         Inside 2016
#17  0.1943789  0.0619863596 BINDOY         Inside 2016
#18  0.1924750  0.0348895563 BINDOY         Inside 2016
#19  0.1876516  0.0165441678 BINDOY         Inside 2016
#20  0.1853833  0.0016281922 BINDOY         Inside 2016
#21  0.1832898 -0.0126894179 BINDOY         Inside 2017
#22  0.1774036 -0.0243657601 BINDOY         Inside 2017
#23  0.1750507 -0.0370687919 BINDOY         Inside 2017
#24  0.1734749 -0.0431340651 BINDOY         Inside 2017


Q:

Would linux map the owner id of files coming from other computers to the account name in /etc/passwd?

When I use ls -al to show files downloaded from internet,
-rw-rw-r--  1  427 6011    7544 Jul 20  2006 INSTALL
-rw-rw-r--  1  427 6011    4229 Dec  9 15:36 Makefile.am
-rw-rw-r--  1  427 6011   27893 Dec 10 17:47 Makefile.in

I can see the owner and group ids are shown because there are no corresponding entries in /etc/passwd and /etc/group respectively.
I don't know much about linux and dare not to edit these files, I wonder if somebody already knows whether linux would map the owner id of files coming from other computers to the account name in /etc/passwd and display them when necessary (for example, when using ls -al)?

A:

The uid and gid there demonstrate the owner/group of the whoever created those files. In truth, since you downloaded them from the net and it appears to be a source tarball, they don't really matter. If you plan on using these files yourself in, lets say, your home directory you can just overwrite the uid and gid without having to fear that your computer will melt.
In this situation, what does matter is the fact that you are neither the owner nor part of the owning group for those files and the permissions are set so that you have no write access. To change this, you could simply change the owner/group via "sudo chown : *".


Q:

Laravel : Comparing datetime between two table while selecting record

I have Laravel app where i check the thread comment (thread_comment table) created date time and thread (thread table) last visit date.
i will select if any thread comment created date time is > thread last visit date, i will query them out.
The purpose of this is to notify the user how many new comments since their last visit to their thread.
Below is my code.
$new_thread_comment_count = DB::table('ap_thread')
            ->join('ap_thread_comment', 'ap_thread_comment.ThreadID', '=', 'ap_thread.ThreadID')
            ->where('ap_thread.CreatedBy', Auth::user()->UserID)
            ->where('ap_thread_comment.CreatedDateTime','>','ap_thread.last_visit_date')
            ->count();

My problem is, this doesn't work. If I change the operand to <, it will like display all records, which is incorrect.
Do i need to do any datetime convertion in where clause while comparing datetime between two table?
CREATE TABLE `ap_thread`
(`ThreadID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`ThreadTitle` text NOT NULL,
`Remark` text NOT NULL,
`CountryID` smallint(6) NOT NULL,
`last_visit_date` datetime NOT NULL,
`Thread_StatusID` tinyint(4) NOT NULL,
`StatusID` tinyint(4) NOT NULL,
`CreatedBy` bigint(20) NOT NULL,
`CreatedDateTime` datetime NOT NULL,
`EditedBy` bigint(20) NOT NULL,
`EditedDateTime` datetime NOT NULL,
`IsSelling` tinyint(1) NOT NULL,
PRIMARY KEY (`ThreadID`))

CREATE TABLE `ap_thread_comment` (
`Thread_CommentID` bigint(20) NOT NULL AUTO_INCREMENT,
`ThreadID` bigint(20) NOT NULL,
`StatusID` tinyint(4) NOT NULL,
`reply_to` bigint(20) unsigned NOT NULL,
`CreatedBy` bigint(20) NOT NULL,
`CreatedDateTime` datetime NOT NULL,
`Comment` text NOT NULL,
PRIMARY KEY (`Thread_CommentID`))

Sorry for the confusion. The thread table stores all the threads created by the users. Whereas thread_comment stores the comments that commented by other users.
What i'm trying to do is to select the total new comments for every threads that created by the logged in user by comparing ap_thread_comment CreatedDateTime is > ap_thread last_visit_date.

The last_visited_date will only be updated when the owner of the thread visited the thread.

A:

Solve it using
$new_thread_comment_count = DB::table('ap_thread')
            ->join('ap_thread_comment', 'ap_thread_comment.thread_id', '=', 'ap_thread.thread_id')
            ->whereRaw('ap_thread_comment.created_at > ap_thread.last_visit_date')
            ->where('ap_thread.created_by','=',Auth::user()->user_id)
            ->Count();


Q:

Sort multiple arrays based on an ID array

What i've got so far is basically 2 seperately built arrays with contents like these:
Arraygroup #1:
var nickName = ['Noah', 'Liam', 'Jacob', 'Mason', 'William',];
var lastLogin = ['03042015', '02042015', '02042015', '05032015', '16022015'];
var id = [0001, 0002, 0003, 0004, 0005];

Arraygroup #2:
var banStatus= [0, 0, 2, 1, 0];
var status = ['Online', 'Busy', 'Snooze', 'Offline', 'Offline'];
var id = [0003, 0005, 0001, 0004, 0002];

What i want to do is sort them based on the "id" array they both got, ( but sadly they are in the wrong order ).
The result should be something like this:
id[0] == 0001
nickName[0] == Noah
lastLogin[0] == 03042015
isBanned[0] = 2
status[0] = Snooze

A:

Create a List with two-element tuples. First element: the Id array, second element: integers 0 .. length of your array.
List<Tuple<int,int>> arraySortHelperList = new List<Tuple<int,int>>();
for(...)
{
     int id = ...
     arraySortHelperList.Add(new Tuple<int,int>(id, n++));
}

Sort this list based on the Id element.
Now the second elemnt are the sorted indices i.e. the first item in the sorted list will contain in its second element the index of the array slot which comes first.


Q:

R: conditional aggregate based on factor level and year

I have a dataset in R which I am trying to aggregate by column level and year which looks like this:
    City  State   Year   Status      Year_repealed   PolicyNo
    Pitt   PA     2001   InForce                        6
    Phil.  PA     2001   Repealed        2004           9
    Pitt   PA     2002   InForce                        7
    Pitt   PA     2005   InForce                        2

What I would like to create is where for each Year, I aggregate the PolicyNo across states taking into account the date the policy was repealed. The results I would then get is:
    Year    State PolicyNo
    2001     PA     15
    2002     PA     22
    2003     PA     22
    2004     PA     12
    2005     PA     14

I am not sure how to go about splitting and aggregating the data conditional on the repeal data and was wondering if there is a way to achieve this is R easily.

A:

It may help you to break this up into two distinct problems.

Get a table that shows the change in PolicyNo in every city-state-year.
Summarize that table to show the PolicyNo in each state-year.

To accomplish (1) we add the missing years with NA PolicyNo, and add repeals as negative PolicyNo observations.
library(dplyr)

df = structure(list(City = c("Pitt", "Phil.", "Pitt", "Pitt"), State = c("PA", "PA", "PA", "PA"), Year = c(2001L, 2001L, 2002L, 2005L), Status = c("InForce", "Repealed", "InForce", "InForce"), Year_repealed = c(NA, 2004L, NA, NA), PolicyNo = c(6L, 9L, 7L, 2L)), .Names = c("City", "State", "Year", "Status", "Year_repealed", "PolicyNo"), class = "data.frame", row.names = c(NA, -4L))

repeals = df %>%
  filter(!is.na(Year_repealed)) %>%
  mutate(Year = Year_repealed, PolicyNo = -1 * PolicyNo)
repeals
#    City State Year   Status Year_repealed PolicyNo
# 1 Phil.    PA 2004 Repealed          2004       -9

all_years = expand.grid(City = unique(df$City), State = unique(df$State),
                        Year = 2001:2005)

df = bind_rows(df, repeals, all_years)
#     City State Year   Status Year_repealed PolicyNo
# 1   Pitt    PA 2001  InForce            NA        6
# 2  Phil.    PA 2001 Repealed          2004        9
# 3   Pitt    PA 2002  InForce            NA        7
# 4   Pitt    PA 2005  InForce            NA        2
# 5  Phil.    PA 2004 Repealed          2004       -9
# 6   Pitt    PA 2001     <NA>            NA       NA
# 7  Phil.    PA 2001     <NA>            NA       NA
# 8   Pitt    PA 2002     <NA>            NA       NA
# 9  Phil.    PA 2002     <NA>            NA       NA
# 10  Pitt    PA 2003     <NA>            NA       NA
# 11 Phil.    PA 2003     <NA>            NA       NA
# 12  Pitt    PA 2004     <NA>            NA       NA
# 13 Phil.    PA 2004     <NA>            NA       NA
# 14  Pitt    PA 2005     <NA>            NA       NA
# 15 Phil.    PA 2005     <NA>            NA       NA

Now the table shows every city-state-year and incorporates repeals. This is a table we can summarize.
df = df %>%
  group_by(Year, State) %>%
  summarize(annual_change = sum(PolicyNo, na.rm = TRUE))
df
# Source: local data frame [5 x 3]
# Groups: Year [?]
#
#    Year State annual_change
#   <int> <chr>         <dbl>
# 1  2001    PA            15
# 2  2002    PA             7
# 3  2003    PA             0
# 4  2004    PA            -9
# 5  2005    PA             2

That gets us PolicyNo change in each state-year. A cumulative sum over the changes gets us levels.
df = df %>%
  ungroup() %>%
  mutate(PolicyNo = cumsum(annual_change))
df
# # A tibble: 5 × 4
#    Year State annual_change PolicyNo
#   <int> <chr>         <dbl>    <dbl>
# 1  2001    PA            15       15
# 2  2002    PA             7       22
# 3  2003    PA             0       22
# 4  2004    PA            -9       13
# 5  2005    PA             2       15


Q:

Unsure how to break down this assignment task

A particular Unix kernel operation handles disk I/O by allowing independent user
processes to place I/O request blocks (IORB) in a linked list. The order in which these
requests are serviced depends on their scheduling priority. The scheduling strategy is
adaptive, which simply means that the kernel may carry out different computations at
different times in order to calculate the priority value for each element of the list.
You are required to design, implement and test a C function sort list()on Unix/Linux,
which will sort such a list either in ascending or descending order according to the preference
order computed by whatever function is passed as its second argument. The first
argument is to be a pointer to the head of the list. Since the kernel has other structures
with pointers to IORB blocks, the list must be sorted in place.

A:

This seems to be begging for a selection sort. Go through the entire list to find the smallest element (according to the comparison function). Take that element out of the list, and add it at the end of the list. Then repeat the process, each time finding the smallest element of the remaining list, and putting it at the end.
For example, if you have a list of 10 elements, then find the smallest of the 10, and move it to the end. Then find the smallest of the first 9 elements, and move it to the end. Repeat until there's only 1 element, which gets moved to the end.


Q:

ValueError: not enough values to unpack (expected 2, got 1) Odoo 11 Costum Report

Im facing this Probleme After Using my Costum report
here is the code
lass carnetcheque(models.Model):
    _name = 'carnet.c'
cheque_id = fields.One2many(comodel_name='cheq.c', string='Carnet cheq', inverse_name='carnetcheque_id')
code_cheq = fields.Char(string='Code Chèque',default="")
nbr_feuill = fields.Char(string='Nombre feuille')
date_debut_carnet = fields.Date(string='Date début Carnet')
status = fields.Selection(selection=[('en cours', 'En Cours'),
                                     ('terminé', 'Terminé')])
@api.multi
def imprimer_report(self):

    return self.env.ref('car_report_id').report_action(self, data=data, config=False)

About the XML files
<?xml version="1.0" encoding="utf-8"?>

    <report
            id="car_report_id"
            string="Report of adham"
            model="carnet.c"
            report_type="qweb-pdf"
            file="carnet.c.carnet_report_id"
            name="carnet.c.carnet_report_id"
            menu="False"
    />

</data>

The Action Id
<template id="car_report_id">

Would you please help

A:

You have to put your module_name before "car_report_id" in self.env.ref() like that:
self.env.ref('module_name.car_report_id').report_action(self, data=data, config=False)

Good luck.


Q:

Trying to autofill a data form with selenium and python

I am trying to build an automation script with python and selenium. Here is the code so far. I have sensitive info blanked out for privacy reasons. I basically want the handlingunit box to be autofilled with HandlingUnit variable.
from selenium import webdriver
from selenium.webdriver.common.by import By

OriginZip = 99501
DestinationZip = 94016
HandlingUnit = 1

driver = webdriver.Chrome(r"C:\Users\*******\Desktop\WebAutomation\chromedriver")
driver.maximize_window()

driver.get("***********")
driver.implicitly_wait(1)

#Login Page
driver.find_element(By.XPATH, "//button[@id='dropdownMenuButton']").click()
driver.find_element(By.XPATH, "//input[@id='UserName']").send_keys('*******')
driver.find_element(By.XPATH, "//input[@id='Password']").send_keys('*******')
driver.find_element(By.XPATH, "//button[@class='btn btn-primary btn-block']").click()

#2nd Page
driver.find_element(By.XPATH, "//input[@id='OriginZip']").send_keys(OriginZip)
driver.find_element(By.XPATH, "//input[@id='DestinationZip']").send_keys(DestinationZip)
driver.find_element(By.XPATH, "//button[@class='btn btn-secondary form-control']").click()

#3rd Page
driver.refresh()  #<-- Add this to fix
driver.find_element(By.XPATH, "//input[@id='handlingunits']").send_keys(HandlingUnit) #here is where the error occurs

Here is a picture of the 3rd page

The error that appears:
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=80.0.3987.87)

I've tried adding an implicity_wait method, as well as finding elements by ID. Anyone know the proper solution to this?

A:

you can try this-

1 .Refresh you page before entering data.
2.Try to use CSS instead of xpath
3.use try and catch

for e.g.
try:
driver.find_element_by_css_selector("#handlingunits']").send_keys(HandlingUnit)

except (StaleElementReferenceException):

     wait=WebDriverWait(driver, 5,ignored_exceptions=ignored_exceptions).until(..your code))
     driver.find_element_by_css_selector("#handlingunits").send_keys(HandlingUnit)

hope this helps


Q:

Windows Universal App - MediaElement and M3U

is it possible to open up a m3u webradio stream in a MediaElement class in Windows 10?
Sample stream would be
http://www.antenne.de/webradio/channels/top-40.m3u
Opening normal mp3 in the internet work perfect but i do not get any m3u file opened.
Kind regards
Michael

A:

In m3u file (playlist file), there are often links point out to the source of audio. You need to get the file, open, parse it to get urls, and supply one of them to MediaElement. Its the same when you try to streaming video.


Q:

Where can i find the Ubuntu-touch 14.04 changelogs

I am trying to find the changelogs for the Ubuntu touch 14.04 dailys builds.
Please advise.
Thanks!

A:

okay so here is what I wanted. Someone from canonical on IRC #ubuntu-touch provided it. With the comment that that link isn't to be treated as a 'stable' channel. I guess its mostly meant for Canonical employees. Still, its usefull to me for testing purposes, so I thought I'd share:
people.canonical.com/~j-lallement/touch/changes/


Q:

How can I improve my algorithm runtime? cpmoptimithe not to propose

I need to find all the combinations flowers. Number of flowers only odd. Purchase amount not greater than the predetermined.
def bouquets(narcissus_price, tulip_price, rose_price, summ):
    count_combinations = 0
    for n in xrange(int(summ / narcissus_price) + 1):
        for t in xrange(int(summ / tulip_price) + 1):
            if n * narcissus_price + t * tulip_price > summ:
                break
            for r in xrange([1,0][(n + t) % 2], int(summ / rose_price) + 1, 2):
                if n * narcissus_price + t * tulip_price + r * rose_price > summ:
                    break
                elif (n + t + r) & 1:
                    count_combinations += 1
    return count_combinations

print bouquets(200, 300, 400, 100000) == 3524556 # large run-time

A:

Reduce the iteration range for tulips - rather than iterating to summ // tulip_price you can stop at (summ - n * narcissus_price) // tulip_price
You can count the number of possible values for r without enumerating them

Example:
def bouquets(n_price, t_price, r_price, total_price):
    """
    Count how many n, t, r (integers >= 0) exist
    such that
      n * n_price + t * t_price + r * r_price <= total_price
    and
      n + t + r is odd
    """
    count = 0

    max_n = total_price // n_price
    for n in xrange(max_n + 1):
        rem_n = total_price - n * n_price
        max_t = rem_n // t_price
        for t in xrange(max_t + 1):
            rem_t = rem_n - t * t_price
            max_r = rem_t // r_price
            min_r = (n + t + 1) % 2
            count += (max_r - min_r) // 2 + 1
    return count

On the given test input, this reduces the runtime from 2.33s to 67.2ms (about 35 times faster).


Q:

How can I loop through a string two lines at a time (two carriage returns per iteration)?

I want to loop through a string two lines at a time. I know I can loop through each line in a string by splitting on carriage return with the following:
For Each line As String In Split(myString, vbCrLf)
 //do something with line
 Continue For
End If

How might I iterate through a string two lines at a time? Do I have to use two loops?

A:

You can't do the loop you are after with a For..Each loop as the definition of that loop is to loop through each element.
You need to use an old-fashioned For loop with a counter and a Step instruction.
Dim stringArray As String() = Split(myString, vbCrLf)

For loopCounter As Integer = 0 To stringArray.Length - 2 Step 2
    If (loopCounter + 2 >= stringArray.Length) Then
        ' Need to handle the scenario for an Odd number of items in the array
        Debug.WriteLine($"{stringArray(loopCounter)}")
    Else
        Debug.WriteLine($"{stringArray(loopCounter)}:{stringArray(loopCounter + 1)}")
    End If
Next


Q:

Python Wheels on linux (how? and why?)

I know that wheels are binary version of a module uploaded on PyPI.
with pip install

On Windows: I get wheels downloaded and installed.
On Ubuntu: I should get the source distribution of the package BUT in some cases I get wheels.
On fedora: Tricky I have to install with dnf

I tried to add wheels to my package as well. But I am only able to upload wheels for windows.

Why do some packages provide wheels for Linux platform?
Is this okay? Providing binaries instead of the source?
Why I cannot provide wheels?

Note: I know a bit about Fedora rpm packages. I am interested now in wheels on Ubuntu.

A:

Why do some packages provide wheels for Linux platform?

Why shouldn't they, as long as source distributions are available as well? :)
Your question is not clear. If you meant

Why do some packages provide platform-specific wheels for Linux platform instead of platfom-independent ones?

then take a look at this question and its answers. If not, please clarify your question.

On Ubuntu: I should get the source distribution of the package BUT in some cases I get wheels.

Try using:
pip install --no-binary :all: somepackage

This should make pip download a source distribution if it exists on PyPI. I don't know why there are no source packages for PyQt5 on PyPI, probably because they are not installable with pip and need a whole toolchaing for compilation.

Is this okay? Providing binaries instead of the source?

It's okay as long as you provide both binaries and the source. I suggest you doing so.

Why I cannot provide wheels?

Try python setup.py bdist_wheel. You need to install wheel package (on PyPI) to make it work. If your package supports both Python 2 and 3 and contains no C extensions, append the --universal option to make a "universal wheel".
Replace bdist_wheel with sdist to make a source distribution. It will create an archive in dist directory.

sdist creates the archive of the default format for the current platform. The default format is a gzip’ed tar file (.tar.gz) on Unix, and ZIP file on Windows.
You can specify as many formats as you like using the --formats option, for example:
python setup.py sdist --formats=gztar,zip

to create a gzipped tarball and a zip file

(Quote from https://docs.python.org/3/distutils/sourcedist.html)

More info about packaging and wheels is available here: https://packaging.python.org/distributing/#packaging-your-project


Q:

Cannot invoke `join` with an argument list of type (String, [String]) in Swift 2.0

var specializationTitles = ["a", "b", "c", "d"]
let outputString = join(" / ", specializationTitles)

got an error:

Cannot invoke join with an argument list of type (String, [String])

How to solve this?

A:

let separator = " / "
let outputString = separator.join(specializationTitles)

With Xcode7beta6:
specializationTitles.joinWithString(" / ")

With Xcode7 release version:
specializationTitles.joinWithSeparator(" / ")


Q:

Volatile Struct Semantics

Is it sufficient to declare an instance of a structure-typed variable as volatile (if its fields are accessed in re-entrant code), or must one declare specific fields of the structure as volatile?
Phrased differently, what are the semantic differences (if any) between:
typdef struct {
  uint8_t bar;
} foo_t;

volatile foo_t foo_inst;

and
typedef struct{
  volatile uint8_t bar;
} foo_t;

foo_t foo_inst;

I recognize that declaring a pointer-typed variable as volatile (e.g. volatile uint8_t * foo) merely informs the compiler that the address pointed-to by foo may change, while making no statement about the values pointed to by foo. It is unclear to me whether an analogy holds for structure-typed variables.

A:

In your example, the two are the same.  But the issues revolve around pointers.
First off, volatile uint8_t *foo; tells the compiler the memory being pointed to is volatile.  If you want to mark the pointer itself as volatile, you would need to do uint8_t * volatile foo;
And that is where you get to the main differences between marking the struct as volatile vs marking individual fields.  If you had:
typedef struct
{
    uint8_t *field;
} foo;

volatile foo f;

That would act like:
typedef struct
{
    uint8_t * volatile field;
} foo;

and not like:
typedef struct
{
    volatile uint8_t *field;
} foo;

A:

if you declare  a structure with volatile then all its  members  will also be volatile


Q:

How can I use UIWebView in Objective-C to display a Webpage

I've been trying to implement UIWebView into my application for a while now but when I do my application crashes upon startup.
 My code is:
-(void)viewDidLoad {
[super viewDidLoad];
NSString *urlAdress=@"http://www.facebook.com";

NSURL *url = [NSURL URLWithString:urlAdress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[webView loadRequest:requestObj];

The Debugger says Thread 1: Stopped at breakpoint 4

A:

Your problem is that you have breakpoints set.  See the blue arrow in the narrow column immediately left of your code?  You have three of them set.  You can disable the break point by clicking on the blue breakpoint arrow so that it dims (disabled).  You can remove the breakpoint by right clicking on the blue arrow and removing it.  A second way to remove it is to click and drag the breakpoint into the main window of your code, causing it to use the same dissolve animation used on the Mac OS X dock when you remove an item from it.


Q:

Get selected text in a UITextView

I have a UITextView, and I want to allow the user to highlight a portion of text and copy it with a button instead of using the default Apple method. The problem is that I can't get the text within the selected range.
Here's what I have:
@IBAction func copyButton(_ sender: Any) {
    let selectedRange: UITextRange? = textView.selectedTextRange
    selectedText = textView.textInRange(selectedRange)
    UIPasteboard.general.string = selectedText
}

But I'm getting

UITextView has no member textInRange

and I'm not sure what I should be using instead.

A:

What is happening is that UITextView method textInRange have been renamed to text(in: Range) since Swift 3. Btw you forgot to add the let keyword in your sentence:
if let range = textView.selectedTextRange {
    UIPasteboard.general.string = textView.text(in: range)
}


Q:

Creating multiple image SRC element with JavaScript

Image links from the database are registered this way:
Here are sample apartment pictures {img="/path/photo1.jpg" alt="I am Photo Title"} and {img="/path/photo2.jpg" alt="I am Photo Title #2"}

While printing on the screen:
Here are sample apartment pictures  and

How is this changed with JavaScript?
I have studied many questions about this, but I have not found it.

A:

In jquery you can write it like this:
first of all let's call the img object from the DB by naming it 'imgObj' for the example...
Then:

var imgObj = { img : 'http://via.placeholder.com/350x150', alt : 'alternative text' };

$(document).ready(function() {
  $('.img').attr('src', imgObj.img);
});

UPDATE: (For couple images)
Now i building the html as string (using the img object from the db) before i append it to the DOM.
For instance:

var imgObj =
[{ img : 'http://via.placeholder.com/350x150', alt : 'alternative text', class:'img-1' },
 { img : 'http://via.placeholder.com/350x150', alt : 'alternative text', class:'img-2' },
 { img : 'http://via.placeholder.com/350x150', alt : 'alternative text', clsas:'img-3' }];

 var htmlOutput = "";

$(document).ready(function() {

  for(var i = 0; i < imgObj.length; i++)
  {
      var imageElement = '';
      htmlOutput += imageElement.replace('#SRC#', imgObj[i].img).replace('#ALT#', imgObj[i].alt).replace('#CLASS#',imgObj[i].class);
  }

  // Append the HTML string to the dom
  $('.img-container').append(htmlOutput);
});