Getting NPE in 2D Game thread

Question: I keep getting a NPE when I run this very basic 2D game. It has something to do with the Key Events but I am not sure how to fix this. Can someone help me? It says the NPE is on this line if (_input.up.isPressed()) {
Here is the InputHandler Class
public class InputHandler implements KeyListener {

    public InputHandler(Game game) {
        game.addKeyListener(this);
    }

    public class Key {
        private boolean pressed = false;

        public void toggle(boolean isPressed) {
            pressed = isPressed;
        }

        public boolean isPressed() {
            return pressed;
        }
    }

    // public List<Key> keys = new ArrayList<Key>();
    public Key up = new Key();
    public Key down = new Key();
    public Key left = new Key();
    public Key right = new Key();

    public void keyPressed(KeyEvent e) {
        toggleKey(e.getKeyCode(), true);
    }

    public void keyReleased(KeyEvent e) {
        toggleKey(e.getKeyCode(), false);
    }

    public void keyTyped(KeyEvent e) {

    }

    public void toggleKey(int keyCode, boolean isPressed) {
        if (keyCode == KeyEvent.VK_W) {
            up.toggle(isPressed);
        } else if (keyCode == KeyEvent.VK_S) {
            down.toggle(isPressed);
        } else if (keyCode == KeyEvent.VK_A) {
            left.toggle(isPressed);
        } else if (keyCode == KeyEvent.VK_D) {
            right.toggle(isPressed);
        }
    }
}

here is the Player Class
public class Player extends Mob {

    private InputHandler _input;
    private int _speed;
    private int _r = 10;
    private int _x, _y;

    public Player(int x, int y, int speed, InputHandler input) {
        super("Player", x, y, 1);
        _input = input;
        _speed = speed;
        _x = x;
        _y = y;
    }

    public boolean hasCollided(int dx, int dy) {
        return false;
    }

    public void update() {
        int dx = 0;
        int dy = 0;

        if (_input.up.isPressed()) {
            dy--;
        } else if (_input.down.isPressed()) {
            dy++;
        } else if (_input.left.isPressed()) {
            dx--;
        } else if (_input.right.isPressed()) {
            dx++;
        }

        if (dx != 0 || dy != 0) {
            move(dx, dy);
            isMoving = true;
        } else {
            isMoving = false;
        }

        if (_x < _r)
            _x = _r;
        if (_y < _r)
            _y = _r;
        if (_x > Game.WIDTH - _r)
            _x = Game.WIDTH - _r;
        if (_y > Game.HEIGHT - _r)
            _y = Game.HEIGHT - _r;
    }

    public void render(Graphics2D g) {
        g.setColor(Color.BLACK);
        g.fillOval(x - _r, y - _r, 2 * _r, 2 * _r);

        g.setStroke(new BasicStroke(3));
        g.setColor(Color.GRAY);
        g.drawOval(x - _r, y - _r, 2 * _r, 2 * _r);
        g.setStroke(new BasicStroke(1));
    }
}

here is the game class which creates the player
public class Game extends Canvas implements Runnable {

    private static Game _instance;
    private static final String TITLE = "ProjectG";
    public static final int WIDTH = 960;
    public static final int HEIGHT = WIDTH * 3 / 4;
    private static final int SCALE = 1;
    // to make it have a higher resolution double the width and height but half
    // the scale. You are doubling the width and height but keeping the same
    // window size by reducing the scale
    public static final Dimension SIZE = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);

    private static final int UPDATE_RATE = 60;
    private static final int RENDER_RATE = 60;

    private JFrame _frame;
    private Thread _thread;
    private boolean _running = false;

    private int _tps = 0;
    private int _fps = 0;
    private int _totalTicks = 0;

    private BufferedImage image;
    private Graphics2D g;
    public InputHandler input;

    private Player player;

    public Game() {
        _instance = this;

        setPreferredSize(SIZE);
        setMinimumSize(SIZE);
        setMaximumSize(SIZE);

        _frame = new JFrame(TITLE);
        _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        _frame.setLayout(new BorderLayout());
        _frame.add(_instance, BorderLayout.CENTER);
        _frame.pack();

        _frame.setResizable(false);
        _frame.setLocationRelativeTo(null);
        _frame.setVisible(true);

        player = new Player(Game.WIDTH / 2, Game.HEIGHT / 2, 1, input);
    }

    public synchronized void start() {
        _running = true;
        _thread = new Thread(this, TITLE + "_main");
        _thread.start();
    }

    public synchronized void stop() {
        _running = false;

        if (_thread != null) {
            try {
                _thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void run() {
        double lastUpdateTime = System.nanoTime();
        double lastRenderTime = System.nanoTime();

        final int ns = 1000000000;
        final double nsPerUpdate = (double) ns / UPDATE_RATE;
        final double nsPerRender = (double) ns / RENDER_RATE;
        final int maxUpdatesBeforeRender = 1;

        int lastSecond = (int) lastUpdateTime / ns;
        int tickCount = 0;
        int renderCount = 0;

        image = new BufferedImage(WIDTH * SCALE, HEIGHT * SCALE, BufferedImage.TYPE_INT_RGB);
        g = (Graphics2D) image.getGraphics();

        while (_running) {
            long currTime = System.nanoTime();
            int tps = 0;

            while ((currTime - lastUpdateTime) > nsPerUpdate && tps < maxUpdatesBeforeRender) {
                update();
                tickCount++;
                _totalTicks++;
                tps++;
                lastUpdateTime += nsPerUpdate;
            }

            if (currTime - lastUpdateTime > nsPerUpdate) {
                lastUpdateTime = currTime - nsPerUpdate;
            }

            float interpolation = Math.min(1.0F, (float) ((currTime - lastUpdateTime) / nsPerUpdate));
            render(interpolation);
            draw();
            renderCount++;
            lastRenderTime = currTime;

            int currSecond = (int) (lastUpdateTime / ns);
            if (currSecond > lastSecond) {
                _tps = tickCount;
                _fps = renderCount;
                tickCount = 0;
                renderCount = 0;
                lastSecond = currSecond;
                System.out.println(_tps + " TPS " + _fps + " FPS");
            }

            while (currTime - lastRenderTime < nsPerRender && currTime - lastUpdateTime < nsPerUpdate) {
                Thread.yield();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                currTime = System.nanoTime();
            }
        }
    }

    public void update() {
        player.update();
    }

    public void render(float interpolation) {
        BufferStrategy bs = getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(3);
        }

        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
        g.setColor(Color.BLACK);
        g.drawString("TPS: " + _fps + " FPS: " + _fps, 10, 20);

        player.render(g);
    }

    public void draw() {
        Graphics g2 = this.getGraphics();
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
    }

    public Game getGame() {
        return this;
    }
}

Comment: How are you creating your players>?
Comment: @SotiriosDelimanolis added the class where the player is created
Answer: You haven't initialized input, so what you pass to
player = new Player(Game.WIDTH / 2, Game.HEIGHT / 2, 1, input);

is null. You need to initialize it before
input = new InputHandler(this);

Comment: i initialized `input` in the game constructor and it is still giving me the same one.
Comment: Nevermind i placed the initialization after the player was initialized so I moved it above and it worked. But the player does not move when I press the keys

Getting NPE in 2D Game thread


Need adventure map help

Question: I'm working on an adventure map. I have characters that when you click on a sign that says: (Character name here) Click to talk. I used this command:
/give @p sign 1 0 {
    BlockEntityTag: {
        Text1: "{\"text\":\"Wounded Man\",\"color\":\"red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"say Wounded man: Who are you? Doesn't matter. There's a storm coming I suggest You find Shelter.\"}}",
        Text2: "{\"text\":\"Click to talk\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"say New Quest: Find Shelter\"}}",
        Text3: "{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"particle fireworksSpark\"}}"
    },
    display: {
        Name: "Custom Sign"
    }
}

I wanted it to say: (@) Wounded Man: A storm's coming I suggest you find shelter..., but instead it says: (LordSockingham) Wounded man: A storm's coming and I suggest you find shelter.... Any ideas?
Comment: I think this might be a result of the fact that it's the player that is performing the `/say` command. There might be some magic you could work with a `/tellraw`, but I'm not certain
Answer: The problem is that the player is the one who is running the command with JSON commands. One possible workaround is the /trigger command:
Before anything else, once:
/scoreboard objectives add TalkToWoundedGuy trigger
/summon ArmorStand ~ ~ ~ {CustomName:"O"}

On a repeatingCommandBlock/chainCommandBlock loop, in order:
/scoreboard players enable @a TalkToWoundedGuy
/execute @p[score_TalkToWoundedGuy_min=1] ~ ~ ~ execute @e[name=O] ~ ~ ~ [all the 'say' commands you want, on different command blocks]
/execute @p[score_TalkToWoundedGuy_min=1] ~ ~ ~ [all the other commands you want, on different command blocks]
/scoreboard players set @a TalkToWoundedGuy 0

On the sign:
{Text1:"{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/trigger TalkToWoundedGuy set 1\"}}"

Answer: You should use the /tellraw command instead of /say for greater control of content.
For example, you would cause the player to run the following command:
/tellraw @a {"text":"[Wounded Man]: A storm's coming I suggest you find shelter..."}

Output:

[Wounded Man]: A storm's coming I suggest you find shelter...

You /give command would instead become:
/give @p sign 1 0 {BlockEntityTag: {Text1: "{\"text\":\"Wounded Man\",\"color\":\"red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"tellraw @a {\\\"text\\\":\\\"[Wounded Man]: A storm's coming I suggest you find shelter...\\\"}\"}}",Text2: "{\"text\":\"Click to talk\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"say New Quest: Find Shelter\"}}",Text3: "{\"clickEvent\":{\"action\":\"run_command\",\"value\":\"particle fireworksSpark\"}}"},display: {Name: "Custom Sign"}}

Answer: Tellraw runs from the console I believe. That should work if you're able to implement it into your script.

Need adventure map help


Manipulating list of dictionary in a single line list comprehension

Question: I have a list like below:
l = [{'Value': 'value1', 'Key': 'key1'}, {'Value': 'value2', 'Key': 'key2'}, {'Value': 'value3', 'Key': 'key3'}]

I want a output list as below:
lst = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]

My code is as below:
lst = []
for item in l:
    key = item["Key"]
    value = item["Value"]
    dict = {}
    dict[key] = value
    lst.append(dict)

Is it possible to do the same in a single line with list comprehension?
Answer: l = [{'Value': 'value1', 'Key': 'key1'}, {'Value': 'value2', 'Key': 'key2'}, {'Value': 'value3', 'Key': 'key3'}]

>>> [{item['Key']: item['Value']} for item in l]
[{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]


MYSQL restrict user access to information_schema

Question: I have a MySQL server (Server version: 5.1.68-community; MySQL client version: 5.0.51a).  Is there any way to restrict ALL access to information_schema for all users?
What happens is that, some customer sites are getting hacked frequently through SQL Injection and they can get the database structure from information_schema table/view.  Of course, we need to change the PHP codes to prevent SQL Injection, but still I would like to restrict access to information_schema server-wide.
Please guide me... thanks in advance
Answer: The INFORMATION_SCHEMA is a virtual database that holds meta-information about all databases accessible to current user. I.e. it's build dynamically according to user's permissions. It isn't real database. You should not try to change permissions to it in any case - it's updated dynamically according to server's state.
So your question has little sense. If someone will compromise some of users and get system control with it's permissions, he will be able to access to INFORMATION_SCHEMA for that user by definition (as that user can access any thing which is allowed by it's permissions - INFORMATION_SCHEMA is "a projection" of user's permissions).
Comment: You should realize: if SQL injection _was successful_ - then there's no way to prevent user from using it's own permissions. `INFORMATION_SCHEMA` is just a projection. If user has access to some table(s) - then he'll do that even without accessing that database. In your case, he'll just use `SHOW TABLES`
Comment: thank you very much for your quick response.  My issue is not about someone compromising other user.  But with SQL Injection, anybody can inject an sql statement like `....%20union%20select%201,group_concat(table_name),3%20%20from%20information_schema.tables%20where%20table_schema=database()` (taken from an actual injection happened to my site) to PHP code and get the structure of the current database. I totally understand that vulnerability in the PHP code has to be fixed, but if we could restrict the SELECT privilege (at least) for all users from information_schema, will be safer.
Comment: You are absolutely right and I totally agree with you... Regarding the sample Injection, with this they can get the table list and then go for another injection to get data, and then to add/edit/delete on these tables, we will be running into trouble.
Answer: One cannot prevent access to the information_schema (yet),
but in the case of sql-injections through GET Request, it is easy to do a:
RewriteCond %{REQUEST_FILENAME}   !handle_error\.php
RewriteCond %{QUERY_STRING}   information_schema
RewriteRule  ^(.*?)          /handle_error.php [R=301,L]

in your .htaccess and this should save one some headache.
Comment: Then if I don't want a link to be opened, I'll just add "information_schema" to it. Example: I use "information_schema" as my nickname in your website, and any link with my nickname in it will be blocked. Same goes if I put. Plus, it gives no protection against POST
Comment: that's the choice of the website developer, your use case is probably never encountered, it's not necessary that pages will be displayed with the nickname in the querystring.
Otherwise you're fully right, cannot disagree.


Local and production versions of php and mysql using git

Question: I have a question regarding how to set up local and production versions of a WordPress website that uses, PHP an MySQL.
I want to have these two versions (local and production) use different databases because we can test.
I will be using git to push my changes up to the server.
I have MySQL installed locally, and a webserver set up locally, but I don't know of a way to push mysql changes to the server and keep it connected with with git.
I will be working with several others so it needs to be using git for the database.
How would I go about doing this?
Thank you for any help!
Comment: Usually you would use migrations and fixtures (eg. Doctrine), but you could stick a `mysqldump` into a git repo.
Answer: You can dump the scheme and/or the data to a file and then check that file into git.
For example, this will dump the table schema and data to a file named [table_name].sql
mysqldump --user=[user_name] -p --opt [local_database_name] [table_name] > [table_name].sql

To load this data in production, you would do something like this:
mysql --user=[user_name] -p [server_database_name] < [table_name].sql

Comment: Okay, so I call the first command to store the local version and save to a file, and then when I push, I push that file as well, and after that I have to load using second command on the server? That seems like one way I could do it. Is there a better way though?
Comment: There are some products dedicated to handling database version control, but I am not familiar with them. The approach I suggested is a method I know will work with git. Sorry I can't be more help.
Comment: Thanks. This option seems feasible; its just that I thought it would be easier :P


binding an ICommand to a custom eventhandler

Question: I am trying to create a datapager usercontrol. This user control has one event declared in its code behind  :
public event EventHandler OnPageIndexPagerChanged;

I use this control in a main usercontrol, and I bind my event to another event in the code behind like this :
xaml :
OnPageIndexPagerChanged="SuperDataPager_OnPageIndexPagerChanged"

c# (Code behind) :
private void SuperDataPager_OnPageIndexPagerChanged(object sender, EventArgs e)
        {
            var viewModel = DataContext as ViewSchedeConsuntiviViewModel;

            if (viewModel != null)
            {
                viewModel.FilterCommand.Execute(sender);
            }
        }

And this works fine, But I would have liked to skip passing through the code behind an do something like :
OnPageIndexPagerChanged="{Binding Path=FilterCommand}"

This, I already do for the filter button, present in my main usercontrol, therefore I thought I could do the same for this event. But every time I receive an error :

Impossibile assegnare alla proprietà
  'Super.Silverlight.SuperDataPager.OnPageIndexPagerChanged'. [Line: 90
  Position: 55]

'iexplore.exe' (Silverlight): Loaded 'C:\Program Files (x86)\Microsoft
  Silverlight\4.0.60531.0\it\mscorlib.resources.dll'    su
  System.Windows.Application.LoadComponent(Object component, Uri
  resourceLocator)    su
  Super.Silverlight.SchedeConsuntivi.InitializeComponent()    su
  Super.Silverlight.SchedeConsuntivi..ctor()

Sorry for the error in Italian, but I was unable to get the exact translation -> (unable to assign property...)
Could someone explain me this behavior?
Thanks for reading,
[EDIT]
Here is the my view Model  for the main usercontrol :
 public class MyViewModel : DependencyObject, INotifyPropertyChanged
{
      public ICommand FilterCommand { get; set; }

      public MyViewModel()
      {
         FilterCommand = new Super.Silverlight.Tools.DelegateCommand<object>(p => Filter());
      }

    public void Filter()
    {
        //....blah blah blah...
    }
}

[/EDIT]
Answer: First of all your Event is not a RoutedEvent, something you should consider. But thats not the main problem.
Of course you can't set an ICommand to an EventHandler. Don't get confused of RoutedEvents with RoutedCommands. You have 2 options, you can give your UserControl an dependency Property of type ICommand and just fire that inside your code behind. In XAML you can bind now your command. Or if you want to have that as an event, again consider using RoutedEvents, there are options to bind commands to routedevents like EventBehaviorFactory and some more.
The easiest solution would be to use an ICommand directly in you user control and remove the event.
Answer: I'm afraid you can not do this, cause Command is special type routed event, instead reading DataPager specification doesn't seems to support any commanding. And what you do in code, instead, is assign to event.
EDIT
You can have also workarrounds but it will not definitely like you want here.
Regards.


Setting Controls in Classes

Question: I'm trying a booking system, I want to put controls on the booking aspect. I want to use If and then cases. I want to control in such a way that if number of booking is 4, then it will throw an exception and stop inserting in the database.
public ApiResult<TimeModelExtended> SaveBooking(Booking booking)
    {
        AchimotaGCDb repo = new AchimotaGCDb();

        var result = new ApiResult<TimeModelExtended>();
        try
        {
            booking.PlayDate = getPlayDate(booking.RefCode);

            Int16 nb = getNbBooked(booking.RefCode);

            if (nb == 4)
            {
                Exception ex = new Exception();
                result.Successfull = 0;
                result.InternalError = ex.Message;
                result.Error = "Booking slot is full";
            }

            else  if (nb == 0)
            {
                booking.BookingStatus = 1;//Booked already
            }
            else
            {
                booking.BookingStatus = 0;//Reservation already
            }

            repo.Insert(booking);

            result.Successfull = 1;

            result = GetOneteeTime(booking.RefCode);

        }
        catch (Exception ex)
        {
            result.Successfull = 0;
            result.InternalError = ex.Message;
            result.Error = "Error from server";
        }
        finally
        {
            repo.Dispose();
        }

        return result;
    }

help to solve that.
Comment: Possible duplicate of [How to throw exception in Web API?](https://stackoverflow.com/questions/14607844/how-to-throw-exception-in-web-api)
Comment: Unrelated: `Int16` - why are you using this?
Answer: If you want to throw an exception, you need to really throw it:
if (nb == 4)
        {
           throw new Exception("Booking slot is full.");
        }

But I don't think throwing an exception is a good idea. Throwing an exception and validation is a different thing.
Here is my suggestion:
  if (nb == 4)
        {
           return result = new ApiResult<TimeModelExtended>()
                        {
                           Successfull = 0,
                           InternalError = "Other messages",
                           Error = ""Booking slot is full."
                        };
        }

This will return as result message that nothing will continue unless you satisfy that nb != 4
Comment: Also mind that if he would throw an exception with the rest of the code as given in question, he would catch it in the same method modifying the result ... so this is completely superfluent. Your suggestion is the way to go.
Comment: Does that mean that when the nb=4,the exception will the returned and when the nb<>4,then the booking is inserted into the database?
Comment: Yes, unless you still want to insert even you want to throw an exception? I can edit my answer if that's the case.

Setting Controls in Classes


18.04 Server: Change WiFi frequency to 2.4Ghz band on Raspberry Pi 3B+

Question: I have 2.4GHz-only APs but my Raspberry Pi 3B+ has dual band capability. I want to tell Ubuntu in its terminal to make sure nothing runs on 5.2Ghz.
I have searched far and wide locally and on the internet for a solution to this, and have come back with nothing.
3B+ specifications
SoC: Broadcom BCM2837B0 quad-core A53 (ARMv8) 64-bit @ 1.4GHz
GPU: Broadcom Videocore-IV
RAM: 1GB LPDDR2 SDRAM
Networking: 2.4GHz and 5GHz 802.11b/g/n/ac Wi-Fi
Bluetooth: Bluetooth 4.2, Bluetooth Low Energy (BLE)
Any ideas?
Answer: nmcli is the CLI tool to use here to control Network Manager.  As per https://docs.ubuntu.com/core/en/stacks/network/network-manager/docs/configure-wifi-connections make sure your WiFi radio is on with nmcli r wifi on then find the name of your Pi's WiFi with nmcli d  .
List the WiFi Access Points (WAPs) with nmcli d wifi list then connect with nmcli d wifi connect my_wifi password   .
Since your WAPs are 2.4GHz, you won't select any 5 GHz WAP, and once you've connected to your 2.4 GHz WAP, it will stay connected.
wpa_supplicant allows you to specify frequencies restricted to the 2.4 GHz band only by adding a file /etc/wpa_supplicant.conf with a line including

freq_list=2412 2417 2422 2427 2432 2437 2442 2447 2452 2457 2462

https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up/5 provides GUI-based instructions if you've added a GUI to your server; https://i.stack.imgur.com/mXxHL.png shows the critical screen for WAP selection.
Comment: They will have different names *if* you rename them in the administration pages of the router!
Comment: On dual-band APs it is possible to use the same SSID ("name") and password on both 2.4GHz and 5GHz. Some AP vendors even recommend this and/or set it up that way by default.
Comment: Restriction method added above. Knew there was once, had to dig for it.


Read and write complex numbers from a file in C++ (translation from C)?

Question: I have a big problem. I get a task in which I should write a program in C++, which I previously write in C. This program in C++ must read complex numbers from a file and write them. I must create a class and real and imaginary parts must be private. I also must create operators << and >>. I don't know what I should do. This is my input file
data.txt
(2.3,5) (7.12,-2.91) (7.99,8)
(5,3.25)

My output file should be
result.txt
2.3, 5
7.12 -2.91

In C I use these functions
void readZ(FILE *wp, double *a, double *b)
{
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,a,&c,b,&c,&c));

}
int writeZ(FILE *wp, double complex z)
{
    fprintf(wp, "%.2f, %.2f\n", creal(z), cimag(z));

    return 1;
}

Now I must do this in C++
This is my code
main.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "read.h"

using namespace std;

int main(int argc, char* argv[])
{
    ifstream inFile;
    ostream  outFile;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    read >> x1;
    write << x1;

    inFile.close();
    outFile.close();

    return 0;
}

read.h
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&)
    {
        cout << real << '.' << imag << ',' << ' ';
    }
    friend std::istream& operator>>(std::istream&, Complex_num&){
        char c;
        cin>>c>>&real>>c>>&imag>>c>>c;
    }
};

read.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "read.h"

using namespace std;

Complex_num::Complex_num(double r, double i)
{
    real=r;
    imag=i;
}

I have so many errors I dont even know what I should do
g++ -c read.cpp -Wall
In file included from read.cpp:4:0:
read.h: In function 'std::ostream& operator<<(std::ostream&, const Complex_num&)':
read.h:18:17: error: invalid use of non-static data member 'Complex_num::real'
         cout << real << '.' << imag << ',' << ' ';
                 ^~~~
read.h:8:12: note: declared here
     double real, imag;
            ^~~~
read.h:18:32: error: invalid use of non-static data member 'Complex_num::imag'
         cout << real << '.' << imag << ',' << ' ';
                                ^~~~
read.h:8:18: note: declared here
     double real, imag;
                  ^~~~
read.h:19:5: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
read.h: In function 'std::istream& operator>>(std::istream&, Complex_num&)':
read.h:22:18: error: invalid use of non-static data member 'Complex_num::real'
         cin>>c>>&real>>c>>&imag>>c>>c;
                  ^~~~
read.h:8:12: note: declared here
     double real, imag;
            ^~~~
read.h:22:28: error: invalid use of non-static data member 'Complex_num::imag'
         cin>>c>>&real>>c>>&imag>>c>>c;
                            ^~~~
read.h:8:18: note: declared here
     double real, imag;
                  ^~~~
read.h:23:5: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
read.cpp: At global scope:
read.cpp:8:1: error: prototype for 'Complex_num::Complex_num(double, double)' does not match any in class 'Complex_num'
 Complex_num::Complex_num(double r, double i)
 ^~~~~~~~~~~
In file included from read.cpp:4:0:
read.h:7:7: error: candidates are: constexpr Complex_num::Complex_num(Complex_num&&)
 class Complex_num {
       ^~~~~~~~~~~
read.h:7:7: error:                 constexpr Complex_num::Complex_num(const Complex_num&)
read.h:10:5: error:                 Complex_num::Complex_num()
     Complex_num(){
     ^~~~~~~~~~~

Comment: do them one by one. Start with the first. What is not clear about it? You probably forgot to give the argument a name and then you want to use members of that argument...
Comment: you should friend std::ostream& operator<<(std::ostream&, const Complex_num&); in class and then write definition after class for a friend function.
    friend std::ostream& operator<<(std::ostream& out , const Complex_num& num)
    {
        out << num.real << '.' <<num.imag << ',' << ' '; return out;
    }
Comment: You should probably not just port your C code straight off. Use [`std::complex`](https://en.cppreference.com/w/cpp/numeric/complex) in C++.
Answer: read.h:18:17: error: invalid use of non-static data member 'Complex_num::real'
         cout << real << '.' << imag << ',' << ' ';

Your friend operator functions are not member functions, so they dont have access to member variables. You should make use of their parameters:
friend std::ostream& operator<<(std::ostream& os,  const Complex_num& c)
{
    os << c.real << '.' << c.imag << ',' << ' ';
    return os;
}
friend std::istream& operator>>(std::istream& is, Complex_num& cn){
    char c;
    is>>c>>cn.real>>c>>cn.imag>>c>>c;
    return is;
}

Comment: I think you should also return os and is because of function return type
Comment: ahh :-) I probably have not reloaded to see it, I see I changed your edit slightly


Downloading langage packs makes the installation process take a long time.

Question:
Possible Duplicate:
How can I remove the Translation entries in apt?
How to disable the download of language packs while installing Kubuntu

When installing while connected to the internet, downloading language packs can take a long time.

(original message) :
Why mandatory install slow load huge Language Pack.Native user
applaud.Chosen at install already practical.Window install on request
only.
Comment: I am not understanding , Question was not clear . could you explain more .
Comment: Maybe someone with more knowledge may come along, but this language pack business does take up a significant part of the installation process.
Answer: I have to agree.  The best thing to do if you have a slow internet connection is not let the install programme connect to the internet and update while installing.  Connect after the installation is complete and do the updates then.  Install time should be 20 minutes or even less depending on the speed of your computer.
Comment: Unplug network before install - will be 0 hours.  The install will still be in your language.  You can update the language packs later.
Comment: To Fabricator4.A novice to Ubuntu OS.Use liveCD to install side to WIN.Dialogue indicate Select language and 2 other:Updates N Software and not clicked.When install 472 items appear and jam at language section.Question MANDATORY mean is it a package install.I choose a language I understand for install.Language is useful if communication between people is understood.Otherwise it is blabbering of tongues in unknown dialogue.A Korean or Hindu will applaud their language is offered.These extra language files wont see light so delete to gain space or keep?I wont mind 2 hours but now 8 hours.
Comment: Or press the "Skip" button (it's on the right).


Greedy Algorithms and Time Complexity #2

Question: We have a bomb that is ticking and may explode. This bomb has n switches, that can be moved up or down. Certain combinations of these switches trigger the bomb, but only one combination disables it.
Our task is to move the switches from the current position to a position that disables the bomb, without exploding it in the meantime. The switches are big and awkward, so we can move only one switch at a time.
We have, lets say, n = 4 switches currently in position ^vvv. We need to get them to the position ^v^^. Forbidden positions are vvv^, ^vv^, ^v^v, and ^^^v.
a.) I had to draw this by hand and find the shortest sequence of switch movements that solves the task - result I got was 4 ...and I found two such sequences, if i am right...
b.) this is where it gets a hard - write a code that answers the above question/questions (the shortest sequence and how many). The code should be generalized so that it would work with another number of switches and other starting, targeted, and forbidden combinations; targeted and forbidden combinations may be multiple or even fewer. Only thing we know for sure is that the switches have only two positions. It should also provide the possibility that the desired condition is unavailable; in this case, the program should of course tell.
c.) Next questions is the time complexity of the code this but for now I think I will just stop here...
I used '0' and '1' instead, because it is easier for me to imagine this.
So my approach towards this was something of a greedy algorithm (I think) - starting position, you think of all the possible (allowed) positions, you ignore the forbidden ones, then pick the one that the sequence of positions has the fewest difference from our targeting sequence.
The key part of the code I am yet to write and that's the part I need help with.

all_combinations = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011' , '1100', '1101', '1110', '1111']

def distance (position1, position2):
     distance = 0
     for i in range (len (position1)):
         if position1 [i]! = position2 [i]:
             distance + = 1
     return distance

def allowed_positions (current, all_combinations):
     allowed = set ()
     for combination and all combinations:
         if the distance (current, combination) == 1:
             allowed.add (combination)
     return allowed

def best_name (current, all_combinations, target):
     list = []
     for option and permitted_mood (current, all_combinations):
         list.append (distance (option, target), option)

Comment: One big issue with your approach is in moving to the "defuse" position you may hit a forbidden position. So the shortest path is not always the correct answer
Answer: The task at hand is finding a shortest path in a graph.  For this there is one typical approach and that is a breadth-first search algorithm (https://en.wikipedia.org/wiki/Breadth-first_search).
There is no real need to go into the details of how this is done because it can be read elsewhere in more detail and far better explained than I can do this in a StackOverflow answer.
But what might need to be explained is how the switch-combinations you have at hand are represented by a graph.
Imagine you have just two switches.  Then you have exactly this graph:
^^---^v
|     |
|     |
v^---vv

If your starting position is ^^ and your ending (defusing) position is vv while the position ^v is an exploding position, then your graph is reduced to this:
^^   ^v
|
|
v^---vv

In this small example the shortest path is obvious and simple.
The graph at hand is easily sketched out in 2D, each dimension (x and y) representing one of the switches.  If you have more switches, then you just add one dimension for each switch.  For three switches this would look like this:
^^^--------^^v
 |\         |\
 | \        | \
 |  \       |  \
 |   \      |   \
 |   ^v^--- | --^vv
 |    |     |    |
 |    |     |    |
v^^--------v^v   |
  \   |      \   |
   \  |       \  |
    \ |        \ |
     \|         \|
     vv^--------vvv

If the positions ^^v, v^^, and vv^ are forbidden, then this graph is reduced to this:
^^^        ^^v
  \
   \
    \
     \
     ^v^--------^vv
                 |
                 |
v^^        v^v   |
             \   |
              \  |
               \ |
                \|
     vv^        vvv

Which already shows the clear way and the breadth-first search will easily find it.  It gets interesting only for many dimensions/switches, though.
Drawing this for more dimensions/switches gets confusing of course (look up tesseracts for 4D).  But it isn't necessary to have a visual image.  Once you have written the algorithm for creating the graph in 2D and 3D in a general way it easily scales to n dimensions/switches without adding any complexity.
Comment: Note that BFS takes exponential time, but A* does not.  Because each invalid state must be given explicitly, the number of wrong guesses is limited to the size of the input.
Comment: can anyone code this? can it be done recursively for "n" dimensions? i am lost on how to code some things here. If someone could do the  "b.)" example and explain the time complexity for searching would be really cool.
Answer: start = 8
target = 11
forbidden = {1: -1 , 9: -1, 10: -1, 14: -1}
dimensions = 4

def distance(start, target, forbidden, dimensions):
stack1 = []

stack1.append(start)
forbidden[start] = -1

while(len(stack1) > 0):
    top = stack1.pop()
    for i in range(dimensions):
        testVal = top ^ (1 << i)

        if testVal is target:
            forbidden[testVal] = top
            result = [testVal]
            while testVal is not start:
                testVal = forbidden[testVal]
                result.insert(0, testVal)
            return result

        if testVal not in forbidden:
            forbidden[testVal] = top
            stack1.append(testVal)

return [-1]

print(distance(start, target, forbidden, dimensions))

Here is my code for your example in your question. Instead of using bits, I went ahead and used the base 10 number to represent the codes. Forbidden codes are mapped to a hashmap which is used later to trace the path upwards after the target is found. I use a stack to keep track of which code to try. Each time the while loop passes, the last code added is popped and it's unvisited neighbors are added to the stack. Importantly, to prevent cycles, codes on the stack or seen before are added to the list of forbidden nodes. When the target code is found for the first time, an early return is called and the path is traced through the hashmap.
This solution uses breadth first search and returns the first time the target is found. That means it does not guarantee the shortest path from start to target, but it does guarantee a working path if it's available. Since all possible codes are possibly traversed and there are 2^dimensions number of nodes, the time complexity of this algorithm is also O(2^n)


getField not displaying results

Question: I am trying to display points from a user row on a profile page.  I try using the following
<code><?php echo $profile->getField('points');?>
</code>
to pull up the field that holds a users points but nothing is displaying for the user I am testing it with. I am testing it logged in as the user who has 16 points set, but nothing will show, any ideas whats wrong ? If instead of ('points') I put ('username') or ('name') it will display those fields, but not points. Thanks for any assistance!
Answer: I'm not sure what it could be. Have you tried using error_reporting(E_ALL); above your script?  Perhaps use an or die().mysql_error(); to find out more..Also why is points Char and not say varchar or int?
Comment: still no errors coming back on my end.  I did change the CHAR to VARCHAR now, but still not working! Thanks for the assistance though mate !

getField not displaying results


Visual Studio Express 2013

Question: I would like to learn C# and using Visual Studio 2013. There are a few different flavors of Visual Studio Express 2013: for Web, for Windows and for Windows Desktop. I am not really sure which one I should download. Can someone advise on this? I borrowed the book Professional Visual Studio 2013 from the library, but it seems that this book is targeted for the professional version of Visual Studio 2013. Would I still be able to use the Express version to work on the examples in the book?
Also, I want to learn WPF, WCF and Silverlight, do they come bundled with the Web, Windows or Windows Desktop flavor?
Thanks in advance.
Comment: The download page gives an overview of what each version is for.  Web = web sites (and WCF), Windows = Win 8 Store Apps and Desktop = WinForms/WPF (in general terms).  There are some features of VS 2013 that aren't in the express editions and/or are present in one edition but not the others.
Answer: You should download and install all 3 of the express edition since they are free and serve different purposes. However, I would suggest you to get a commercial version for many extra features and convenience.
Comment: Which of the 3 has WPF, WCF and Silverlight?
Comment: The Express Edition for Web has WCF and the Express Edition for Windows Desktop has WPF. You need to manually install silverlight as it doesn't come along with the express.

Visual Studio Express 2013


Error: Unknown host 'No such host is known (proxy)'. You may need to adjust the proxy settings in Gradle

Question: I'm try to connect Firebase's realtime database and keep getting this error. Any suggestion?
Answer: Update your project level build.gradle to latest version - it worked for me
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.2.0'

Comment: @Luong Nguyen Viet Khoa K16_HL  .... Let me know does this worked for you or not ?


Text preview boxes are jumbled in Chrome

Question: When I hover over text or links in Google Chrome the text boxes are jumbled. I don't quite know how to describe it, it just looks weird and that's why I figured I'd show you some pictures:
Pictures
This doesn't happen every time, but is easily reproducible.
My graphics card is Nvidia Geforce GTX 950M.
Answer: we're still waiting on amd to release a new AMDPRO GPU driver that works with ubuntu 17.04 if and when they do it should fix this issue (which i also have. BTW it ony does this on first hover. if you hover it again you get to see the actual thing)
an update on ubuntu's stock amd driver is also much needed from canonical/the linux community.
also please specify what grapics card model you have exactly.
if you have ubuntu 16.04 or under then head on over here : http://support.amd.com/en-us/kb-articles/Pages/AMD-Radeon-GPU-PRO-Linux-Beta-Driver%E2%80%93Release-Notes.aspx
see if your graphics card is supported and if it is horray!
Comment: Yes, sorry I forgot. I edited my answer and added the specs as a picture.
Comment: well that allowed me to know you are on ubuntu 16.04 but i still don't know what graphics card you have.
Comment: I thought it was in the specs but apparently not. Changed it.
Comment: then your on nvidia and this is thus a systemwide 17.04 issue that isn't caused by one either nvidia or AMD. I don't know that there is a solution for this (yet!) and am as interested as you are in any eventual fix. you should add a bounty on your question.
Comment: But I'm not using 17.04. Ok. Thank you :) It doesn't bother me that much, I just wanted to know if there was a solution.


Mongo DB: Change a field to array

Question: Lets say we have a document like this
<code>{
    "_id" : "1234",
    "Data" : {
         "Name" : "Pythagoras",
         "Like" : "Math"
}
</code>
And we changed over mind and want to push more things to Data->Like so it looks like;
<code>{
    "_id" : "1234",
    "Data" : {
         "Name" : "Pythagoras",
         "Like" : ["Math", "Science"]
}
</code>
All the atomic operators like $push, $pushAll and $addToSet works just when Data->Like already is an array.
I´m using the php-driver. In this example there is no meaning to not set the Data->Like to an array at the beginning but it does not work like that in my code ;(
Hope you can help me and sorry for my bad English ;) Thanks!
Answer: You'll have to iterate over all your documents and change the value to an array. For example, you can do that with:

$m = new Mongo();
$c = $m->yourdbname->yourcollectionname;

foreach ( $c->find() as $r )
{
    if ( !is_array( $r['Data']['Like'] ) )
    {
        $c->update( array( '_id' => $r['_id'] ), array( '$set' => array( 'data.like' => array( $r['data']['like'] ) ) ) );
    }
}
Comment: Thanks, I do not want to do it with all my documents but I think I can mange to fix it in the way I want. I hoped for an operator that just added the data ;(

Mongo DB: Change a field to array


Why do I sometimes get EQT_{guid} folders with copies of my application when running MsTest unit tests?

Question: I have noticed on occasion (not very frequently) that after I run my suite of MsTest unit tests in Visual Studio, I will get a folder or folders that are of the form (the guid varies):
EQT_6A69DAE9-1C34-4B96-8B96-698A94EA1ADF

The folder will only contain a copy of my .exe file for the application.  In this case, the application is using WPF.
These folders always show up inside my Debug directory.
There is nowhere in my application that I am creating anything like this (and certainly not copying my own .exe file), so it appears to be a product of something in MsTest.
Why does MsTest sometimes create this folder with a copy of just my .exe file?
Answer: I believe these are the runs that would have code coverage enabled via your .testsettings file. Your .exe is being backed up here while an instrumented version is created for code coverage when running with .testsettings.
This will not happen when you run code coverage without any .testsettings using the "Analyze code coverage" option available in VS2012


How did Albert Fink observe the tears?

Question: Later in the game, we find out:

Albert Fink was able to hear the music of the future through tears, which he used to make him and his brother a lot of money.

Why was Albert able to view these tears in the first place?
Answer: According to Jeremiah Fink (Albert Fink's brother) in his Voxophone log, "Out of the Thin Air":

Dear brother, these holes in the thin air continue to pay dividends. I know not which musician you borrow your notes from, but if he has half the genius of the biologist I now observe, well...then you are to be the Mozart of Columbia.

The "Uncanny Mystery in Columbia" kinetoscope video* shows that some Columbian citizens have been able to observe the tears too. It also says that this has something to do with Rosalind Lutece's research.

These suggest that the tears appear in random places ("out of the thin air") in Columbia due to Rosalind Lutece's research on the tears and Albert Fink observed music coming from them. Jeremiah Fink has also been able to observe the tears to create some of the technologies that his company produces.
As you play the game, you'll notice that Booker and Elizabeth will notice music coming from the tears too. In one instance, they'll be able to hear the 1983 Cyndi Lauper version of the song, Girls Just Want to Have Fun through a tear and comment that they have never heard that song before. Notice that the beach music in Battleship Bay is based on the tune of "Girls Just Want to Have Fun". (As commented by @Kappei) There's also another tear in Finkton from which Booker and Elizabeth can hear Fortunate Son in its original version.

* found at the entrance of the Monument Island Gateway
Answer: According to the wiki, the tears on Colombia simply exist, and are visible by anyone, but only Elizabeth can interact with them. One such tear was in Albert's studio, and the existence of the tear was enough to allow him to hear the songs from the future.

How did Albert Fink observe the tears?


How can I remove the rounded edges and transparent border from a metacity theme?

Question: I have a problem with my current theme. When windows top border close to top panel, there's a transparent background at the top corner (please take a look at the attached image).

So, how could I :

remove it?
change the rounded corners (I love the less rounded corners - like MAC OS X)

Thanks in advance.
Answer: To change the corners, you will have to edit the theme, or choose a different one. Also, you should ensure compositing is enabled, if you want rounded corners. You can do this by using compiz instead, or by running gconf-editor, opening the /apps/metacity/general item in the tree, and enabling the compositor_effects option in the list on the right. With that on, you should not see this artifact in the theme.


Full Java/C# Code Generation tools from Model?

Question: It's very surprising that there are no real tools to fully generate code from a model. All UML tools I've seen are not really practical except this one:
http://www.intrinsarc.com/
<code>A hierarchical component model with full connectors
At the heart of Evolve is a hierarchical component model with full connectors. Connectors act like
wires between components, making it simple and intuitive to express detailed structures that are
difficult or impossible in other approaches such as dependency injection.
Resemblance and evolution
These two constructs provide unprecedented levels of support for component reuse.

Resemblance
    is a form of component inheritance. Evolution builds on this to allow the structure of an existing
    system to be remodeled, without destroying the original definition. These facilities can be used to
    create variants of a system, or to switch in test components.
</code>
Did someone try it : what do you think ? It seems like based on UML but not on UML class but other types of diagrams.
Any other tool which can do real code generation UML or not ?
What I mean by real: EMF is not such a tool it's only a framework for building UML Tool as far as I can see not a tool by itself which facilitates the building and maintenance of an application.
Same for Visual Studio Ultimate. Though the UML tool inside is quite good it's just yet another UML tool that doesn't really help ypu model but just do graphically what you can do by typing code.
Comment: I'm starting to suspect that this more of an attempt to start a debate than a real question.
Answer: I wrote the Evolve system which the question is about.
Evolve generates code to connect up classes from UML component models. It can also generate full code for state diagrams, which is incredibly handy. You can easily import and connect up your own classes. It effectively allows you to create software in a way like how you might plug together chips into an electronics circuit board.
The real advantage though is that it aligns software creation, reuse and evolution. In other words, you can create a system, pass it to a colleague, and they can evolve or extend it in any way, even without the source code, and without you having to pre-plan the extension points. You can extend and reuse state charts also.
It does sound magic, but it has a very strong foundation - it was the outcome of recent phd research, and it is actually one of the more sophisticated design tools on the market. The professors who supervised the research also influenced Microsoft's COM work.
Here is a small video of it in action: http://intrinsarc.com/movies/evolve.html
Try it and let us know how you go! The manual has a tutorial which shows you how to build up to a GWT/Hibernate working example.
(BTW Evolve uses EMF under the covers for storing the UML models)
Comment: The problem I see is that I cannot make it work reading your documentation. For example doc doesn't explain how to import package to create the IRun interface. There are many details that seem missing.
Comment: Yes, apologies for the current documentation. I've been working with some people over the last week or so and realised that the docs are too broad and not easy to follow.  The IRun interface is in the com.intrinsarc.backbone.runtime.api package in the backbone.jar file. Please feel free to email me at email@example.com or post to the support forum if you have issues.
Comment: By the way, we are always interested in comments, criticisms and suggestions for improvement. The Evolve tool has compressed almost a decade of research into a toolset, so although it is extremely powerful, we are having teething problems getting people over the learning curve. We hope to improve the docs etc in the near future. Feel free to send any comments to firstname.lastname@example.com
Answer: I use Sybase Powerdesigner and custom Ruby code (to access the data model) to generate my ORM model from UML.  It can be tough to generate code against UML because there are many ways you can customize the model.  I have stereotypes that are not really classes, but are being used for other code generation purposes that are custom to the problem I'm solving.  How would a generic code generator understand my custom uses of the model?
Comment: ORM is not full application. Above tool is meant to generate a full blown app and make it evolve.
Answer: Eclipse EMF generates complete Java code from EMF models (ECore).  EMF generates classes to represent instances of the model in-memory with support for XML or XMI serialization / deserialization, hooks for validation, an optional editor, and more.

What I mean by real: EMF is not such a tool it's only a framework for building UML Tool as far as I can see not a tool by itself which facilitates the building and maintenance of an application.

You need to do more research before you make statements like that.  EMF is a real tool for building real software based on real models.  I've used it successfully for building and maintaining production software over a number of years.

Have you ever seen somebody using EMF to generate a full blown app with GUI etc?

Oh yes.  Done it myself.  Admittedly, I'm talking about specific kinds of applications, and specific kinds of GUIs.
Comment: Have you ever seen somebody using EMF to generate a full blown app with GUI etc? ?
Comment: EMF is a framework for building UML Tool as far as I can see not a tool by itself which facilitates the building and maintenance of an application.
Comment: That's my point there's nothing general as far as I can see except the one above.


Why are there multiple receptacles by amperage?

Question: I could imagine the various receptacle shapes being a tool to protect you from making a mistake about what you plug in.
Consider a 15A breaker with 14ga wiring to NEMA 5-15R receptacles. The circuit goes to 3 different rooms. In each room I plug in a device that draws 6A, and I overload the circuit and trip the breaker. So, a 15A recep didn't protect me from anything.
If, on the other hand, each circuit had exactly one receptacle, then you could look at the plug configuration and know how much load you can put on that circuit. You might daisy chain a bunch of power strips on that recep and overload it that way (or not, if you're just charging a bunch of Kindles) but you have the information you need to decide if that's going to work for you.
I get why there are different receptacle shapes by voltage. But this is about amp rating of circuits, wiring, outlets, and devices. I'm interested in the codes that govern what's behind the walls & built in to houses, not best practices when plugging in. Assume ignorant/lazy users.
Why do receptacle shapes vary by amperage? What's the purpose?
Comment: Regarding "a 15A recep didn't protect me from anything" -- US receptacles (with a few exceptions) don't include any sort of over-current device. So a 15A receptacle rating means that that receptacle will feed 15A of current without overheating, catching on fire, or otherwise malfunctioning. The rating means you must use a device that breaks the circuit if *over* 15A is drawn, because above that current the receptacle may fail. Same idea as with wiring, which must be thick enough to carry the circuit's maximum current without overheating.
Answer: I'm not really sure exactly what your question is in reference to the multiple room examples you give. Without referencing the exact NEC sections, it basically allows 15amp circuits in living spaces and bedrooms, a minimum of two 20amp circuits in kitchens with home runs (single purpose circuit) for certain Higher draw appliances such as refrigerators, dryers, water heaters, etc.  It has always been working practice to split up some lighting from receptacles and also use multiple circuits to separate higher use rooms such as a living room from bedrooms.   There are limits to the number of receptacles on a branch circuit, but I don't have the reference at hand.
As far as the different shapes of receptacles, 15amp, 20 amp, 30amp etc. This is quite obvious in the fact that the male plug on appliances is slaved to it's draw of amps. These different shapes assure that a machine that draws 17amps cannot be plugged into a 15amp feeder. Granted, one could put several 6 amp devises on one 15amp and overload it, but that is what the circuit breaker is for.  Under normal and historical uses in residential structures, it would be rare to easily overload a circuit with typical household items, such as lamps, stereos, fans etc. if someone is going to use multiple high draw appliances, then common sense has to kick in and design the circuit plan to accommodate the anticipated load. When i design a house plan, I always use a minimum of a 20 circuit panel(most of the time a 40)  and separate branch circuits to each room, basement and garage, as well as a few for lighting or outdoor usage.
I don't know if this really answers your question, but that's all I got for ya!
Comment: To add on a bit, one of the functions of the circuit breaker is actually to protect the wire. The wire can connect to several receptacles, but regardless, a 14ga wire is still only rated to 15A, hence why the breaker is 15A (note though, for very long runs, there is a voltage drop, and the current rating is effectively lower. You usually don't run into this in a house, but it's worth mentioning).
Comment: Also, we don't run individual circuits with individual breakers to each receptacle because of the cost: it would use a significant amount more more, plus many more breakers, and the majority of the time, it's not needed because most devices in a house don't pull that much power. The service to most houses now is 100 or 200A (200 being most common), and so even if you have 30 receptacles, that is 30*15A + 40A (dryer) + 40A (stove) = 530A.. so you can't run that much at once anyways, even if you wasted the extra money on the wire, breakers and labour.
Comment: You've hit it on the head--the different shapes only protect against plugging an appliance into an underpowered circuit. They don't protect in the other direction (plugging too many appliances into a circuit).
Answer: In the days before electronic circuit breakers, overloading a circuit meant a trip to the hardware store to get a replacement fuse.  So, by preventing you from plugging in an appliance that could blow your fuse, having different shaped receptacles could save you some time, money and inconvenience.
Since you mention ignorant/lazy users, remember that a blown fuse was sometimes replaced with a coin.  If someone did just that on a circuit rated for 15A and then plugged in a 20A load on it, you would get more heat dissipation in the wiring than you should, which could end up causing a fire.
Comment: Getting my house rewired with circuit breakers ~8 years ago was the greatest improvement I've done, even if I hired someone else to do it.  Now I just need to get around to re-wiring the kitchen and basement, so the laundry won't trip if too many lights are on upstairs, and I'd be able to use the toaster and microwave at the same time!  ... I was probably blowing a fuse once a week when I first moved in.
Answer: I think the rating is for the receptacle itself. The different plug shapes allow the manufacturer to make lower cost receptacles for lower amp loads.
Imagine if every receptacle was built to carry 30 amps. The receptacles would all cost more and would normally be under utilized.
If you acidentally installed a 15 amp recepticle on a 30 amp circuit, you could not overload the receptacle by pluggin in a 30 amp load. The plug would not fit.
Comment: I think you're correct - that 15A receps might fail under a 30A load. However, 15A receps are rated at 20A, and the code explicitly allows them to be protected by a 20A breaker. You can put more receps on a 20A circuit than on a 15A circuit. It's a special case, though.
Answer: The breaker, and the plugs, did indeed protect you. From an electrical fire caused by overloading and overheating of one or more components of said circuit.
Electrical codes exist and are enforced primarily to prevent situations in which an electrical system can pose an imminent hazard to human life or safety, and further, most safety codes are in place for fire safety, with the next largest subset of codes being for shock safety. All other considerations, including convenience, are secondary, and usually "convenience" code requirements, like maximum spacing between wall receptacles, exist for cases where someone faced with an inconvenient electrical situation will do something inherently dangerous to solve their problem.
Case in point: for convenience, to avoid the homeowner running extension cords around the room, a room will have many outlets on one circuit, which if all used at the same time would be unsafe. This is acceptable because normally, you don't plug in something to every plug on a circuit and turn them all on (notable exceptions may include kitchen outlets and outlets powering your home theater). It's called "demand load"; different rooms in the home have different expectations for the percentage of available outlets used at one time, and that's used to determine amperage requirements of the branch circuits supplying those outlets.
Additionally, the receptacle design and the circuit breakers provide redundant levels of fire safety. You cannot buy anything off the shelf that plugs into a 15A socket and draws more than 80% of that (12A; a safe "continuous" load). If it draws more than 12A it requires a T-blade plug for a 20A outlet, and cannot draw more than 16A. The design of the plug protects the receptacle first, and the circuit second; you can't plug in any single device that would exceed the rating of the plug. The breaker then acts to protect the entire circuit; if circuit load exceeds circuit rating for any reason (short-circuit, too many devices, and/or illegal modification), the breaker trips.
You consider plugging three 6A devices into a circuit rated at 15A, and tripping the breaker, a "nuisance". What has happened is that the engineer who designed your home's electrical system didn't plan on you ever needing 18A total draw on that circuit, based on the type of space it was intended to be, and the resulting demand load calculation given the number of outlets a space that size is required to have. You have three options:

Find a receptacle on a different circuit that one of the devices can be plugged into, spreading the load between breakers.
Pull a new 15A circuit on a new breaker to serve some of the outlets currently on the overloaded circuit, again spreading the load between breakers.
Beef up the existing circuit to 20A by pulling a new run of 12/2 Romex in place of ALL existing 14/2 on the circuit (including between "daisy-chained" outlets), increasing the maximum load of the circuit to meet the new expected demand load.
Answer: To prevent plugging in a load to a circuit that definitively can't support that load. That's not to say that (for various reasons) the proper plugged circuit CAN support the load, but it's certain that the improper one can not.
Note: In the US at least, the 20 amp plug is seldom used, at least on the load side of things. I have an air compressor that is rated for 20 amps (and boy howdy does it need it), but the plug is the same one for 15 amp circuits.
Comment: It is actually quite rare to find 20 amp rated outlets used anywhere, which is why 20 amp devices often come with 15 amp style cords. Also the internals of newer 15 amp outlets, are usually exactly the same as the internals of 20 amp outlets.
Comment: 20A devices are generally rare in residental. However, a device that draws more than 15A MUST use a T-blade plug. 15A outlets are NOT rated for 20A. They are rated for 15A, and can TOLERATE 20A flowing through the terminals behind the plate, allowing for installation in a 20A circuit (in that situation it still can provide only a maximum of 15A to a device plugged into that actual receptacle; but, the entire circuit can tolerate a higher "demand load").
Comment: One problem with the design is it that handles poorly devices whose purpose is to switch and forward power to other devices.  If a lighting controller controls six outlets, and can switch 10 amps to each one, and will sometimes be used in situations where only one lamp will be lit at a time, and sometimes will be used with multiple lower-power lamps lit simultaneously, and if nothing in the controller would have any problem handling a total of 30 amps, it would be irksome to have to use a separate controller in cases where there was only a 15-amp outlet available but one had fewer lights.


Pivot Table Multi-filter Ranking

Question: This may turn into a long winded Q so I apologies in advanced.
I'm doing some work for a sports league & need some help with advanced Pivot Table help.
I'm trying to produce a "Historical Record" spreadsheet for the league.
I am able to get my required data into a suitable pivot table (See Image 1). The pivot table has two rows these are Name & Team. The team row is used for a future section (Explained Later)
Image 1 - Sample Data in Pivot Table
This data then needs to be sorted in two separate ways.
The first sorting version is to sum the total value of several columns and place them into a separate column on an alternative sheet. I have used this formula to start to achieve this:
=QUERY('Player Records - Offense'!$A:$H,"select A, max(D) group by A order by max(D) desc limit 10 label max(D) ''",0)
This sorts through the specified columns in the pivot table and finds the top 10 values an orders them in from highest to lowest with the corresponding name, see Image 2.
Image 2 - Formula Example
The first issue is seen here, as you can see in Image 2 the formula brings through both the individual records as well as the total records for each given player. So is there a way to filter so that only the total values are used in the formula & not each player individual records? Can this filter be customized so that it can filtered based on the team that they played for, i.e. KC / NOR / SA etc.
https://docs.google.com/spreadsheets/d/10R9PsckIoDj-0hMrVQOmd33zBImUbdx5B5NBluXap-U/edit?usp=sharing
Above you will find the link to the sheet, hopefully that may help.
I would really like to try and avoid using a macro on this if possible with the aim of keeping the sheet as dynamic as possible. Though if it's only possible that way then so be it.
Thank you for any help you can provide me.
Answer: for totals only you can do:
=QUERY('Player Records - Offense'!$A:$H,
 "select A, max(D) where A contains 'Total' group by A
  order by max(D) desc limit 10 label max(D)''", 0)

and KC can be:
=QUERY('Player Records - Offense'!$A:$H,
 "select A, max(D) where B = 'KC' group by A
  order by max(D) desc limit 10 label max(D)''", 0)

Pivot Table Multi-filter Ranking


Debugging PHP in Ubuntu (Xdebug)

Question: PHP Vim Debugger: Configuring Apache
I am trying to install Vdebug to debug PHP in Vim. Unfortunately, when I press F5 this message appears after a few seconds
Waiting for a connection (Ctrl-C to cancel, this message will self-destruct in
20  seconds...)
No connection was made

What should I do?
I searched about this in Google, followed this tutorial and this one (and many others) but did not work.
I followed Vdebug instructions.
I do not know how to achieve this:
Edit your apache configure file

In your VirtualHost section, set debugger port same as the one in your vimrc:

php_value xdebug.remote_port **9009**

The remote_port that has just been mentioned is different from what I have in xdebug.ini and vimrc. Please, see below.
Right now I have in /etc/php5/apache2/conf.d/xdebug.ini:
zend_extension=/usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000

xdebug.profiler_enable_trigger=1
xdebug.profiler_output_dir=/media/www/xdebugdata

And in my vimrc
let g:vdebug_options = {}
let g:vdebug_options["port"] = 9000

I installed Xdebug helper Chrome extension too. Using an IDE is not an option: I wish to use Vim.
Comment: just FYI but your php_value xdebug.remote_port points to 9009 whereas your xdebug.remote_port=9000
Answer: I solved it and now Vdebug is working.
Enable xdebug in PHP
Edit your php.ini file and add the following under the "Module Settings" section:
;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;

zend_extension=/path/to/my/xdebug.so

[debug]

; Remote settings

xdebug.remote_autostart=off

xdebug.remote_enable=on

xdebug.remote_handler=dbgp

xdebug.remote_mode=req

xdebug.remote_host=localhost

xdebug.remote_port=9000

; General

xdebug.auto_trace=off

xdebug.collect_includes=on

xdebug.collect_params=off

xdebug.collect_return=off

xdebug.default_enable=on

xdebug.extended_info=1

xdebug.manual_url=http://www.php.net

xdebug.show_local_vars=0

xdebug.show_mem_delta=0

xdebug.max_nesting_level=100

;xdebug.idekey=

; Trace options

xdebug.trace_format=0

xdebug.trace_output_dir=/tmp

xdebug.trace_options=0

xdebug.trace_output_name=crc32

; Profiling

xdebug.profiler_append=0

xdebug.profiler_enable=0

xdebug.profiler_enable_trigger=0

xdebug.profiler_output_dir=/tmp

xdebug.profiler_output_name=crc32

Try it out
Everything should be ready to go now. Restart apache and run phpinfo() to see if any xdebug information comes up. If it doesn't, then the apache error_log + google are your friends.
Otherwise, you are ready to run the debugger inside vim.
Open a PHP script in VIM that you can access from your localhost
Open that same PHP script in your web browser
Add F5. You should see at the bottom of VIM like "waiting for a new connection on port 9000 for 10 seconds..."
Within the next 10 seconds, refresh the browser page with the ?XDEBUG_SESSION_START=1 on the end of the URL.
Go back to VIM and you're in the debugger in all its glory.
Don't forget: to switch between windows in VIM, press CTRL-w-w.
Source -it applies to Ubuntu though it refers to another linux distribution-
Hope this helps.

Debugging PHP in Ubuntu (Xdebug)


How do I get the "Instant Karma" achievement?

Question: I have managed to get him to kill some of his minions by standing in the mob and not doing too much damage, but it takes way too long just for a couple of kills. What is the ability he uses that can kill his own minions (what does it look like), and how do you make use of it to get the achievement?
Answer: The skeleton king has a couple of attacks you should watch for:

weapon swings - these are pretty generic, he just swings his mace around. These strikes can damage his minions if they are too close to him.
Whirlwind - this is what you want to watch for if you're doing the achievement, however, as it deals a good deal bit more damage (both to you and the minions).

The achievement can be earned pretty easily by kiting the skeleton king around, making sure that there are always minions between him and you. Equip gear with Life Regen or Life Steal and simply run around the arena, regenning life between attacks.
Try to avoid damaging the skeleton king's minions yourself (or at the very least, avoid killing them), because the more of them there are, the more likely it is that the Skeleton King will hit at least one.


User defined join in Informatica with DB2

Question: We are trying to replace source qualifier override with user defined joins and source filter.
for below user defined join in Informatica source qualifier:
{A INNER JOIN B ON a.dept_id= b.dept_id
b.load_date between 20170712174712000000 and 20170904152656000000
LEFT OUTER JOIN C ON a.emp_id =  c.emp_id}

for this I'm getting SQL query as
FROM A,B,C WHERE {A INNER JOIN B ON A.dept_id = B.dept_id
AND b.load_date between 20170712174712000000 and 20170904152656000000
LEFT OUTER JOIN C
ON  C ON a.emp_id =  c.emp_id}

I have tried replacing INNER JOIN in override query with NORMAL JOIN, as I saw it somewhere that informatica translates normal to inner join.
The source database is DB2.
Answer: I don't know anything about informatica, but the resulting SQL syntax that you listed in the question is not valid for DB2. The biggest problem is that you have the JOIN in the WHERE clause rather than the FROM clause. Not real sure how to fix that in informatica though.  Appropriate DB2 syntax though would be something like this:
FROM a
  INNER JOIN b ON a.dept_id = b.dept_id
  LEFT OUTER JOIN c ON a.emp_id = c.emp_id
WHERE
  b.load_date BETWEEN 20170712174712000000 and 20170904152656000000

This assumes that b.load_date is not a timestamp field. If you are using a timestamp field, the format for the timestamps should be '2017-07-12 17:47:12.000000'
Answer: The T-SQL should be used in FROM clause not in the WHERE clause. Hence use:
FROM A INNER JOIN B ON a.dept_id = b.dept_id
       LEFT OUTER JOIN C ON a.emp_id = c.emp_id


Do newer GFCI receptacles still trip due to inductive load from motors?

Question: I am rewiring a kitchen and faced with a dilemma of having the garbage disposal on a GFCI circuit.
Will it trip when turned off like the older GFCI's?
Comment: If you'll accept anecdotal evidence, my garbage disposal is on an GFCI and it has never tripped in the past 2 years that I've lived here. I'm curious whether he NEC would require a GFCI for a garbage disposal plugged into an outlet below the sink -- the outlet is within 6 ft of the sink, but it's not a countertop outlet.
Answer: Quick answer:
Unless your disposal leaks current via ground or via the water/sewer line, you won't have any problems.
More details:
GFCI is really great for appliances that interface with water during the cource of their normal duties. Sumps, washers, disposals, sprinkler systems.  As they degrade, they are especially able to cause dangerous leakage current that can hurt people nearby.
I hate answers that make decisions for the asker.  But this is one of the cases where its really pretty clear.  Even if it was a nuisance, it would be worth it.
If you want an EASY way to gain confidence that it won't be a nuisance, wire the outlet to an old computer power cord for a few days and run the disposal a few times to see if it ever trips.  If it does you should check resistance between hot and ground, neutral and ground, hot and your sink, and neutral and your sink.  They ought to all be infinite resistance.  If not, then you have a significant safety problem with your disposal.
Answer: If you hard-wire the thing, then no GFCI required.
Answer: This thread has aged but the question is ever new so...
With 2022 on the horizon at this post, I just bought several new GFCI outlets (15A "S... E..." brand) to update as needed.
All units false-trip erratically (once every few or many cycles) when load is inductive and relay contacts break or on cord unplug. None are tripped at any other time.
The inductive load can be as small as a 7-watt aquarium pump or the tiny transformer inside an LED bulb, up to a fractional horsepower induction motor (shaded pole or PSC).
Even with aggressive arc suppression across relay contacts, the surge-on-break still sometimes triggers the false GFCI trip. This can of course be unbelievably annoying.
To check if the manufacturer's design or build quality was at fault, I did try another brand. Same result.
So my current answer would have to be: "Yes, it will trip."
If there are any brands that tend to not false trip and it's not a rule violation to name them, suggestions are welcome.


Need "connect by" type query with MySQL for pagination

Question: I've got a submissions_comments table with has parents and children and each child has a 1:1 relationship and each parnet has a 1:many relationship.
That is, all parents can have unlimited (1 level deep children) and all children can have only 1 parent.
My current query works fine, since it returns ALL comments for a particular submission, which I then can do my nested in the front-end of my application, however, when I introduce an offset for ajax pagination, I'm grabbing only the parents that are in the offset, and if they contain a child comment that isn't returned in that particular offset, my nesting won't work.
How can I modify my query to get me all relevant child comments using an offset (such as 0,15 15,30, etc.)
    SELECT parent.id,
      parent.deleted,
      parent.comment,
      parent.user_id,
      parent.created,
      parent.parent_id,
      s.user_id submissionUserId,
      u.username,
      u.photo AS userPhoto
    FROM submissions_comments AS parent
    LEFT JOIN users u ON parent.user_id = u.id
    LEFT JOIN submissions_comments AS child ON child.parent_id = parent.id
    LEFT JOIN submissions s ON parent.submission_id = s.id
    WHERE parent.submission_id = ?
    AND parent.deleted = 0
    GROUP BY parent.id
    ORDER BY parent.created DESC,
    child.created
    LIMIT 0,15 // or offset that I pass in from my front-end application.

Here is a sqlfiddle with the data/tables:
http://sqlfiddle.com/#!2/924c8
Also here is an example of the data that is out of order (e.g. the comment with id = 5 should be in the second set of results (not the first)
Using an offset of initially 0,15 (as that's how many default comments are displayed on the page):
+-----+---------+-----------------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+
| id  | deleted | comment               | user_id | created             | parent_id | submissionUserId | username | userPhoto                            |
+-----+---------+-----------------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+
| 21 |       0 | Replying to comment 5 |      2 | 2014-08-08 01:14:42 |       5 |               58 | bobcobb2     | 772187eabd2df8ce62a2f1d59f61eb21.jpg |
| 20 |       0 | .... comment 20       |      1 | 2014-08-08 01:13:31 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 19 |       0 | .... comment 19       |      1 | 2014-08-08 01:13:29 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 18 |       0 | .... comment 18       |      1 | 2014-08-08 01:13:26 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 17 |       0 | .... comment 17       |      1 | 2014-08-08 01:13:23 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 16 |       0 | .... comment 16       |      1 | 2014-08-08 01:13:18 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 15 |       0 | .... comment 15       |      1 | 2014-08-08 01:13:16 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 14 |       0 | .... comment 14       |      1 | 2014-08-08 01:13:13 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 13 |       0 | .... comment 13       |      1 | 2014-08-08 01:13:11 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 12 |       0 | .... comment 12       |      1 | 2014-08-08 01:13:06 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 11 |       0 | .... comment 11       |      1 | 2014-08-08 01:13:05 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 10 |       0 | .... comment 10       |      1 | 2014-08-08 01:13:04 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 9 |       0 | .... comment 9        |      1 | 2014-08-08 01:13:02 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 8 |       0 | .... comment 8        |      1 | 2014-08-08 01:13:00 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 7 |       0 | .... comment 7        |      1 | 2014-08-08 01:12:57 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
+-----+---------+-----------------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+

And then passing in the offset 15,30 when you click on the "Load More Comments..." link on page to fetch (older) comments.
+-----+---------+----------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+
| id  | deleted | comment        | user_id | created             | parent_id | submissionUserId | username | userPhoto                            |
+-----+---------+----------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+
| 6 |       0 | .... comment 6 |      1 | 2014-08-08 01:12:54 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 5 |       0 | .... comment 5 |      1 | 2014-08-08 01:12:51 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 4 |       0 | .... comment 4 |      1 | 2014-08-08 01:12:50 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 3 |       0 | .... comment 3 |      1 | 2014-08-08 01:12:48 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 2 |       0 | .... comment 2 |      1 | 2014-08-08 01:12:47 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
| 1 |       0 | .... comment 1 |      1 | 2014-08-08 01:12:41 |      NULL |               58 | bobcobb    | 935dc24b4529374bc1efcb782411f50e.png |
+-----+---------+----------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+

Comment: I don't understand what you mean by an offset. Also, in the absence of any aggregating functions, a GROUP BY clause is inappropriate, and potentially misleading (although, irritatingly, it can be faster than the correct form)
Comment: @Strawberry edited my original post to clarify. Essentially it's just what I'm retrieving each time (e.g. how many entries). Also, thanks for the tip!
Comment: I see, but it would be more useful to show us what you'd actually want the result to look like (You could use a smaller offset for illustrative purposes, 0-5,5-10 say)
Comment: @Strawberry added an example above.
Comment: It seems to me that you are asking several questions here. By offset, you mean that you want to return records 0-15 to the user. Then, when they click to view the next page of results, you want to return records 15-30. Is that correct? I am a little confused by the next part. You want to change the order that the data is returned. Why is the comment with id 21 out of order? Where should it go? There is no parent with id 330. Should the parent id affect the ordering?
Comment: @Jenn that's a mistake from trying to replicate data on my machine. I've updated it to reflect what it should actually reference (id=5). My main question still remains, which is how to get the properly nested comments when I do my offset. So on first page load, they see comments 0,15. They want to read more so they click "View more comments" which sends in the new offset of 15,30, and then 30,45 until all comments are shown. Comment with id=21 is on top, because that's the order it was replied to, but because I initially fetched the comments with the offset 0,15 it shows up first.
Answer: My understanding of the issue is that one of the comments is returned out of order. Currently, your query is ordering all of the comments by their created date in descending order. This is generally correct, except in the case when one comment is a reply to another one. Then, the "child" comment needs to be returned at the same time as the parent comment. Here is a query that will achieve this ordering.
SELECT parent.id,
  parent.deleted,
  parent.comment,
  parent.user_id,
  parent.created,
  parent.parent_id,
  s.id as sid,
  s.user_id submissionUserId,
  u.username,
  u.photo AS userPhoto
FROM submissions_comments AS parent
LEFT JOIN users u ON parent.user_id = u.id
LEFT JOIN submissions s ON parent.submission_id = s.id
WHERE parent.submission_id = ?
AND parent.deleted = 0
GROUP BY parent.id
ORDER BY Case when parent.parent_id is null Then
          parent.created
         Else (Select p.created
               From submissions_comments p
               Where p.id = parent.parent_id) End DESC,
parent.id
LIMIT 15,30

The changes to your original query are the following:

1) The left join to the submissions_comments table has been removed. I
removed this join because the table was only used in the order by. I
used the same table in the order by clause, but the less self-joins,
the better.
2) The order by now includes a case statement.

The order by needs to have a case statement because we need to completely change how the results are ordered if the record has a parent_id. The case statement will return the created date if the parent_id is null. If the parent_id is not null, the case statement will return the parent's created date. This will cause the child comment to be sorted right next to the parent comment.
Then, I ordered by the id so that the parent id would come first. This may not be what you want, you could order by parent.created desc instead so that all the child comments are returned before the parent comment. Here is what it looks like, using the sql fiddle you provided.
Example Results (not all columns included):

|id|deleted|user_id| created             | parent_id |submissionUserId| username |
+-----+---------+----------------+---------+---------------------+-----------+------------------+----------+--------------------------------------+
| 6|     0 |     1 | 2014-08-08 01:12:54 |      NULL |             58 | bobcobb |
| 5|     0 |     1 | 2014-08-08 01:12:51 |      NULL |             58 | bobcobb |
|21|     0 |     2 | 2014-08-08 01:14:42 |         5 |             58 | bobcobb2|
| 4|     0 |     1 | 2014-08-08 01:12:50 |      NULL |             58 | bobcobb |
| 3|     0 |     1 | 2014-08-08 01:12:48 |      NULL |             58 | bobcobb |

The only issue with this query is that the limit is going to supersede everything else. If a parent is listed as row 15 and the child is row 16, these results will NOT be returned together. The limit will stop at row 15.
The only other thing I would like to mention is that mysql does not allow you to pass a parameter in to the LIMIT clause. You may need to rethink this portion of your query if you are planning on passing the range that should be returned as a parameter. One possible solution is to create a temporary table and assign temp ids (based on the ordering of the results) and then only return the results that have the temp id between the range that you are looking for.
Comment: The offset is being passed in as a parameter that I'm just interpolating it depending on which page it's on (I keep track of it with my front-end through Javascript). Is there any way to circumvent that caveat you mentioned above re: the parent being id=15 and child being id=16 with an offset of 0,15? Any way to apply the offset ONLY to the parent?
Comment: @bob_cobb I believe that could be done with the use of temporary tables. The biggest issue I see is the potential for recursion in your data, which mysql does not handle very well. What if a child has a child and that child has a child? How should the data be ordered then? The only way to order this situation properly is by creating a separate stored procedure and calling that.
Comment: Thanks, Jenn. I'll look into that. As for recursive with this table, it's only 1 level deep (and all children would be ordered by created date DESC), so I don't think it'd be a huge issue.
Comment: My suggestion for the parents and children to always be returned together is to create a temporary table with a column 'countId' or something similar. When you encounter a parent, you assign a new countId (beginning with 1 and incrementing by 1). When you encounter a child, assign the same countId as the parent.

Let's assume your range is 0, 15. Select from the temporary table (instead of your submissions_comments) and specify that the count id must be greater than 0 and less than or equal to 15.


How to import image file in vueJs template?

Question: using Vite I need to import image url for example with the way like this
 <svg :src="import('®/@material-icons/svg/1k/outline.svg')"></svg>

but instead of url I'm getting src="[object Promise]"
is there any ways to make it work correctly?
Answer: You have to use require
<svg :src="require('®/@material-icons/svg/1k/outline.svg')"></svg>

Ensure to have the correct path for the file
Fore Vite
<svg :src="svgPath"></svg>

Comment: Edited. Please try. I came across with this [solution](https://stackoverflow.com/questions/69696677/vite-vue-3-require-is-not-defined-when-using-image-source-as-props)
Comment: I've updated the answer, give it a try
Comment: You can make an utility function in a separate file, and pass the path as parameter and return the default value
Comment: but require is not working with Vite
Comment: thank you, but seems vue render works synchronously and I cannot use await(
I'm getting 'await' is only allowed within async functions and at the top levels of modules.
and I don't know is there any ways to change templates render type to async
Comment: yep, thanks, that works, but that's a lot of code if compare with require using webpack, is there any plugins to make that shorter)?
Answer: The easiest way to work with images in Vitejs is to place images inside the public folder then use them without any import, Assume that we have a folder named svg inside the public one :
<svg src="/svg/1k/outline.svg"></svg>

Or import it as module then bind it to the src attribute :
<template>
  <svg :src="imgUrl"></svg>
</template>

Comment: thanks but I'm using @material-icons/svg which are located in node_modules
seems the only problem I have is I have 30+ svgs and that's pretty hard to remember name of every variable using import every time in script((


How to select all children text but excluding a tag in Selenium's XPath selector?

Question: I have this html:

Title 1

Sub-Title 1

    Description 1.

Description 2.

Sub-Title 2

    Description 1
Description 2

        Information Title

Long Information Text

I want to get all text in
 in Selenium's find_element_by_xpath function but excluding
's content, so the expected result is like this:
Title 1

Sub-Title 1

Descripton 1.

Descripton 2.

Sub-Title 2

Descripton 1.
Descripton 2.

I can get it by using this code in online XPath tester:
//div[@id="content"]/descendant::text()[not(ancestor::div/@class="infobox")]

But if I pass the code to selenium's find_element_by_xpath, I will get selenium.common.exceptions.InvalidSelectorException.
result = driver.find_element_by_xpath('//div[@id="content"]/descendant::text()[not(ancestor::div/@class="infobox")]')

Answer: The xpath used inside find_element_by_xpath() has to point to an element, not a text node and not an attribute.
The easiest approach here, would be to find the parent tag, find the child tag which text you want to exclude and remove the child's text from the parent's text:
parent = driver.find_element_by_id('content')
child = parent.find_element_by_class_name('infobox')
print parent.text.replace(child.text, '')

Comment: Great answer! I know you mentioned this is easiest. But can the xpath be written for this?
Comment: @Saifur thank you, it can, though `find_element_by_xpath()` cannot be used for this. The other option I thought was to evaluate the xpath with js and `execute_script()`.


Dynamically retrieving information from JSON using javascript

Question: I'm trying to grab a series of strings from a JSON object and concatenate them into one big string. It seemed pretty obvious for me to just use a loop, adding each new string in every iteration of said loop. When I actually plugged it in, however, I get some odd errors.
TypeError: data.posts[i] is undefined

I would normally just assume that it can't be called like that (I'm new to javascript so I'm basing much of this upon educated guesses), but here's the weird thing: the logs I printed to firebug contain exactly the expected information. I could live with the unexplained error, but then it won't display the combined string on the web page.
var data = JSON.parse(d);
var i = 0;
while(i <= data["posts"].length) {
    messages += "" + data["posts"][i]['nickname']
             + ": - " + data["posts"][i]['content'] + "
";
    i++;
    console.log(messages);
}
console.log(messages);
$('.post1').html(messages);

What exactly am I missing here?
Comment: @user1375883 then see my answer, you probably have an array of size 0
Comment: @user1375883 please add this info to the question not the comments :D
Comment: What is the structure of your JSON?
Comment: something is very strange with your question, the error message does not seem to match the code you posted... what line exactly did that error occur?
Comment: The error occurs on the first line inside the while loop.

The JSON is an array containing 'error' and 'posts'. Posts is populated by rows from a database query:

    $data['posts'] = $this->communication_model->fetch_posts($username, $offset );
Answer: Hard to tell with your question if this is the only problem, but it looks like you have an off by one issue.  If the array is indexed 0 - n then length returns n+1 and your loop should be
while(i < data["posts"].length) {

note the < and not a <=
Comment: Well now I feel like a MASSIVE idiot. Still, thanks for the help!
Answer: I recommend using a for loop and defining the whole block of returned data to be defined as a single set, for example, data.
And use the following method:
$.ajax(
{
    // Post variable1 to url.
    type : 'post',
    url : 'urlToBackend,
    dataType : 'json',
    data :
    {
        'variable1' : 'theValue'
    },
    success : function(data)
    {
        var message;
        var reply1;
        var reply2;

        for(var i = 0; i < data.length; i++)
        {
            reply1 = data[i].reply1FromBackend; // Assuming that reply1FromBackend was returned.
            reply2 = data[i].reply2FromBackend; // Assuming that reply2FromBackend was returned.

            message += reply1;
            message += reply2;
        }
        // do something
    },
    complete : function(data)
    {
        // do something
    }
});

So you just have to make sure that the url is valid, that the backend can do something with the variable1 and that the backend echos reply1FromBackend and replyFromBackend, like this:
// Receive the posted variable's value if it is set.
$variable1= isset($_POST['variable1']) ? $_POST['variable1'] : false;

// ... do something

$json[] = array
(
    'reply1FromBackend' => 'yo',
    'reply2FromBackend' => 'sup'
);
echo json_encode($json);
flush();

Did that help?


Cron process sends email, where are these sent emails?

Question: Ubuntu 14.04
I have an email process that sends an email via cron, using sendemail (which I believe is a Perl program that doesn't need an MTA). Where are these sent-emails stored? If they are stored at all?
NOTE: Since I installed sendemail, it looks like all other email packages, postfix, mail, sendmail, were uninstalled automatically.
Thank you.
Comment: No, it does not. It only sends them. It does not archive them or keep local copies.
Comment: Are you asking where the mail gets sent to (as in to firstname.lastname@example.com, or the users mail when the crontab was not for root), or if the cronjob keeps a mail folder with things like 'sent mail', 'inbox', 'spam' etc etc? In the last case the answer is Nope. It just sends the mail and does not keep any logs.
Comment: If I send an email using alpine, a copy of the outgoing email is stored in a folder called "sent-email". My question is, does "sendemail" the script, save sent emails somewhere.
Answer: The script does not save its sent email, it just sends out the mail - that's all.


jQuery if condition for exactly matching classes

Question: I have the code presented below in php echo statement. Brackets are empty but can assure you that statement which I put inside to modify CSS works - with one flaw.
I want it to work for elements with class attribute equal to "zoom" or "zoom first". Unfortunately it works for all elements which have "zoom" class, including "woocommerce-main-image zoom".
I could exclude elements with "woocommerce-main-image" class, but I would prefer a cleaner solution, applying my code to elements with these 2 specified class attributes:
if ($(this).hasClass("zoom") || $(this).hasClass("zoom first")) {}

Comment: There is no such thing as class `"zoom first"`, that means it has both classes `"zoom"` and `"first"`. As such you might want to change your class to be something like `zoom-first`. Classes are seperated by spaces, so if an element has `class="foo bar zoom"` it still has the `zoom` class.
Comment: $(this).attr("class") === "zoom" || $(this).attr("class") === "zoom first"
Comment: cleaner solution check this fiddle http://jsfiddle.net/ZdNaf/
Comment: so it'll only check if the class is exactly equal to either "zoom" or "zoom first"
Comment: I realize that they are multiple classes, but contained in one class attribute. Unfortunately it is the way woocommerce and zooming plugin in Wordpress name the elements, so changing class names is in this case a difficult and invasive task.
Comment: Thanks everyone for support, I will accept Jorrex' solution as an answer. I got it to work as it should. The solution from jsfiddle is very good, but I am using interaction with clicked element's siblings what complicates the use of it.
Answer: If you want to search elements that has the "zoom" class exclusively, or elements that has both "zoom" and "first" exclusively, maybe you could try the below:

var search = ["zoom", "zoom first"];

$.each(search, function(i, v) {
  var classes = v.split(' ');

  $('.' + classes.join('.'))
    .filter(function() {
      return $(this).attr('class').split(' ').length == classes.length;
    })
    // Do something here
    .css('background', 'yellow');
});

zoom

zoom foo

first zoom

zoom first

zoom foo first

zoom first foo