Check if class property has been set

Question: Lets assume I have a User class
public Class User
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Level {get;set;}
}

User user1 = new User();
user1.Name = "name";
user1.Surname = "Surname";
user1.Level = 0;

User user2 = new User();
user2.Name = "name";
user2.Surname = "Surname";

When I check user1.Level == user2.Level it returns true since default int value is 0.
So is there any way to do that I can understand that Level property of user2 is not set so that I can say these two are not identical?
Comment: You could set the default to (for example) -1 in the constructor
Comment: You could use `int?`, but then you would probably better setting level 1 as the default entry level. Your question is a bit of an XY problem.. what are you trying to achieve?
Answer:
If you use int? as type for Level, it will be NULL when not setted.

public class User
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int? Level { get; set; }
}

You can use the setter of the Level attribute and set a boolean when you set a new value, if the other proposed solution is not good for you. Example:

public class User
{
    public string Name { get; set; }
    public string Surname { get; set; }
    private int _Level;
    private bool _hasLevel;
    public int Level
    {
        get { return _Level; }
        set { _Level= value; _hasLevel = true; }
    }

    public bool HasLevel { get { return _hasLevel; } }
}

Answer: Another option (in addition to the others suggested) is to set the value to something other than 0 in the class constructor. It's common to use -1.
public Class User
{
    public User()
    {
        Level = -1;
    }

    public string Name { get; set; }
    public string Surname { get; set; }
    public int Level {get;set;}
}

Answer: Use Nullable
public Class User
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int? Level {get;set;}
}

It will have by default value null instead of value 0.
for more about Nullable look at msdn documentation
Answer: You can change your class to make Level nullable.
public class User
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int? Level {get;set;}
}

Check if class property has been set


In need of help using /testfor command

Question: I want to test if there is a sheep at location -155 7 14. Im a begginer and have little to no clue to what I'm doing. I dont know how to format anything in minecraft command blocks like when to use !,=,@,[,] etc. If there is no sheep there I want the code to detect it and thus carry on a different command, vise versa. How should I format this?
Comment: Please do some research next time before posting a question. The [Minecraft Wiki's page on `/testfor`](https://minecraft.gamepedia.com/Commands/testfor) should do you well in helping you learn the basics of commands. Also check out their [page on target selectors](https://minecraft.gamepedia.com/Commands#Target_selectors).
Answer: /testfor @e[type=sheep,x=-155,y=7,z=14,r=1]

type=sheep - Look for a sheep.
x=-155..y=..z=... - Start search at these coordinates
r=1 - Look in a radius of 1 block
Comment: I tried that but it keeps on saying "No targets matched selector." Does this mean it's false? (as in there is no sheep there)
Comment: It's resolved! I didn't need the command block and replaced it with a redstone circut that works.
Comment: Very good explanation! I replaced metre with block because not everyone is clear about 1m being one block.

In need of help using /testfor command


Understanding Node Addon API (N-API) HandleScope

Question: I have difficulties to understand how to correctly use HandleScope and EscapableHandleScope. For example, from this Node example:
MyObject::MyObject(const Napi::CallbackInfo& info) : Napi::ObjectWrap<MyObject>(info) {
  Napi::Env env = info.Env();
  Napi::HandleScope scope(env);

  this->val_ = info[0].As<Napi::Number>().DoubleValue();
};

Why do we need to create a new HandleScope in this case? And from this other example:
Napi::Object CreateObject(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  Napi::Object obj = Napi::Object::New(env);
  obj.Set(Napi::String::New(env, "msg"), info[0].ToString());

  return obj;
}

Why is it not needed here?
Also, I didn't find any example using EscapableHandleScope, when is this needed?
Answer: The following seems to hold true for nan, N-API, and node-addon-api:

[Handle Scope] is an abstraction used to control and modify the lifetime of objects created within a particular scope. In general, N-API values are created within the context of a handle scope. When a native method is called from JavaScript, a default handle scope will exist. If the user does not explicitly create a new handle scope, N-API values will be created in the default handle scope. For any invocations of code outside the execution of a native method (for instance, during a libuv callback invocation), the module is required to create a scope before invoking any functions that can result in the creation of JavaScript values.

Source: https://nodejs.org/api/n-api.html#n_api_napi_handle_scope
Which means in the examples given, since both expect const Napi::CallbackInfo& info it's obvious both are called from JavaScript directly, so they already have a scope provided by the JS runtime -- the additional calls to create scope are only necessary if you want to perform memory management yourself, or in cases where your code is executing independently of the JS engine (such as on a timer, a callback from something other than JS code, etc.)
Answer: Why do we need to create a new HandleScope in the snippet?
Actually, we can choose to not create a new HandleScope here. There is an outer scope in Node.js that is enclosing our handles created in this function. But then all the handles created in this function will live longer than necessary and handles cost resources.
When do we need EscapableHandleScope?
When a handle from an inner scope needs to live beyond the lifespan of that scope. For example, when returning data newly created in a function.
Reference
V8 embed: https://v8.dev/docs/embed#handles-and-garbage-collection
node-addon-api: https://github.com/nodejs/node-addon-api/blob/master/doc/object_lifetime_management.md
Answer: For an explanation of what HandleScopes are and what to use them for, see V8's documentation, e.g. for the class Local:

There are two types of handles: local and persistent handles.
Local handles are light-weight and transient and typically used in
  local operations.  They are managed by HandleScopes. That means that a
  HandleScope must exist on the stack when they are created and that they are only valid inside of the HandleScope active during their
  creation.  For passing a local handle to an outer HandleScope, an
  EscapableHandleScope and its Escape() method must be used.

And for the class HandleScope:

A stack-allocated class that governs a number of local handles. After
  a handle scope has been created, all local handles will be allocated
  within that handle scope until either the handle scope is deleted or
  another handle scope is created.  If there is already a handle scope
  and a new one is created, all allocations will take place in the new
  handle scope until it is deleted.  After that, new handles will again
  be allocated in the original handle scope.
After the handle scope of a local handle has been deleted the garbage
  collector will no longer track the object stored in the handle and may
  deallocate it.  The behavior of accessing a handle for which the
  handle scope has been deleted is undefined.

Pragmatically:

When calling from JavaScript into C++, you'll need at least one HandleScope if the C++ code creates any Local<>s. Usually exactly one HandleScope is the right number.
There's a cost to creating and destroying HandleScopes, so if you have many fine-grained HandleScopes, you're wasting time. On the other hand, a HandleScope (by design, that's its purpose!) keeps all objects alive (in the GC sense) that the handles contained in it are referring to, so for very long-running code, or loops with many iterations, you may want to introduce short-lived HandleScopes so that temporary objects you're done with can be freed.
As the documentation says, you need an EscapableHandleScope if you want to return an object beyond the end of the lifetime of the scope.
Comment: But the OP's question was specifically about the Node Addon API and Napi::HandleScope, not about V8 and v8::HandleScope.
Comment: This is incorrect. A HandleScope is generally superfluous at the top level of a C++ method.  To quote the NAPI documentation: "The lifespan for the default scope is tied to the lifespan of the native method call. The result is that, by default, handles remain valid and the objects associated with these handles will be held live for the lifespan of the native method call."
Comment: That's not a contradiction to what I wrote. You always need a HandleScope. If some abstraction layer (like NAPI) already implicitly creates one (this "default scope" you mention), then you don't need to manually create another.
Comment: Well I do understand why creating an object in a factory requires an `EscapableHandleScope` . But it means that any getter function should also use `EscapableHandleScope`! Though node-addon-api examples are not like this. Why is that?
Comment: @norekhov: when returning to JavaScript, you don't need any HandleScopes at all any more (they are a C++ concept). EscapableHandleScopes are for returning to other C++ (and hence HandleScope-managed) code.


Prove dual space Y* is subspace of X* if X is subspace of Y

Question: We have V - vector space and U, W ⊆ V (subspaces). U* and W* are the dual spaces accordingly. I have to prove that if U is subspace of W, then W* is subspace of U*. I am honestly baffled because the concept of duality is still fresh in my mind. What I tried is proving that W* is closed around scalar multiplication and addition, but because it's a space consisting of functionals I don't know how to proceed. Any hints would be welcome.
Comment: Strange result... even in finite dimension it's not true...
Comment: If $X$ is a vector space, I will assume that $X^*$ denotes the vector space of all linear maps from $X$ to the scalar field. Thus, an element of $W^*$ is a function with domain $W$, so it cannot be an element of $U^*$ unless $U=W$ (in which case $U^*=W^*$ is trivially true). Thus, this result is false if $U \neq W$.
Comment: @azif00 thanks for the explanation. thats weird we had this on an exam. maybe i wrote it incorrectly...
Answer: Let $U\subset W$, and $f \in W^*$. So
$$\forall w \in W, f(w) \in \mathbb{F}.$$
($\mathbb{F}$ is the scalar field). As $U \subset W$, then $\forall u \in U$, $u \in W$. Then, $f(u) \in \mathbb{F}, \forall u \in U$. So, as $f$ is linear in $W$, then $f$ is linear in $U$. Therefore, $f \in U^*$.


Upgrading Chrome stable aptitude reports version 39 but chrome://chrome reports 38

Question: I am trying to upgrade google chrome to the latest stable release.
I used apt-get purge google-chrome-stable to remove and then installed the lastest through the PPA
<code>/opt/google/chrome$ apt-cache policy google-chrome-stable
google-chrome-stable:
Installed: 39.0.2171.71-1
Candidate: 39.0.2171.71-1
Version table:
*** 39.0.2171.71-1 0
500 http://dl.google.com/linux/chrome/deb/ stable/main amd64 Packages
100 /var/lib/dpkg/status
</code>
However the about page lists Version 38.0.2125.122 (64-bit)
Ideas?
Answer: Download the latest deb package manually
 and install it. When you install that deb package via Software center, PPA will be added automatically. there is no need of any complications


What can be done to avoid non linear snapping when cutting large tiles by the score and snap method?

Question: These are porcelain tiles
I am referring to cracks like in the picture below
They seem to be caused by the fact that the vertical force used to snap/crack the  tile is applied at the opposite end and it is probably uneven or diminished at the other end of the tile
Comment: Diamond blade saw and water cut really well.
Comment: a better tool and a bigger hammer is always the answer but I was asking about this specific method and not for wet cutting
Comment: After scoring, how are you snapping it? Over an edge the full length of the tile?
Comment: (Timed out on my edit) if you're using a score and snap tool, with the v-shaped foot that breaks the tile, you could try two things: a second scoring pass to score more deeply, and slide the movable part to snap from the middle of the tile.
Comment: I am using Qep Slim line 24. You cant try to snap on the middle as the blade will touch the tile first ...only at the far end of the cut the blade/scoring disk cleard the tile and then that foot thar is used to snap the tails can e used. They say one gently scoring pass only
Comment: Scoring a shallow grove on the front surface then scoring the other side, then breaking it by tapping and bending.
Comment: Add something hard to fit between the lever legs and the tile to raise the wheel but land the feet, so that you can snap in the middle of the tile rather than at the end. You could try two pieces of tile. Whether this works depends on the dimensions of the lever/fulcrum.
Comment: On the bright side, it's leaving extra material to be removed and not veering into the piece you want to keep, ruining it.
Answer: Ceramic tiles approved for flooring and porcelain tiles are much harder than the ceramic wall tile variants, and they require deep and continuous scoring in order to provide a straight snap cut.
When the snap cut curves away from the scoring line (as in your picture) it means that the scoring was not deep enough especially at and around the tile edge where the scoring starts (because it is opposite from where the tile is pressed to snap).
When scoring, apply more pressure and roll slowly.
Make sure the cutting wheel scores both ends around the tile edge, that is, the glazed top but also some of the ceramic side. After scoring once by pushing the lever and wheel forward, roll the wheel back and ride the tile edge a few times to make sure it is clearly scored. Do this for both tile edges.
Then snap with a rapid and firm movement of the lever.
Should this still fail, use a a tile nipper (or a wet saw) to score both ends deeper.
Comment: I have a cheap (crap) score/snap tool and I find it hard to score the ends of the score line properly in only one direction.  I have to score in both directions, and each end gets scored properly only when moving towards its edge.  But moving towards the snap foot is awkward because it gets in the way so it has to be propped up.   I think this answer is good advice, but to generalize: "Make sure it's thoroughly scored".


Strategies for Fixing Problems / Tweaking NHibernate Apps in Production

Question: First off, I am not a DBA, but I do work in an environment where DBAs do tune/make changes in the production database from time to time in ways that do not cause the need for an application rebuild/redeployment. Usually these changes consist of reworking indexes, changing procs, and sometimes changing the table structure in minor ways (usually abstracted from the app via procs).
Obviously, a team should strive to catch performance problems with NHibernate before they get into production using things like NHProf, SQL Profiler, and load tests. That being said, are there certain strategies that can be used to allow some amount of tweaking once the code is built and out running in production? Using stored procedures 100% of the time seems like it would allow the most flexibility for the DBA's, but obviously that would really kill the efficiency of NHibernate. From what I've read, updatable views (in SQL Server) don't really work that well with NHibernate either (this may-or-may-not be true).
I've read quite a bit about NHibernate and experimented with it over the years, but I have never put it into practice in a production environment. I have yet to come across a set of "best practices" to allow for maximum tweaking once deployed.
As an NHibernate user, how are you and your team dealing with issues if they arise in production? My production environment is made up of ASP.NET apps and SQL server, but I don't think the answers need to be restricted to that platform.
Answer: I'm not in the deploy phase yet, but on my current project I've come up against this already and my solution presently has been to replace my queries with stored procs.  As long as the shape of the data coming back from the DB remains the same it's not a big deal.  Yeah you do lose some of that agility you enjoyed during development but I'm not sure it's as bad as it initially sounds.  You'll have a code push when you first make the change of course, and then from that point it's just proc changes.
Answer: I am in a similar position, and in order to keep our DBA happy, I did the following:

Wrote some of the queries in HQL, some others in SQL (especially those perf-sensitive)
Externalized those queries to files, one file per query.
When your app needs to execute of these queries, it just loads the appropriate file, optionally running it through a pre-processor, and runs it.

With this approach, the DBA could theoretically tweak the queries just by modifying those files. That's quite similar to having stored procedures.
In practice, it's up to you to decide if you'll really give the DBA access to those files (if you catch my drift...)
IMHO the DBA should just use the DBMS's profiling tools and report her findings back to the devs (as in "there's this query that is running 20 times/sec and does 10 joins. is that really necessary? can it be cached? do you really need all those joins? can we denormalize this?" etc.
Comment: This sounds like an interesting approach. I see you blog. Going into more detail on this with examples would make an interesting blog post IMHO.
Answer: You can use a profiler like NHProf to see the sql queries executed, so you can show them to a DBA. This tool can also detect some problem like n+1 select.
Using a second level of cache can be useful : http://web.archive.org/web/20110514214657/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/11/09/first-and-second-level-caching-in-nhibernate.aspx
Comment: NHProf is a great tool to use during development, but it doesn't provide a complete solution for this scenario beyond identifying the details and amount of db hits that are being performed. However, used early it can vastly improve your mappings and querying strategy, which is bound to have a positive effect in reducing the amount of issues that arise in production.


Multiple many-to-many relations to the same model in Django

Question: Given the following model with two many-to-many relations:
class Child(models.Model):
    name = models.CharField(max_length=80)

class Foo(models.Model):
    bar = models.ManyToManyField(Child)
    baz = models.ManyToManyField(Child)

This gives the error:
accounts.foo: Accessor for m2m field 'bar' clashes with related m2m field 'Child.foo_set'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Accessor for m2m field 'baz' clashes with related m2m field 'Child.foo_set'. Add a related_name argument to the definition for 'baz'.

Fine; I don't need the backwards relation. According to the Django docs for related_name (which is only under ForeignKey as far as I can see), I can set related_name="+" and backward relations won't be created:
class Child(models.Model):
    name = models.CharField(max_length=80)

class Foo(models.Model):
    bar = models.ManyToManyField(Child, related_name="+")
    baz = models.ManyToManyField(Child, related_name="+")

This doesn't work though:
accounts.foo: Accessor for m2m field 'bar' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Reverse query name for m2m field 'bar' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'bar'.
accounts.foo: Accessor for m2m field 'baz' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'baz'.
accounts.foo: Reverse query name for m2m field 'baz' clashes with related m2m field 'Child.+'. Add a related_name argument to the definition for 'baz'.

What do I need to do to avoid creating reverse relations?
Answer: I think you need to just give the two fields different related_names:
class Child(models.Model):
  name = models.CharField(max_length=80)

class Foo(models.Model):
  bar = models.ManyToManyField(Child, related_name="bar")
  baz = models.ManyToManyField(Child, related_name="baz")

If you don't give a related name, then it's trying to create the same accessor name (foo_set) twice on the Child model. If you give the same related name, it's again going to try to create the same accessor twice, so you need to give unique related names. With the above code to define your models, then given a Child instance c, you can access related Foo objects with c.bar.all() and c.baz.all().
If you don't want the backwards relations, then append a + to each of the (unique) related names:
class Foo(models.Model):
  bar = models.ManyToManyField(Child, related_name="bar+")
  baz = models.ManyToManyField(Child, related_name="baz+")

Comment: How can we get all Child items from `Foo` Model, can we do this way `self.Child_set.all()`. is it right or any other approach?
Comment: The approach [the docs](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.ForeignKey.related_name) are now recommending is `related_name="+"` if you don't want the backwards relations.
Answer: You haven't read Django's documentation carefully enough. Here it says:

If you have more than one ManyToManyField pointing to the same model and want to suppress the backwards relations, set each related_name to a unique value ending with '+'.

The related_name attributes have to be unique, not the same.
Comment: Guilty as charged :). Thanks -- I've accepted the other answer, but an upvote for you.


How to automatically start a tunnel when a session is opened in MobaXterm?

Question: I use MobaXterm for remote access to servers running in the cloud. For development and admin purposes, these servers expose admin application on local network interfaces. For example, Tomcat will expose 127.0.0.1/manager.
Since I prefer not to have to expose these services to the internet, I've set up ssh tunnels in MobaXterm to connect to these web applications on a local port through local port forwarding, which is easy to set up with the application itself.
My question: How can you get MobaXterm to automatically start a tunnel when a session is opened and to stop/close them when the session is ended?
I know a client like Putty would do this by default, but I don't want to use different clients for different jobs if I don't have to and MobaXterm has other features I need that Putty doesn't.
Comment: This could be a pretty obvious feature request for Moba. I'll also need it...
Answer: You can setup new SSH tunnels in Tunneling section (or from the MobaXterm's Tools menu, you can start MobaSSHTunnel). This will show a graphical port forwarding tool, where you can setup a new SSH tunnels which can be configured to be started automatically at MobaXterm startup by selecting Autostart from the tunnel settings.
Comment: Thanks for the feedback, I'm aware of the built-in wizard for setting up the connection, of which you've provided a screenshot, but your suggestion for auto-starting would start the tunnel on MobaXTerm startup. I only want the tunnel to be opened when a specific session is started. This way, I can connect to services running on a specific port depending on what server I'm connected to. Your suggestion would *always* start and having multiple tunnels mapped to the same local port would be an issue.
Comment: This solution doesn't quite work for me, because it requires me to log in again on the SSH server (where I need to type a long password, unfortunately). With Putty and also with OpenSSH the tunnel is established together with the interactive session, requiring only one login for both.
Comment: Thanks for the useful illustration.
Answer: Try to use MyEn Tunnel:
https://myentunnel.informer.com/
There is an option to Connect on Startup


Strange autoclicking of qpushbutton

Question: I've been trying to learn c++ and qt framework by doing a point of sale software project.my main window has couple of tabs and with in one tab i have a qpushbutton which open a newpurchase dialog which takes input from user to record a new purchase from supplier.this newpurchase dialog has a lineedit which, when recieves product barcode from a barcode reader ,triggers another quanity dialog which, user can use to enter the quantity of the product. but when i click ok on the button box of the quantity dialog instead of closing just the quantity dialog ,it closes the newpurchase dialog as well.i debugged the qt application and it shows that a qpushbutton (which saves and closes the newpurchase dialog)on the newpuchase dialog gets triggered automatically.additionally this behaviour is only spotted when quantity dialog is triggered through the barcode lineedit,i have another lineedit which accepts description of the product and triggers the same quantity dialog ,but clicking ok button when quantity dialog is triggered through description lineedit does not closes the newpurchase dialog or trigger the qpushbutton which saves and closes the newpurchase dialog.im attaching the screen shots of the dialog and code for the dialogs
on mainwindow.cpp
<code>   void MainWindow::on_pushButton_clicked()
{
    newpurchase mypurchase;
    connect(&mypurchase,SIGNAL(purchase_added()),this,SLOT(update_view()));
    mypurchase.exec();
}
</code>
newpurchase dialog
newpurchase.cpp
<code>#include "newpurchase.h"
#include "ui_newpurchase.h"
#include <QtDebug>
#include <qtablewidget.h>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QCompleter>
#include <QObject>
#include <QWidget>
#include <QDate>

newpurchase::newpurchase(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::newpurchase)
{
    ui->setupUi(this);
    QSqlQuery qry;
    qry.prepare("select description from product");
    if(!qry.exec())
    {
        qDebug() << "error getting description from product";
    }
    QStringList items;
    while(qry.next())
    {
        items <<qry.value(0).toString();
    }
    QCompleter *completer =new QCompleter(items,this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    ui->lineEdit_descripion->setCompleter(completer);
  connect(completer,static_cast<void (QCompleter::*)(const QString&)>(&QCompleter::activated),
               [&](const QString &text)->void

    {
        newpurchase::clear(text);
    });

    QSqlQuery supqry;
    supqry.prepare("select supplier_name from supplier");
    if(!supqry.exec())
    {
        qDebug() << "error getting suppliername from supplier";
    }
    QStringList supitems;
    while(supqry.next())
    {
        supitems <<supqry.value(0).toString();
    }
    QCompleter *supcompleter =new QCompleter(supitems,this);
    supcompleter->setCaseSensitivity(Qt::CaseInsensitive);
    ui->lineEdit_sup->setCompleter(supcompleter);
}

newpurchase::~newpurchase()
{
    delete ui;
}

void newpurchase::on_lineEdit_barcode_returnPressed()
{
    if(!ui->lineEdit_sale->text().isEmpty() && !ui->lineEdit_sup->text().isEmpty() && !ui->lineEdit_inv->text().isEmpty())
    {
        quantity_dialog quandialog;
        connect(&quandialog,SIGNAL(purdetails(QString)),this,SLOT(code(QString)));
       quandialog.exec();
    }
    else
    {

        Errdialog myerror("please provide supplier and invoice" );
        myerror.exec();
    }
}
void newpurchase::saveDataIntoTable(QString item,double price,int quantity,QString code,QString date)
{
    double rupee =price*quantity*1.00;
    //qDebug() <<date;

    QString mrp= QString::number(rupee,'f',2);
    QString qty= QString::number(quantity);
    QString prc= QString::number(price);
    // QString kod= QString::number(code);

    if (!ui->tableWidget)
        return;

    const int currentRow = ui->tableWidget->rowCount();
    ui->tableWidget->setRowCount(currentRow + 1);

    ui->tableWidget->setItem(currentRow, 0, new QTableWidgetItem(item));
    ui->tableWidget->setItem(currentRow, 1, new QTableWidgetItem(prc));
    ui->tableWidget->setItem(currentRow, 2, new QTableWidgetItem(qty));
    ui->tableWidget->setItem(currentRow, 3, new QTableWidgetItem(mrp));
    ui->tableWidget->setItem(currentRow, 4, new QTableWidgetItem(code));
    ui->tableWidget->setItem(currentRow, 5, new QTableWidgetItem(date));

    double total=ui->label_3->text().toDouble();
    total = total+rupee;
    ui->label_3->setText(QString::number(total,'f',2));

}
void newpurchase::clear(QString item)
{
    if(!item.isEmpty())
    {
        if(!ui->lineEdit_des->text().isEmpty() && !ui->lineEdit_sup->text().isEmpty() && !ui->lineEdit_inv->text().isEmpty())
        {
            quantity_dialog quandialog;
            connect(&quandialog,SIGNAL(purdetails(QString)),this,SLOT(descr(QString)));
            quandialog.exec();

        }
        else
        {

            Errdialog myerror("please provide supplier and invoice" );
            myerror.exec();
        }
    }
}

void newpurchase::descr(QString q)
{
    QStringList elements = q.split(':');
    QSqlQuery qry;
    qry.prepare("select * from product where description='"+ui->lineEdit_des->text()+"'");
    if(!qry.exec())
    {
        qDebug() << "error getting table product";
    }
    if (qry.next())
    {
        QString result=qry.value(1).toString();
        double cost= elements[1].toDouble();
        QString itemco=qry.value(2).toString();
        int quan=elements[0].toInt();
        QString mfd=elements[2];
        saveDataIntoTable(result,cost,quan,itemco,mfd);
        ui->lineEdit_des->clear();
    }
}
void newpurchase::on_pushButton_clicked()
{

    QItemSelectionModel *select =ui->tableWidget->selectionModel();
    int row = select->selectedRows().takeFirst().row();
    double rupee=ui->tableWidget->item(row,3)->text().toDouble();
    ui->tableWidget->removeRow(row);
    double total=ui->label_3->text().toDouble();
    total = total-rupee;
    ui->label_3->setText(QString::number(total,'f',2));

}

void newpurchase::on_lineEdit_des_returnPressed()
{
}
void newpurchase::code(QString q)
{

    QStringList elements = q.split(':');

    QSqlQuery qry;
    qry.prepare("select * from product where code="+ui->lineEdit_sale->text());
    if(!qry.exec())
    {
        qDebug() << "error getting table product";
    }
    if (qry.next())
    {
        QString result=qry.value(1).toString();
        double cost= elements[2].toDouble();
        QString itemco=qry.value(2).toString();
        int quan=elements[0].toInt();
        QString mfd=elements[1];

        saveDataIntoTable(result,cost,quan,itemco,mfd);

    }

    ui->lineEdit_sale->clear();
}

void newpurchase::on_pushButton_2_clicked()
{

    QString datetime= QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString supplier=ui->lineEdit_sup->text();
    QString invoice=ui->lineEdit_inv->text();
    int numrow=ui->tableWidget->rowCount();
   // qDebug() << numrow;

    for (int i = 0; i < numrow; i++)
    {

        QSqlQuery query;
        query.prepare("SELECT MAX(Id) FROM stock_transaction");
        if(!query.exec())
        {
            qDebug() << "error getting id";
        }
        int id=0 ;
        if (query.next())
        {
            id=query.value(0).toInt()+1;
        }

        QString coder=ui->tableWidget->item(i,4)->text();
        QString qua=ui->tableWidget->item(i,2)->text();
        double rate=ui->tableWidget->item(i,1)->text().toDouble();
        QString date= ui->tableWidget->item(i,5)->text();
        QString d=QString::number(id);
        QString batch=supplier+"_"+invoice+"_"+d;

        QSqlQuery querysale;

        querysale.prepare("INSERT INTO stock_transaction(id,code,stock,mfd,supplier,invoice,cost,date_time) VALUES(:id,:code,:stock,:mfd,:supplier,:invoice,:cost,:date_time)");

        querysale.bindValue(":id", id);
        querysale.bindValue(":code",coder);
        querysale.bindValue(":stock", qua.toInt());
        querysale.bindValue(":mfd",date);
        querysale.bindValue(":supplier", supplier);
        querysale.bindValue(":invoice", invoice);
        querysale.bindValue(":cost", rate*1.00);
        querysale.bindValue(":date_time", datetime);

        if(!querysale.exec())
        {
            qDebug() << "error recording sale";
        }

    }
    emit this->purchase_added();
    close();

}
</code>
quantity dialog
quantity.cpp
<code>#include "quantity_dialog.h"
    #include "ui_quantity_dialog.h"

     quantity_dialog::quantity_dialog(QWidget *parent) :
                                QDialog(parent),
                                ui(new Ui::quantity_dialog)
                            {
                                ui->setupUi(this);
                                ui->lineEdit_quan->setFocus();
                                ui->buttonBox->setEnabled(false);
                                connect(ui->lineEdit_quan, SIGNAL(textChanged(QString)), this, SLOT(checkLineEdits()));
                                connect(ui->dateEdit, SIGNAL(dateChanged(QDate)), this, SLOT(checkLineEdits()));
                                connect(ui->lineEdit_3, SIGNAL(textChanged(QString)), this, SLOT(checkLineEdits()));
                            }

                            quantity_dialog::~quantity_dialog()
                            {
                                delete ui;
                            }

                            void quantity_dialog::on_buttonBox_accepted()
                            {
                                emit purdetails(ui->lineEdit_quan->text()+":"+ui->dateEdit->text()+":"+ui->lineEdit_3->text());

                                ui->lineEdit_quan->clear();

                            }
</code>
Please let me know if i can provide any other details
Comment: It is very hard to read the text without punctuation.
Comment: Sorry if I might sound rude, but your your question is too convoluted. Can't you please be more succinct?
Answer: the auto default property of the autoclicking qpushbutton was set.changing this property solved my issue

Strange autoclicking of qpushbutton


Can we simply change/rearrange the order of navigation?

Question: Can we simply change/rearrange the order of navigation?
My manager asked me to bring the "Jobs" to the top part, instead of "Newsfeed". Because he said according to data analytics, more user is looking for the "Jobs".
Is this the right way? Is it will affect the user experience?
Answer: How much it affects the experience depends on how regularly your users visit the site
New users won't notice, frequent visitors will have to relearn it, but even if your users visit daily, swapping a couple of menu labels isn't going to cause too much confusion. The risk here is low.
If you start renaming items, then yes, that has a much bigger potential for error and confusion, and you should test any changes with representative users before launching.
Comment: Thanks. I agreed with you "How much it affects the experience depends on how regularly your users visit the site"

But in this situation, I was thinking about the Jacob's law - users prefer our site to work the same way as all the other sites they already know - such as Facebook, Linkedin, Quora etc...The news feed is always on top. Now it's at the bottom, is it will bring the bad ux?

Besides that, if we found less user is using the newsfeed, should we focus on how to improve the newsfeed to bring more engagement? instead of rearranging the order?
Answer: Frequent reordering is not useful because of user habits. Data should be read carefully instead of a blind decision. 'Too many people click on Jobs, then let's carry it on top' approach cannot always a good thing. It depends on what you are trying to achieve.
For example, imagine that your website's primary focus is messaging, message button isn't clicked too much. People love learning section of your application, and it's clicking rate is much higher than the message. What will you do? Data says learning section is important, but your company wants to sail with the messaging feature. You probably heard the Henry Foard saying: 'If I had asked people what they wanted, they would have said faster horses.'
So don't make rash decisions, investigate data carefully.
Answer: This is a very simple version of menu optimisation. Basically you have some metrics saying there will be a benefit for users by moving an option further up a menu - this is totally fine and if it is indeed based on solid pre-analysis then there is little to no risk here.
If you have real concerns and want to prove this indefinably you can always A/B test the position of this to see whether moving it up the list is having a positive or negative effect. Further still, you may want to look at new vs repeat visitors to see which is better for each group of users.
Answer: Sclarke is correct. You have metrics and you can make a scientific guess that moving the Jobs nav to the top won't cause too much harm. I can't see the data, but I'm hoping the drop rate isn't high on the Jobs tab.
If more evidence is needed, then I'd suggest to conduct card sorting from your users.


C++: construct by return within constructor

Question: Suppose I have several objects with a C-style constructor:
struct MyStruct { int item1; int item2 };
MyStruct construct_struct(int a, int b, int c, ...);

And I would like, without totally rearranging code copying and pasting duplicate code, to simply define beneath the structures a C++ style constructor:
MyStruct::MyStruct(int a, int b, int c, ...){
    // in pseudo code
    this = construct_struct(a,b,c,...);
}

How can this be done in C++?
Comment: And if `construct_struct` will create an instance of `MyStruct`, then you have infinite recursion there.
Comment: You should not try to set `this` in constructor: it is just a pointer to the object under construction. So the common usage is to call a (possibly private or protected) constructor in the factory function and not the opposite...
Comment: Why not flip it around? Write it such that `construct_struct` can be reduced to `return {a, b, c, ...};` - Then you'll have no code duplication.
Comment: Looks like you need `*this = construct_struct(a,b,c,...);` then.
Comment: You cannot define a member function without declaring it in the class first
Comment: @NathanOliver of course...
Comment: @Someprogrammerdude this is pseudo code.  There should be no infinite recursion, as I will simply be setting data values after calling the default constructor in the function.  Regardless, I already have it working, and the point of the question is to have one instance of the code, and call it within the constructor.  It should be possible.
Comment: @SergeBallesta pseudo code
Comment: @Someprogrammerdude please think a bit more outside the box.  The point is to avoid having to re-organize a ton of code. Merely add code so that the C-style construction works in calling code, and I can add the OO-style construction paradigm without impacting anything.
Answer:
I would like, without totally rearranging code copying and pasting duplicate code, to simply define beneath the structures a C++ style constructor

Rather than copying the code, you should move it into the C++ constructor, and then rewrite your C-style constructor to call the C++ one:
MyStruct::MyStruct(int a, int b, int c, ...){
    // the code from construct_struct(a,b,c,...) goes here
}

MyStruct construct_struct(int a, int b, int c, ...) {
    return MyStruct(a, b, c, ...);
}

This solves the problem with code duplication, and preserves the C constructor.
Comment: @bordeo In terms of implementation, it's the opposite; in terms of maintaining the interface, you get the same thing with cleaner code. You could even make `construct_struct` an inline function (optimizer would probably do for you as well).
Comment: Well, that is the opposite of what I would like to do.
Comment: This is close to the usual approach I've seen in C bindings for C++ class libraries.
Comment: Right, however, the optimization likely applies to the constructor which calls the function and applies it to `*this`.  I don't see any benefit, other than semantics behind the interface.
Comment: @Scheff so right now, we are looking at C++ bindings for a C-style class.
Comment: @bordeo I am not 100% certain that the compiler would apply [copy elision optimization](https://en.cppreference.com/w/cpp/language/copy_elision) to `*this = ...` assignment.
Comment: @Scheff I don't know why you are speaking in terms of specifics and details.  This is a general level question written in pseudo code. The point is to simply add lines of code to achieve desired functionality, rather than move or rearrange lines of code.  This is a clean dev step, as opposed to a dirty, time consuming, and error prone dev step.
Comment: @dasblinkenlight - That's because you can't apply copy elision aggressively to assignment. You must have at least two objects, from and to.
Comment: @dasblinkenlight then I can benchmark and test if this micro optimization achieves any benefit after I get a working state with minimal code changes.
Answer: If you don't want to do what dasblinkenlight suggested (even though you should). The approach in your own answer would also work so long as you object is assignable. For the unlikely case of your object getting a const member, or being made unassignable for another reason, I present this for completeness.
You can delegate to the copy/move constructor:
MyStruct construct_struct(int a, int b, int c, ...){
}

MyStruct::MyStruct(int a, int b, int c, ...) : MyStruct(construct_struct(a,b,c,...)) {}

Comment: @bordeo - And it's not a bad question. Otherwise it would not have attracted so much attention. Plus, at the end of the day, consistency is another aspect of idiomatic coding. Since you follow the idioms in *your* team. Either way, if you got what you needed, and more than one solution was presented, hopefully this post will help more readers in the future, then SO fulfilled its purpose here. So you'll pardon my distraction at not voting sooner.
Comment: @bordeo - Then we have quite a bit in common. If I sounded too zealous I apologize. It's just that notion of tying initializtion and deinitialization to object lifetime is IMO very good. It's a thing C++ got very much correct, since a c'tor or d'tor must be called at lifetime boundary, if you stick to c'tors you won't get half baked objects. That's why I advocate so strongly for it. It's not a hill to die on of course. You raised good points too.
Comment: Great, this is what I was looking for.  If you can present me with a version of this that impacts performance over copying the code into the constructor (I know you can't), then I will agree with you.  In the meantime, having a functional interface in my namespace is worth more to me than depositing my functions in a struct inside the namespace (which is, more or less, a struct with functions as first class citizens).
Comment: @StoryTelier Math, Physics, Computer Science.  Not Object-Oriented.
Comment: @bordeo - Well, they I'll conserve my strength, if you will. I doubt there's convincing any of you.
Comment: @StoryTelier I think it does not serve OO programming to ignore the fact that functions are inherently static and are first class citizens everywhere their inputs can be provided.   OO programming has the effect of locking things into place.  I don't disagree with it; to draw an analogy: if functions are legos, an OO code base is a piece of furniture carved out of a single piece of wood. I also think a bit of kindness on the part of the OO community would go a long way.  OO languages tend to be very oppressive and inflexible communities on here.
Comment: @bordeo - Writing idiomatic code is not about following paradigms. So whatever critique you may have about any OO community, is moot. I'm not up for discussing it. Idiomatic code is about communicating with those who will read your code after you. Those idioms are as important as the idioms in natural languages. Since you and all your collaborators are essentially in agreement about what you like and don't like, it's pointless to try and convince you about idioms in the community of C++ users at large.
Comment: If it makes you feel better, this is a case of me writing a C++ style struct and constructor, next to several C-style structs and constructors.  Rather than trying to rewrite all the C-style structs and constructors right now, I am interested in duplicating the C++ api without changing anything.  This involves fewer changes to code right now.  So I asked the question, and got all this harassment -- which doesn't incline me to respecting the C++ community, or their "way," which has been falling out of favor for years.
Comment: @bordeo - I feel nothing about any side of this argument. So you need not worry about me feeling better. You only got "harassed" because you felt the need to go into a debate with anyone who suggested something you don't approve of. I presented my answer to the benefit of the entire SO community, not just yours. Had you not prodded me about my agreement with dasblinkenlight, none of this later back and forth would have happened.
Comment: In that case, why the personal question? Why the "should"? The normative commentary was out of line. You attempted to scold me, and we both know this is a question of idiom and semantics rather than an objective standard, such as performance.  The upvote you have is from me, by the way.
Comment: @bordeo - The "should" is because more programmers would be able to understand your code if it's following well known idioms. That's an advice I wholeheartedly gave to all future readers of this Q&A. Because Q&A's are here for posterity. Since you prodded, the personal question was to establish how likely this communication benefit would affect your team. Your answer told me it won't, so no point discussing communication benefits, is there? Everything else is just matching the tone you seem intent on setting.
Comment: I accepted your question, and upvoted your response.  In spirit, I agree with placing these constructors in the structs in the final version of code.  However, it isn't a logical next step for me -- remaining consistent is more important at this stage.  This motivates my question.
Comment: Thank you for saying that.  I just see C++ as, in the future, a dominant **multi-paradigm** language.  Also a dominant GPU programming language. But I also see it dying out if this multi-paradigm approach is rejected by the community, or idioms are enforced too strongly (unlike in python, for example).  I say this because I think C# + F#, Java + Scala, Python: these languages will out compete C++ in OO programming; whereas C++ shines in its flexibility.
Comment: That's where my tone came from. I am afraid it will become the next Fortran.
Answer: The simple answer is:
MyStruct construct_struct(int a, int b, int c, ...){
}
MyStruct::MyStruct(int a, int b, int c, ...){
    *this = construct_struct(a,b,c,...);
}

Comment: Refrain if you can. This will involve a copy of the struct or at best a move. @dasblinkenlight's way is more straightforward and *idiomatic*.


Joomla! - Load editor-xtd plugin layout from specified file in button's iframe handler

Question: I'm working on a Joomla! 2.5/3.x editor-xtd button and I have a problem loading a layout from file on button click.
I have tried this method:
$link = 'plugins/editors-xtd/myplugin/myplugin.layout.php?name='.$name;

$button = new JObject;
$button->modal = true;
$button->class = 'btn';
$button->link  = $link;
$button->text  = 'Insert something';
$button->name  = 'myplugin';
$button->options = "{handler: 'iframe', size: {x: 500, y: 300}}";

... but the full generated link in admin looks like http://my.local.host/mywebsite/administrator/plugins/editor-xtd/link-etc.. and it doesn't work. I also have tried including JURI::base in my $link, but the administrator path is still loaded.
I'm new in plugin dev with Joomla! and I have search a lot but no solution found.
** I also tried a link like this index.php?folder=plugins.editors-xtd.myplugin&file=myplugin.layout.php&name=$name but still nothing.
Is there a workout for this or I'll have to create&use a javascript function to run on button click?
Answer: Solution
Modify link variable like this (if application is admin):
$link = '../plugins/editors-xtd/myplugin/myplugin.layout.php?name='.$name;

... and delete button options (this means that file contents will be loaded via ajax inside modal)
Further more, in myplugin.layout.php we can add a little security check and we can import Joomla! framework library and defines so that we can make use of Joomla! framework in our file (things like language load for eg.)
This is my actual header of file:
<?php

// No direct access
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if( ! IS_AJAX) die;

// Include J!Framework for later use
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../../..'));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE.DS.'includes'.DS.'defines.php');
require_once ( JPATH_BASE.DS.'includes'.DS.'framework.php');

//more magic goes here...

Comment: I don't see any benefit in defining `IS_AJAX`. Just write those checks in an `if` expression without creating a constant and die when required.
Answer: Unfortunately there is a bit of a gotcha here in that the JED checker process requires that ALL php files start with defined('_JEXEC') or die; on the very first line of code so if you want to share it on extensions.joomla.org then you are stymied...
Answer: Back on the OP you can detect whether you are in the Admin or Site before generating the link:
    $app = JFactory::getApplication();
    // ...
    if ($app->isAdmin()) {
        $root = '../';  // Joomla expects a relative path, leave site folder "administrator"
    } else {
        $root = '';
    }
    $button->link = $root.'/plugins/editors-xtd/myplugin/myplugin.layout.php?name='.$name;

Also, as you may already know the $button->name  = 'myplugin'; needs to be the name of the icon from the Joomla icomoon set - you can see them here https://ma.tvtmarine.com/en/blog/112-joomla-icomoon-icons-directory
The name needs to be the icon name without the .icon- bit eg:
$button->name  = 'warning-2';
code block doesn't seem to be working properly...sorry about the formatting


resolution not set right on a fresh installation

Question: just intalled ubuntu on the first time!
There is a problem though with the resolution.
i need the resolution to be 1280X980
however ubuntu only lets it set to 1280X720, plus it says my monitor is unknown.
I have installed the latest nvidia 7800 gtx drivers using additional drivers function.
also no luck with messing with the xrandr function on the terminal.
any ideas?
Answer: you can force the adoption of a new resolution using xrandr, however i suggest to use the Nvidia control panel for the display management as first step.
all the required steps are described here https://wiki.ubuntu.com/X/Config/Resolution


VNC Suddenly Stopped Working Ubuntu 18.04

Question: I had VNC working great -- allowing access from both my Mac and my Windows laptop. I set it up from "Sharing" under the System Settings.
This morning nothing will connect.
The only thing that has changed on Ubuntu is that I was working to get the Mosquitto MQTT server running, and as part of that I enabled ufw so I could open port 1883. I was connected via VNC from both of my devices (i.e. Mac and Window 10 laptop) -- in fact I issued the ufw commands from the Windows 10 laptop VCN'd into the Ubuntu computer)
This morning is when nothing is connected or will allow connection. I'm not sure, does ufw need to have a VNC port added if it is running? If so, how do I determine which one to open?
Here is the output from ufw Status:
ufw Screenshot
Comment: Do you mean you had ufw disabled before? What's the output of 'sudo ufw status'?
Comment: There is no need to post terminal output as an image. [edit] your question and paste the text in.
Comment: @fregger: It seems that ufw was disabled by default.
Comment: @fregger I can't post images yet, but I added a screenshot of the ufw status
Comment: Your screenshot tells us that you're blocking all ports except 1883. Assuming VNC uses the default port 5900, you need to open that port with 'sudo ufw allow 5900'. If VNC uses another port, you need to open that one. See also https://askubuntu.com/questions/8402/how-can-i-change-the-default-port-of-remote-desktop-vnc and https://help.ubuntu.com/community/UFW
Answer: VNC uses port 5900 by default.

VNC by default uses TCP port 5900+N, where N is the display number
  (usually :0 for a physical display).
  source

If you block that with ufw (the default) you won't be able to connect.
Comment: I'lll mark this as the correct answer since it was first. But everyone basically nailed it. 'sudo ufw allow 5900' was the answer. Thanks!
Comment: Glad you got it sorted.
Answer: You would be able to find more help on UFW here: Official guide to UFW
Please check out this official guide to have a better understanding of UFW and its commands. If still the issue persists, then I would request you to check your VNC setup once.
I corrupted my VNC configuration once and it took me days to identify it. To reconfigure my VNC setup, I took the help of these two guides:
Install and Configure VNC on Ubuntu 18.04
and, Installing VNC Server on Ubuntu OS
Sometimes, even the Firewall can be responsible for such errors. So, if you observe that the firewall is causing the issue. This guide highlighting Steps to Configure Firewall with UFW is your one-stop solution.
Thank you!
Regards


Programmatically call gesture on ios

Question: I would like to create an application that can call a gesture (swipe, pinch etc) without having to physically do the gesture.
The button would sit next to a webview to allow the gesture to be called inside it.
I have searched for a possible way to do this but cannot find and reference of calling a gesture programatically.
Does anyone have any advice of how this would be possible?
Answer: Try manually calling the selector associated with your gesture in code.
Answer: <code>[[UIApplication sharedApplicationd] sendAction:@selector(action) to:target :from:webview forEvent:touchEventOrNil];</code>
I prefer this for actions to plain performSelector

Programmatically call gesture on ios


Detecting if windows service is already installed using puppet exec

Question: I have below exec resource which is used to install a window service.
I want to it to execute only if the window service is not installed. So I use the onlyif command but the command is not working. It is running the install all the time:
exec { "install-${target_path}/${binary_name}":
    command   => "${installUtil_filepath} /i /servicename=\"${service_name}\" /displayname=\"${display_name}\" /description=\"${description}\" \"${target_path}\\${binary_name}\"",
    onlyif    => "if((Get-Service \"${service_name}\" -ErrorAction SilentContinue).DisplayName -eq  ${display_name}) { exit 1 } else { exit 0 }",
    logoutput => true,
    provider => powershell,
  }

This worked
if(Get-Service \"${service_name}\") { exit 1 } else { exit 0 }

Answer: Why are you first retrive the service using the service name and then also compare the display name? You can probably omit that check...
Also, don't you want to exit with exit 0 when the service is installed and otherwise with 1?
Try this:
onlyif    => "if(Get-Service ${service_name}) { exit 0 } else { exit 1 }",

Comment: Thanks this worked. if(Get-Service \"${service_name}\") { exit 1 } else { exit 0 }


MySQL Query - Include dates without records

Question: I have a report that displays a graph. The X axis uses the date from the below query. Where the query returns no date, I am getting gaps and would prefer to return a value. Is there any way to force a date where there are no records?
SELECT
    DATE(instime),
    CASE
        WHEN direction = 1 AND duration > 0 THEN 'Incoming'
        WHEN direction = 2 THEN 'Outgoing'
        WHEN direction = 1 AND duration = 0 THEN 'Missed'
    END AS type,
    COUNT(*)
FROM taxticketitem
GROUP BY
    DATE(instime),
    CASE
        WHEN direction = 1 AND duration > 0 THEN 'Incoming'
        WHEN direction = 2 THEN 'Outgoing'
        WHEN direction = 1 AND duration = 0 THEN 'Missed'
    END
ORDER BY DATE(instime)

Comment: What do you mean by saying "make dates with no records?"
Comment: Do you mean that `instime` is NULL in your database (in which case look up `ISNULL` or `COALESCE`, or do you mean there are some days for there are no records in your database? If that's the case, go with the answer @SalmanA suggests below.
Comment: you can set the default for your date column to be now() or current_date
Comment: So for example, there could be no records available for Sunday. So on a chart from data running from Friday to today (Tuesday), the chart would graph data on Friday, Saturday, Monday and Tuesday. Leaving out Sunday completely. If there was some way of forcing a zero for Sunday or any missing dates, it would make the graphing more clear when viewed by users.
Answer: One possible way is to create a table of dates and LEFT JOIN your table with them. The table could look something like this:
CREATE TABLE `datelist` (
 `date` DATE NOT NULL,
 PRIMARY KEY (`date`)
);

and filled with all dates between, say Jan-01-2000 through Dec-31-2050 (here is my Date Generator script).
Next, write your query like this:
SELECT datelist.date, COUNT(taxticketitem.id) AS c
FROM datelist
LEFT JOIN taxticketitem ON datelist.date = DATE(taxticketitem.instime)
WHERE datelist.date BETWEEN `2012-01-01` AND `2012-12-31`
GROUP BY datelist.date
ORDER BY datelist.date

LEFT JOIN and counting not null values from right table's ensures that the count is correct (0 if no row exists for a given date).
Answer: You would need to have a set of dates to LEFT JOIN your table to it. Unfortunately, MySQL lacks a way to generate it on the fly.
You would need to prepare a table with, say, 100000 consecutive integers from 0 to 99999 (or how long you think your maximum report range would be):
CREATE TABLE series (number INT NOT NULL PRIMARY KEY);

and use it like this:
SELECT  DATE(instime) AS r_date, CASE ... END AS type, COUNT(instime)
FROM    series s
LEFT JOIN
        taxticketitems ti
ON      ti.instime >= '2013-01-01' + INTERVAL number DAY
        AND ti.instime < '2013-01-01' + INTERVAL number + 1 DAY
WHERE   s.number <= DATEDIFF('2013-02-01', '2013-01-01')
GROUP BY
        r_date, type

Answer: Had to do something similar before.
You need to have a subselect to generate a range of dates. All the dates you want. Easiest with a start date added to a number:-
SELECT DATE_ADD(SomeStartDate, INTERVAL (a.I + b.1 * 10) DAY)
FROM integers a, integers b

Given a table called integers with a single column called i with 10 rows containing 0 to 9 that SQL will give you a range of 100 days starting at SomeStartDate
You can then left join your actual data against that to get the full range.


How can I change the style to an HTML element that doesn't have ID using javascript function

Question: I know what I want but forgive me because I can barely figure out how to ask it in a concise way. I have done quite a bit of searching for an answer. None of the suggested "duplicates" apply as far as I can see.
Goal:
To change background-color of div based on the dance's style using javascript function. Page loads, any dance style's background-color is set based on style.
My Razor Page loops thru and lists dance events. (other columns have been removed to allow focus on the problem.)
@foreach (var item in Model.Dances)
{

 @Html.DisplayFor(modelItem => item.DanceStyle)

}

Because there are many dynamic rows, the div element does not contain an ID. Hence, I cannot call a javascript function sending the Dance's style and use GetElementByID to set the back color of the DIV.
Below is just a rough attempt for what I thought might work.

 DanceStyle

function fColorDIV(this)
{
        switch(this)
        {
            case "Waltz":
                dancestyleBGcolor = "PapayaWhip"
                break;
            case "WCS":
                dancestyleBGcolor = "LightSalmon"
                break;
            case "Zydeco/Cajun":
                dancestyleBGcolor = "Yellow"
                break;

            default:
                dancestyleBGcolor = "LightGray"
         }
    return dancestyleBGcolor;

}

I doubt onload even works when DIV is being written to page. Adding an ID would not work because all rows would have the same ID in their DIV.
Comment: Why not add a class according to the content to the divs when creating them at back-end?
Comment: class means class attribute to the div. Why do you think it will overkill. It is just to differentiate what div is what.
Comment: When exactly do you want to change the bg-color?
Comment: If I've understood your code correctly, you could use `item.DanceStyle` as a classname. Only that there seems to be some nasty characters, modify the name so that it contains only four - five first characters to avoid escaping ..?
Comment: @JustJohn This might help: https://stackoverflow.com/questions/13123067/how-to-add-a-class-to-html-element-dynamically-using-razor-syntax The example uses tr element, you have div
Comment: Well, the plan was anytime before the page is viewed, hence client side javascript. I can't envision doing it on the C# code behind OnGet. But. . . . I am all ears
Comment: Hi CodeThing,
I think your example that uses the tr element and the ternary operator might work. There are tons of styles/colors, but I think the missing link was how to reference the class function using the ternary operator. @Teemu, I think I understand what you are saying.  I will try this and get back to you guys.
Comment: I guess I will add my own answer if no one complains. I'm not sure how to give you guys credit.
Answer: @CodeThing helped me by pointing me to
How to add a class to html element dynamically using razor syntax?
I made the assumption from the example using class attribute that it would work for style and/or any HTML attribute was correct.
I currently got it working on style attribute by calling function in class (thank you @Temu) and setting style attribute for DIV plus a couple other things like border radius and text-align.

 @Html.DisplayFor(modelItem => item.DanceStyle)

And here is the function I call in a class I have:
 public static string AddStyleColor(string thisStyle)
        {
            string dancestyleBGcolor = "";
            switch (thisStyle)
            {
                case "All Styles":
                    dancestyleBGcolor = "White";
                    break;
                case "Balkan":
                    dancestyleBGcolor = "Bisque";
                    break;
                case "Ballroom":
                    dancestyleBGcolor = "#6699FF";
                    break;
                case "Bhangra":
                    dancestyleBGcolor = "#9900CC";
                    break;
                case "Blues":
                    dancestyleBGcolor = "AliceBlue";
                    break;
                case "Contra":
                    dancestyleBGcolor = "Wheat";
                    break;
                case "Country":
                    dancestyleBGcolor = "BurlyWood";
                    break;
                case "English Country":
                    dancestyleBGcolor = "GreenYellow";
                    break;
                case "Ecstatic":
                    dancestyleBGcolor = "Lime";
                    break;
                case "Folk Also":
                    dancestyleBGcolor = "Black";
                    break;
                case "Irish":
                    dancestyleBGcolor = "SpringGreen";
                    break;
                case "Israeli":
                    dancestyleBGcolor = "LightCoral";
                    break;
                case "Misc/Variety":
                    dancestyleBGcolor = "Honeydew";
                    break;
                case "Polka":
                    dancestyleBGcolor = "PeachPuff";
                    break;
                case "Salsa":
                    dancestyleBGcolor = "PowderBlue";
                    break;
                case "Scottish":
                    dancestyleBGcolor = "MistyRose";
                    break;
                case "Scandinavian":
                    dancestyleBGcolor = "White";
                    break;
                case "Square":
                    dancestyleBGcolor = "#993333";
                    break;
                case "Square(neo)":
                    dancestyleBGcolor = "Aquamarine";
                    break;
                case "Swing/Lindy":
                    dancestyleBGcolor = "LightSkyBlue";
                    break;
                case "Tango":
                    dancestyleBGcolor = "Thistle";
                    break;
                case "Waltz":
                    dancestyleBGcolor = "PapayaWhip";
                    break;
                case "WCS":
                    dancestyleBGcolor = "LightSalmon";
                    break;
                case "Zydeco/Cajun":
                    dancestyleBGcolor = "Yellow";
                    break;

                default:

                    dancestyleBGcolor = "LightGray";
                    break;

          }

            return dancestyleBGcolor;
        }


Solving the 1D Heat Equation on [a,b] rather than [0,L]

Question: Solve the 1D Heat Equation on $x \in [a,b]$
$$ \frac{\partial ^2 T}{\partial x^2} = \frac{1}{\alpha} \frac{\partial T}{\partial t}$$
$$ T(a,t) = T(b,t) = 0,        T(x,0) = T_0(x) $$
Now, I know that we should actually just be able to consider the solution for $T(x-a,t)$, basically making the problem the standard 1D heat equation with homogeneous boundaries on $[0,L]$ rather than $[a,b]$, but I was just playing around with the $[a,b]$ case, and arrived at something which I can't figure out what is wrong with it.
Separating Variables
Separating variables as $T(x,t)=X(x)\Gamma(t)$ gives the standard equations:
$$X''+ \lambda_n ^2 X = 0$$
$$\Gamma' + \alpha \lambda_n ^2 \Gamma = 0$$
Where I am using the "prime" notation loosely even though they represent derivatives with respect to two different variables.
Solving these of course gives:
$$ X(x) = C_1 \cos(\lambda_n x) + C_2 \sin( \lambda_n x) $$
$$ \Gamma(t) = C_3 e^{-\alpha \lambda_n ^2 t} $$
Possible Mistake
Here is where I feel I am making a mistake. I apply the boundary conditions getting:
$$ T(a,t)=X(a)\Gamma(t)=0 \Rightarrow X(a)=0 $$
Same thing for B getting $X(b) = 0$
Then applying the conditions to the solution:
$$0=C_1 \cos(\lambda_n a) + C_2 \sin( \lambda_n a) $$
$$0=C_1 \cos(\lambda_n b) + C_2 \sin( \lambda_n b) $$
If we solve for $ C_1 = - C_2 \tan(\lambda_n a) $, then we can plug back into the bottom equation and get:
$$ 0 = -C_2 \tan(\lambda_n a) \cos(\lambda_n b) + C_2 \sin(\lambda_n b) $$
Giving the eigenvalues after some manipulation and $C_2$ dividing out as:
$$ \tan(\lambda_n a) = \tan(\lambda_n b) $$
Finally, with $C_2$ and $C_3$ being absorbed to a single constant $C_n$, ignoring the $\lambda_0=0$ trivial eigenvalue, and plugging in the above expression for $C_1$ in terms of $C_2$ into the general solution we have:
$$ T(x,t) = \sum_{n=1}^\infty C_n (\sin(\lambda_n x) - \tan(\lambda_n a)\cos(\lambda_n x)) e^{-\alpha \lambda_n^2 t} $$
Now here, I tried to use the solution to the $x$ equation to get the constant $C_n$ using orthogonality like one would normally do. The Sturm-Liouville problem has the standard inner product as well. The only thing that should be different is the bounds.
$$ <f,g> = \int_{a}^b f(x)g(x)dx $$
The orthogonal set of functions for the Sturm-Liouville problem should be $\sin(\lambda_n x) -\tan(\lambda_n a)\cos(\lambda_n x)$ right? Because I try carrying out the integral:
$$ \int_{a}^b (\sin(\lambda_n x) -\tan(\lambda_n a)\cos(\lambda_n x))(\sin(\lambda_m x) -\tan(\lambda_m a)\cos(\lambda_m x)) dx $$
But, this does not give me identically $0$ for $n \neq m$. I tried doing the integration out on paper (messy but doable), and nothing stuck out as making this $0$ for different eigenvalues. I even checked on Desmos by numerically calculating some eigenvalues for a given $a$ and $b$ and then numerically integrating. Even to three decimal places, the precision error cannot account for how far these values were from $0$. So my main question is, where is my mistake? Is it...

This actually is not a valid Sturm-Liouville problem in this form for some reason, thus the functions are not orthogonal?

I'm using the wrong functions for orthogonality, or I have made an algebra error somewhere?

The inner product is actually $0$ and I made a mistake in the calculation?

I can't see why this is not a valid Sturm-Liouville problem, so the functions should be orthogonal. And if it isn't why? Any help is greatly appreciated. Thank you!
Comment: When doing such stuff I usually take a small python program, truncate the series and check my formulas numerically. To me this is far less arduous than agonizing over formulas with pencil and paper.
Comment: Did you determine what values $\lambda_n$ can take?  You should find that integral is zero, assuming that $\lambda_n$ and $\lambda_m$ are indeed eigenvalues.
Comment: @messenger I used a graphing calculator to calculate the first few eigenvalues for select values of a and b to three decimal places. I then plugged them into the integral and numerically calculated it and did not get anywhere close to 0. By "values they can take," do you mean just solutions to that tangent transcendental equation? Or is there some other restriction I am missing? I am neglecting negative values and 0.
Comment: @Gonçalo Thanks this is interesting. But this actually is just a last-minute rerouting to the solution which one would get using $T(x-a,t)$. I am more interested in where my mistake is in doing it this long way and why it is that this inner product doesn't seem to show these two functions are orthogonal when they should in fact be.
Comment: Maybe start by looking at your numerical values of $\lambda$.  Are they they the same as the $n\pi/(b-a)$ (for whatever values of $a$ and $b$ you've used)?  If not, that's where your error is.  If they are, then the error is in your evaluation of the integral.
Answer: It's not hard to see that the solutions of $X''(x)+\lambda X(x)=0$ subject to $X(a)=X(b)=0$ are
$$
              X_n(x)=\sin\left(\frac{x-a}{b-a}n\pi\right),  n=1,2,3,\cdots.
$$The corresponding values of $\lambda$ are
$$
           \lambda_n = \frac{n^2\pi^2}{(b-a)^2}, n=1,2,3,\cdots.
$$
And the corresponding solutions $\Gamma$ are
$$
                \Gamma_n(t)=\exp\left(-\alpha\frac{n^2\pi^2}{(b-a)^2}t\right).
$$
You have not simplified your solutons enough to make the orthogonality conditions easy to see.


Symfony2 - Redirect from non-www to www

Question: I need to redirect my symfony website from "abc.com" to "www.abc.com". I have tried some solutions in stack overflow but they add multiple "www." to the address and others didn't work.
Here is my htaccess source.
DirectoryIndex app.php

<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /app.php/
    </IfModule>
</IfModule>

How can I do this?
Comment: Possible duplicate of [htcaccess and symfony 2 redirect non www -> www](https://stackoverflow.com/questions/27398989/htcaccess-and-symfony-2-redirect-non-www-www)
Answer: Add the following rule as the first rule:
RewriteCond %{HTTP_HOST} !^(www)\.
RewriteRule ^(.*?)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Symfony2 - Redirect from non-www to www


My API is returning undefined instead of response value

Question: I'm consuming an API using Axios in React, but when i come to set the response in a State so I may use the data, it is undefined. The funny thing is, if I put console.log inside Get.js I see the array perfectly. Am I returning the value the wrong way ?
PS: When I use console.log inside the Get.js,inside the 2nd .then, it prints two times the array. Why ?
MainPage.jsx
import { useEffect, useState } from 'react';
import { axiosGet } from '../../services/Get';
import { Header } from '../../components/Header/';
import { Welcome } from '../../components/Welcome/';

export const MainPage = () => {
  const [data, setData] = useState([]);
  useEffect(() => {
    console.log(axiosGet());
    setData(axiosGet());
  }, []);

  return (
    <>

      <Welcome />
      {data.length &&
        data.map(obj => {

obj.name
;
    })}
    </>
  );

Get.js
import axios from 'axios';

export function axiosGet() {
  axios
    .get(
      `https://api.rawg.io/api/games?key=a6a08e14b07f41d09e846ec3c01e5db0&dates=2019-10-10,2022-03-01&page=2`
    )
    .then(res => {
      return res.data.results;
    })
    .then(arr => {
      return arr;
    })
    .catch(err => {
      console.error('oops! error: ' + err);
    });
}

if I change the Get.js code at this piece of code:
.then(res => {
          return res.data.results;
        })
        .then(arr => {
          console.log(arr)
          return arr;
        })

I got this:
Array(20) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]

0: Object { slug: "forza-horizon-5", name: "Forza Horizon 5", playtime: 11, … }

1: Object { slug: "call-of-duty-modern-warfare", name: "Call of Duty: Modern Warfare (2019)", playtime: 0, … }

2: Object { slug: "resident-evil-village", name: "Resident Evil: Village", playtime: 16, … }

3: Object { slug: "assassins-creed-valhalla", name: "Assassin's Creed Valhalla", playtime: 0, … }

4: Object { slug: "genshin-impact", name: "Genshin Impact", playtime: 0, … }

5: Object { slug: "mafia", name: "Mafia: Definitive Edition", playtime: 9, … }

6: Object { slug: "superhot-mind-control-delete", name: "SUPERHOT: MIND CONTROL DELETE", playtime: 2, … }

7: Object { slug: "valheim", name: "Valheim", playtime: 11, … }

8: Object { slug: "it-takes-two-2", name: "It Takes Two", playtime: 11, … }

9: Object { slug: "deep-rock-galactic", name: "Deep Rock Galactic", playtime: 6, … }

10: Object { slug: "risk-of-rain-2", name: "Risk of Rain 2", playtime: 7, … }

11: Object { slug: "tell-me-why", name: "Tell Me Why", playtime: 2, … }

12: Object { slug: "factorio", name: "Factorio", playtime: 17, … }

13: Object { slug: "ghostrunner", name: "Ghostrunner", playtime: 4, … }

14: Object { slug: "marvels-avengers", name: "Marvel's Avengers", playtime: 14, … }

15: Object { slug: "mafia-iii-definitive-edition", name: "Mafia III: Definitive Edition", playtime: 0, … }

16: Object { slug: "guardians-of-the-galaxy", name: "Marvel's Guardians of the Galaxy", playtime: 8, … }

17: Object { slug: "need-for-speed-heat", name: "Need for Speed Heat", playtime: 3, … }

18: Object { slug: "marvels-spider-man-miles-morales", name: "Marvel's Spider-Man: Miles Morales", playtime: 0, … }

19: Object { slug: "streets-of-rage-4", name: "Streets of Rage 4", playtime: 4, … }

length: 20

<prototype>: Array []
Get.js:12:15

Comment: does not your `useEffect` keeps running that seems to be the issue to me, wrap it with empty array ...cause you need to load data one time
`useEffect(()=> your get call, [])`
Comment: Also, you are doing data.map while data may not even be there so better to check `data.length && data.map`
Comment: `Uncaught TypeError: data is undefined`, I did the two changes you suggest.
Comment: your useEffect useEffect(() => {
    console.log(axiosGet());
    setData(axiosGet());
  });
your map function  {data.length && data.map(obj => obj.name;)}
your map is incorrect :)
Comment: can you provide console.log of your get call please ?
probably it is nested inside another prop or something hence giving you undefined
Comment: you don't need obj = ... just `{data.map(obj => {obj.name})}`
Comment: I edited my question Anuj, take a look
Comment: please change your map too
Comment: it's done Anuj.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244408/discussion-between-anuj-and-maiky).
Answer: The function axios.get() returns a Promise of the data you want.
You need to modify your code to return this promise to the calling function:
export function axiosGet() {
  return axios
   .get(
      `https://api.rawg.io/api/games?key=a6a08e14b07f41d09e846ec3c01e5db0&dates=2019-10-10,2022-03-01&page=2`
    )

And then you need to await for an answer (to go from a Promise to the data):
useEffect(async () => {
  console.log(await axiosGet());
  setData(await axiosGet());
}, []);

Answer: The problem is that axiosGet doesn't actually return anything.
You can't though get it to directly return the API data, since that is only retrieved asynchronously. See this question for lots of discussion as to how to get the response from asynchronous requests and use it in your code.
In your case probably the easiest solution is to have axiosGet return the promise that axios.get (and your subsequent .then calls from it) gives you, and then await that in your useEffect so that you can set the state in your component to it.
So I would make the following changes:
First  add the return statement to axiosGet:
export function axiosGet() {
  return axios
    .get(
      `https://api.rawg.io/api/games?key=a6a08e14b07f41d09e846ec3c01e5db0&dates=2019-10-10,2022-03-01&page=2`
    )
    .then(res => {
      return res.data.results;
    })
    .then(arr => {
      return arr;
    })
    .catch(err => {
      console.error('oops! error: ' + err);
    });
}

and adjust the useEffect in your component as follows:
useEffect(async () => {
  const apiData = await axiosGet();
  setData(apiData);
}, []);

Comment: Thank you Robin. I got my problem fixed and everything is fine now.


How to wire a NEMA 6-50 receptacle to a 240V GFCI breaker?

Question: When wiring a 240V GFCI breaker to an NEMA 6-50 receptacle, does one leave the neutral terminal on the breaker open and run the ground wire from the receptacle to the panel ground bus-bar?  Does the ground need to be #6 if the hots are #6, or can it be smaller?
Answer: The GFCI breaker will have a neutral pigtail, or PON.  It needs that to power the breaker's internal electronics, but it also carries load neutral on a 120/240V circuit.
If you have a 240V-only circuit, then you have no neutral and you connect the nonexistent neutral to nothing. The 2 hots wires attach to the GFCI hots.
For a circuit of up to 60A, ground can be #10.
For a 61-100A circuit, ground must be #8.
If you are using 6 AWG copper wire or type other than NM or UF, that is 65A wire and needs a #8 ground.


MongoDB search with CakePHP and multiple $all

Question: Let's say I have a simple database and I'm trying to find all users who speak both English and Spanish and/or English and French (but not Spanish and French). I have a users table with a handful of records set up like this:
{
    "username": "jdoe",
    "languages": ["english", "spanish", "french"]
}

I get the expected results when I search like this:
db.find({ "languages" : { $all:['english', 'spanish'], $all:['english', 'french'] } })

But I'm not sure how to do it with Cake. I can match a single language pair like so:
$this->User->find('all', array('conditions' => 'User.languages' => array('$all' => array('english', 'spanish'))));

But I'm stuck on how to search for multiple pairs; an array of arrays doesn't seem to do it.
This is a project someone else started, so I'm not particularly familiar with the nuances of CakePHP or MongoDB; I have a feeling I'm overlooking something obvious. Any ideas?
Answer: Your shell query example may have returned the expected results for your test data, but it's technically incorrect since you're clobbering the $all property in the query object. Using the top-level $or operator, the correct query would be:
db.users.find({"$or": [
    {"languages": {"$all": ["english", "spanish"]}},
    {"languages": {"$all": ["english", "french"]}}
]});

This translates to CakePHP as:
$results = $this->User->find('all', array('conditions' => array(
    '$or' => array(
        array('User.languages' => array('$all' => array('english', 'spanish'))),
        array('User.languages' => array('$all' => array('english', 'french'))),
    ),
)));

I tested this using the following fixture data (sans _id's) in a CakePHP app:
{ "username" : "john", "languages" : [ "english", "spanish", "french" ] }
{ "username" : "mike", "languages" : [ "spanish", "french" ] }
{ "username" : "bill", "languages" : [ "english" ] }
{ "username" : "fred", "languages" : [ "english", "french" ] }
{ "username" : "luke", "languages" : [ "english", "spanish" ] }

John, Fred and Luke are returned.


App page for an Chrome extension

Question: I am writing an extension for chrome (reminder extension), I want to list all the reminders added by the user in a separate tab. How do I do it?
Currently, I have designed the popup form.
Do I need to write an app instead of extension?
Answer: You can open a tab with an HTML file you pack with your extension, using the Chrome API:
chrome.tabs.create({
  url: chrome.runtime.getURL("mypage.html")
});

That page can use all Chrome APIs your extension can use. Note that "tabs" permission is not required for tabs.create
See tabs documentation for more details.
P.S. If you want a more app-like experience, you can create a popup-type window:
chrome.windows.create({
  url: chrome.runtime.getURL("mypage.html"),
  type: "popup"
});

App page for an Chrome extension


One transfer switch, two main panels

Question: Can a single manual transfer switch be wired to two main panels (both from same meter but they do not feed each other)? Specifically, if desired breakers cannot be consolidated into one panel and there is only going to be one 10-circuit transfer switch -- can new #12 wires be added/spliced into the existing black, red, white and ground wires coming out of transfer switch harness to extend their length so that some of them run to the second panel? Particularly, is it ok to have the neutral and ground wires from the single transfer switch be spliced so that they attach to the neutral/ground bars in both panels?
Comment: **Send it back**. Don't use those 6/8/10 switch "transfer switches".  I mean generally, but *particularly, not for you*, since your requirements vastly exceed its capabilities.
Comment: also asked [here](https://www.diychatroom.com/threads/one-transfer-switch-and-two-panels.706166/).
Comment: Can you tell us more about the actual loads you want to provide backup power to, and why they're split across the two panels?
Comment: @ThreePhaseEel On that other forum, there's a good photo of the panels.  The loads were just put bric-a-brac in either panel more or less evenly. Large loads are not grouped into one panel, and there are no conduit passages between panels.
Answer: OK, so a) you have 400A class service, or some other good reason to have dual main panels with dual main breakers.  And, you are ready to install a fairly large electrical box right next to them. And c) you are OK routing wires or cables from both main panels to this new third box.  Those are all the ingredients we need to succeed.
But send it back. It's the wrong thing.
And way overpriced and very limiting, compared to what we're about to do.
Honestly, it's usually the wrong thing, because the inherent design of those boxes was a 1970s-tier "hack". Generator salesmen love 'em because they feel like they're sending you home with something "that'll work on any panel" - but they are thinking of obsolescent panels like Zinsco or Pushmatic, where there is simply not an option for a proper full-panel interlock.
Today, the problem is this old hack doesn't play well with modern panels, like your dual panels, AFCI, GFCI, power monitoring, or any of the neat stuff Leviton is doing with their smart panels.  In fact they cannot provide AFCI protection and don't provide GFCI either (unless the generator does, but who wants the entire house tripping out)? If AFCI/GFCI is mandatory, it's mandatory in generator mode too.
Either of the methods below will take care for those problems, and happen for around $100 give or take - certainly not $500.
Option 1: Get a full-panel interlock for one panel ($60-100)
based on your photo on DIYchatroom, you'd need to retrofit main breakers ($100) into these panels to implement this option. However, this would be the easiest thing to do, and these quite-new panels definitely have interlocks available for them.
Normally, when you have dual main panels, it's because of 300+ amp service that is simply too big to economically do on one panel.  That is fine as long as the panels are next to each other. (main disconnects must all be in one place).
However, the usual way to set up dual panels is to put your BIG loads (on-demand water heater, or the #1 application, heat pump emergency heat) into one of the panels -- and all your normal residential loads (receps, lights, etc.) in the other panel.  Typically these loads are far too big to ever be able to power from a generator, it doesn't make sense to do that.  So you "write off" the big-load panel.
So that makes generator layout very simple: you only need to support one panel.  Put the usual whole-panel generator interlock into that panel, and you're all set.
If your loads are scattered all over both panels, my advice is to correct that.  If it's possible to simply re-route the Romex cable, that's great.  However, if not, you can use the "old" panel as a splice box, and carry over hot and neutral to the new panel. You must bring over both the hot and the neutral as a pair. You cannot leave neutral in the old panel; it MUST come over to the new panel.  However, you can leave safety ground in the old panel.   Neutral is not ground.
If you need to do several circuits, the best way to do this is with one or several conduit runs between the panels. It's possible to install acceptable conduits without removing a panel from the wall.
Option 2: New subpanel with generator interlock. ($90-120)
Like we say around here, "Think BIG" about panel size.  A modest 24-space panel will switch 20 AFCI circuits or 40 plain ones between utility and generator. The problem, as you know, is you don't use many loads at once but they are scattered on many circuits. By using a whole panel as an interlock, you can support a large number of circuits.
We recommend spending a few lattés on a size bump to 30 or even 40 spaces.  Nobody ever came on here saying "I want to add a circuit but I left myself plenty of spaces, what do I do?"  But the line is around the block of people who chintzed out on panel size and regret it.
You get a panel either with a main breaker and factory-made generator interlock kit, main-lug/no-lug and you fit two 2-pole breakers with an interlock between them.  These are are back-fed, one by utility and one from the generator inlet (which can be anywhere you please; in-wall UF cable is cheaper than heavy generator cord and a darn sight more convenient.)
At that point, you move any circuits you want on generator out of your regular panel into the new panel - as said above, using conduit if able, and both hot and neutral wires must come over together.
If any of the "to be brought over" circuits are on AFCI or GFCI breakers, take close note of the make of the breakers.  Choose your gen subpanel so the existing breakers are legal in it (generally, don't cross brands; they will seem to fit but will burn up the bus bars).  That way you can just move your valuable breakers to the new panel and save $40-60 each.
On regular breakers I'm not so worried, they're typically $5-ish.
Yeah, but you really, really want to save that panel
--Why?  They ripped you off. And it won't even function with your AFCI breakers, and problems like that will just keep biting you: it'll be the path of pain. Don't fall victim to inertia or "the fallacy of sunk costs" Even if you can't return it, unused/complete transfer switches sell pretty well on eBay/Craigslist. It will fetch a fair bit more than the above solutions cost: you'll be cash ahead!
But OK.
The transfer switch can only serve circuits in one panel.   Reliance tech support can't "waive" this requirement; it's in NEC 110.3(B).  When UL approves equipment like this, they also approve the instructions and labeling. UL only approved the device for uses according to the instructions and labeling; they didn't even test it otherwise. The companion law is 110.3(B) which says you must obey those (approved) instructions and labeling.  The switch is only approved to support 1 panel, and that's the end of the discussion.
So, you need to choose 1 panel, and move circuits from the other panel to it.  That is a straightforward matter, and I discuss it at length in option 1.
It's OK to have wire-nut splices inside a service panel, and it's OK to use a panel as a splice box for unrelated circuits. So you can lift a circuit off its breaker and neutral, and extend its hot(s) and neutral together to the other panel.
In the other panel, the neutral lands on that neutral bar, and the hot(s) go to their new breaker there.   Yes, it matters to move the neutral wire.  That's what all this is about.
The hot(s) and neutral for a given circuit must be in the same cable (back to 300.3 again).
With cables, I would just run them the 3 inches straight across, I wouldn't bother going out the top or bottom.
When I have panels side by side (and I do), I like to include conduit "tunnels" between the 2 panels; several of them in fact.  However, the hot(s) and neutral for any given circuit must go through the same tunnel.    If a cable has enough wire length to make it through a conduit tunnel to the other panel, go for it.
Comment: @JoelKranz Whoever said that doesn't even understand 300.3.  Look, they're giving you arm-waving gibberish and the person on the phone has a child's understanding of current flows but no understanding of AC power or Code.  I'm giving you hard facts.  You have to decide who you want to believe.  In other words, it's a lot like the choice Americans had to make on November 3 :)
Comment: I realize that "this thing is unfit for this application" is *the last thing* you want to hear at this stage in the project, and I'm sure procurement of this unit was a long road, and you fear getting the right stuff will take even longer.  Not so much. The subpanel you need is sitting in stock at your local big-box, the only "rare" thing will be the interlock.  Or if you go option 1, the Siemens(?) dealer probably has all that kit in stock, you can have it tomorrow.
Comment: Thank you.  If the panels are side by side and all the circuits I want are in one except two -- can I just use the other panel as a large junction box to extend the wires for those two circuits through a knockout and conduit to the first panel?
Comment: @JoelKranz, Electrical Engineer here just chiming in to say that Harper is right on this, regardless of what Reliance said.  If you install it according to their phone advice (which is NOT the same thing as their UL-Listed instructions, which must be followed), an inspector can flag it and make you re-do it right.  I'm sure Reliance has good EEs on staff, but the person you talked to was not one of them.
Comment: The whole point of 300.3 is that current must return in the same cable or conduit it leaves in.  Why?  Because otherwise you're forming a loop of wire, with steel (conduit, nails, panel housings) in the middle -- and coils of wire around steel cores are how we make things like electromagnets and transformers.  So while it would appear to work, you'd constantly be losing power heating and magnetizing your conduits a bit.  If it gets bad enough, that could start a fire, which is why code prohibits it.
Comment: Agreed with Harper about getting a third opinion too -- and this third opinion should ideally come from your local electrical inspector's office.  Their job is to make sure everything is safe so that houses in their jurisdiction don't burn down, not to sell transfer switches, so they'll be less biased and totally familiar with Code and electrical safety.
Comment: And to your other question, yes, wire-nut splices and pass-throughs are allowed in service panels.  So yeah,  a circuit in panel B can have its hot(s)+neutral spliced and  brought over to panel A.  Safety ground can stay in panel B.  Anytime panels are put up side by side like that, it's best to add a few "conduit tunnels" between them for just this sort of eventuality.
Comment: Thanks -- I did just get off the phone with Reliance about this and they say that since there is a neutral wire coming into the panel on left (closest to transfer switch) it is ok to run only red/black wires to panel at right to power a few breakers and have the neutral/ground wires from transfer switch harness only attached in left panel.
Comment: @JoelKranz Holy Cow, that's a blatant 300.3 violation, and they know it, or reasonably ought to.  Their tech support is terrible, or is blatantly lying to get you far enough into installation that you can't return it.   Go look up 300.3, it says all related wires must be in the same cable or conduit.  The purpose is to so that currents are equal and opposite in all wires, so EMFs cancel each other out.  Yeah, you just can't do that. Wow.
Comment: Further, this is what I received from Reliance in response to 300.3:  "The Transfer Switch is only switching each individual circuit it does not switch the entire panel power source. The neutral is coming from your utility service but shared between both panels.
 The transfer switch power have no bearing on the utility power or the neutral.  The neutral is only a return path to the generator.  If the concern is Imbalance, then you should switched off you mains, Power always returns to it's source."

One transfer switch, two main panels


Can this double picker be achieved by a web app (not a native app)?

Question:
Can this double picker be achieved by a web app in HTML (not a native app)?
Comment: The simple answer is that from a UI POV, nearly any native interaction can be emulated in a web app via JS, CSS and HTML. The more complex answer is to ask the question "when is it more appropriate to invest in emulating a native app vs. embracing the fact that it's a web app?" The answer to that will vary.
Answer: Yes it can.
Take a look at Sencha Touch.  The example below is from my iPhone in Safari (HTML5 app).
Comment: Thanks John! It seems not built into jQuery mobile, even the mobiscroll.com plugin does not provide a double picker :(
Comment: We tried jQuery mobile for a while but ended up switching to Sencha.  I wish we did it 6 months ago.  It's not perfect, but makes dev work much simpler.
Comment: jQuery mobile is mean to be a universal UI layer regardless of platform. Sencha tends to borrow more directly from iOS in emulating the controls.
Comment: IMHO, Sencha is perfect if the team is fairly happy with the stuff out-of-the-box (it is fairly robust). jQuery is preferred if there's going to be a lot of roll-your-own solutions. I always prefer the out-of-the-box option from a dev standpoint but realize that from a UX POV, more often than not, there's a lot of rolling-your-own.


How to connect sqlite in xamarin

Question: I am trying to connect to the DB(SQlite) but I keep on getting an error.

System.TypeLoadException: 'Could not resolve type with token 01000150 from typeref (expected class 'SQLite.CreateTableResult' in assembly 'SQLite-net, Version=1.7.335.0, Culture=neutral, PublicKeyToken=null')'

And my code to connect is:
this.db = new SQLiteAsyncConnection(dbPath, storeDateTimeAsTicks: true);
this.db.CreateTableAsync<User>().Wait();

Any suggestion how can I fix this issue?
Answer: It is diferent for us to reproduce this problem only based on the error log you posted, but you can refer to official document Xamarin.Forms Local Databases.
And there is an good sample included in above document , which code is well encapsulated and very concise. You can check it here Todo .
The TodoItemDatabase.cs is as follows:
public class TodoItemDatabase
{
    static SQLiteAsyncConnection Database;

    public static readonly AsyncLazy<TodoItemDatabase> Instance = new AsyncLazy<TodoItemDatabase>(async () =>
    {
        var instance = new TodoItemDatabase();
        CreateTableResult result = await Database.CreateTableAsync<TodoItem>();
        return instance;
    });

    public TodoItemDatabase()
    {
        Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
    }

    public Task<List<TodoItem>> GetItemsAsync()
    {
        return Database.Table<TodoItem>().ToListAsync();
    }

    public Task<List<TodoItem>> GetItemsNotDoneAsync()
    {
        return Database.QueryAsync<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
    }

    public Task<TodoItem> GetItemAsync(int id)
    {
        return Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
    }

    public Task<int> SaveItemAsync(TodoItem item)
    {
        if (item.ID != 0)
        {
            return Database.UpdateAsync(item);
        }
        else
        {
            return Database.InsertAsync(item);
        }
    }

    public Task<int> DeleteItemAsync(TodoItem item)
    {
        return Database.DeleteAsync(item);
    }
}

How to connect sqlite in xamarin