text:
Q: Ifstream is not able to read a vector from a file Hello I am making a simple program which should make an abstract farm with some
 abstract animals but I have got a problem with reading vector from a file. I was translating most of the project and I deleted some I think unimportant functions and constructors. The program works fine when you 1st time load the vector but it fails after 2nd, 3rd... start. It fails when you try to load farm froma before created file. I am sorry for my english.

this code should be in classes.cpp - i don't know how to write it here

    #include<iostream>
    #include<string>
    #include<vector>
    #include<iterator>
    #include<fstream>
    #include<stdlib.h>
    using namespace std;

//  declaration of class zviera(animal)

    class zviera;

//  class farm

    class farma{
    private :

//  meno(name)

        std::string meno;

//  rozloha(size) - perhaps 945.5 * 749.9 meters

        std::pair<double, double> rozloha;

//  vector of friend class zviera(animal)

        std::vector < zviera > zvery;
    public :

//  class zviera(animal) is friend class of farma

        friend class zviera;

//  constructor -----------------------------------------------------

        farma() : meno(""), rozloha(0, 0), zvery(0) {}

//  pridajZviera(addAnimal) to the vector

        void pridajZviera(zviera & z){ zvery.push_back(z); }
        friend std::ostream & operator<<(std::ostream & os, const farma & far);
        friend std::istream & operator>>(std::istream & is, farma & far);
    };

//  the class zviera(animal)

    class zviera{
    private:

//  druh(kind of animal)

        std::string druh;

//  pocet(number of the animals)

        int pocet;

//  sex of the animals

        int pohlavie;
    public:

//  samec(male), samica(female) the sex of the animal

        enum { samec = 0, samica = 1};

//  constructor

        zviera() :druh(""), pocet(0), pohlavie(0){}
        friend std::ostream & operator<<(std::ostream & os, const zviera & zver);
        friend std::istream & operator>>(std::istream & is, zviera & zver);
    };

//  classes.h

    #include"classes.cpp"

//  Writing values of an animal

    std::ostream & operator<<(std::ostream & os, const zviera & zver){
            os << "Kind of animal : " << zver.druh;
            os << "\nNumber of animals : " << zver.pocet;
            os << "\nSex of animal : " << (zver.pohlavie == zver.samec? "male" : "female");
            return os;
        }

//  Setting values of an animal

    std::istream & operator>>(std::istream & is, zviera & zver){
                std::cout << "Kind : ";
                is >> zver.druh;
                std::cout << "Number : ";
                is >> zver.pocet;
                std::cout << "sex(0 - male, 1 - female) : ";
                is >> zver.pohlavie;
                return is;
            }

//  Writing saved values of a farm

    std::ostream & operator<<(std::ostream & os, const farma & far){
        os << "Name of the farm : " << far.meno;
        os << "\nSize of the farm : " << far.rozloha.first << " * " << far.rozloha.second << "metres." << std::endl;
        os << "Animals on the farm : \n";
        std::vector < zviera >::const_iterator it = far.zvery.begin();
        for (; it != far.zvery.end(); it++){
            os << *it << "\n";
        }
        return os;
    }

//  Setting values of a farm

    std::istream & operator>>(std::istream & is, farma & far){
        std::cout << "Meno farmy je : ";
        is >> far.meno;
        std::cout << "Rozloha farmy je(a * b metrov) : ";
        is >> far.rozloha.first;
        is >> far.rozloha.second;
        std::cout << " metrov.";
        return is;
    }

The main.cpp
    #include"classes.h"

        int main()
    {
        ofstream fout;
        ifstream fin;
        int temp = 0;
        int tmp = 5;
        int tomp = 0;
        string nazov;
        farma far;
        zviera zvero;
        while (cin){
            cout << "Hello would you like to load your farm from a file?(yes - 1, no - 0, end - 2) ";
            cin >> temp;
            switch (temp){
            case 0:
                cout << "Write a name of a file to save your new farm : ";
                cin >> nazov;
                fout.open(nazov.c_str(), ios_base::out);
                cin >> far;
                fout.write((char*)&far, sizeof far);
                cout << "Would you like to add any animals to your farm?(0 - no, 1 - yes) ";
                cin >> tmp;
                while (tmp == 1){
                    switch (tmp){
                    case 1:cin >> zvero;
                    far.pridajZviera(zvero);

I meam the problem is probably here:
                    fout.write((char*)&zvero, sizeof zvero);
                    cout << "Would you like to add any animals to your farm?(0 - no, 1 - yes) ";
                    cin >> tmp;
                        break;
                    default:
                        break;
                    }
                }
                fout.close();
                cout << "Do you wanna see your farm?(0 - no, 1 - yes) ";
                cin >> tomp;
                if (tomp == 1){
                    cout << far;
                }
                break;
            case 1:
                cout << "Enter name of the file in which is your farm : ";
                cin >> nazov;
                fin.open(nazov.c_str(), ios_base::in);

The problem may be also here I think
                fin.read((char*)&far, sizeof far);
                while (fin.read((char*)&zvero, sizeof zvero)){
                    far.pridajZviera(zvero);
                }
                cout << far;
                fin.close();
                break;
            case 2: exit(EXIT_SUCCESS);
            default: cout << "Wrong value. Enter 0,1 or 2.\n";
                break;
            }
        }

        return 0;
    }

A: read and write operations are like memcpy, they make a binary image of the object, and don't follow pointers to subobjects.  So you can only use them for trivially copyable objects.
std::vector and std::string are NOT trivially copyable.  (Objects containing these types are NOT trivially copyable either.)  For those, you'll need to fetch and store the length, followed by the data.  For std::string, and std::vector where the element type is trivially copyable, you can use read and write to store the data en masse.  Most objects will themselves need to be carefully serialized.

A: Reworked - problems solved

classes.h

  #include<iostream>
    #include<string>
    #include<vector>
    #include<iterator>
    #include<fstream>
    class zviera;
    class farma{
    private:
        std::string meno;
        std::pair<double, double> rozloha;
        std::vector < zviera > zvery;
    public:
        friend class zviera;
        farma() : meno(" "), rozloha(0, 0), zvery(0) {}
        void zmenRozlohu(const double & a, const double & b){ rozloha.first = a; rozloha.second = b; }
        void zmenMeno(std::string & s){ meno = s; }
        void pridajZvery(const std::vector < zviera > zv);
        friend std::ifstream & operator>>(std::ifstream & fin, farma & far);
        friend std::ofstream & operator<<(std::ofstream & fout, farma & far);
        friend std::ostream & operator<<(std::ostream & os, const farma & far);
        friend std::istream & operator>>(std::istream & is, farma & far);
    };
    class zviera{
    private:
        std::string druh;
        int pocet;
        int pohlavie;
    public:
        friend class farma;
        enum { samec = 0, samica = 1 };
        zviera() :druh(" "), pocet(0), pohlavie(0){}
        friend std::ifstream & operator>>(std::ifstream & fin, zviera & zver);
        friend std::ofstream & operator<<(std::ofstream & fout, zviera & zver);
        friend std::ostream & operator<<(std::ostream & os, const zviera & zver);
        friend std::istream & operator>>(std::istream & is, zviera & zver);
        void setPohlavie(const int & i){ pohlavie = (pohlavie == i) ? 1 : 0; }
    };

classes.cpp

#include"classes.h"
void farma::pridajZvery(const std::vector < zviera > zv){
    zvery.resize(zv.size());
    copy(zv.begin(),zv.end(),zvery.begin());
}
std::ostream & operator<<(std::ostream & os, const zviera & zver){
    os << "Druh : " << zver.druh;
    os << "\nPocet zvierat : " << zver.pocet;
    os << "\nPohlavie : " << (zver.pohlavie == zver.samec ? "samec" : "samica");
    return os;
}
std::istream & operator>>(std::istream & is, zviera & zver){
    std::cout << "Druh : ";
    is >> zver.druh;
    std::cout << "Pocet : ";
    is >> zver.pocet;
    std::cout << "Pohlavie(0 - samec, 1 - samica) : ";
    is >> zver.pohlavie;
    return is;
}
std::ifstream & operator>>(std::ifstream & fin, zviera & zver){
    getline(fin, zver.druh);
    fin >> zver.pocet;
    while (fin.get() != '\n'){
        fin.get();
    }
    fin >> zver.pohlavie;
    while (fin.get() != '\n'){
        fin.get();
    }
    return fin;
}
std::ifstream & operator>>(std::ifstream & fin, farma & far){
    getline(fin, far.meno);
    fin >> far.rozloha.first;
    while (fin.get() != '\n'){
        fin.get();
    }
    fin >> far.rozloha.second;
    while (fin.get() != '\n'){
        fin.get();
    }
    return fin;
}
std::ofstream & operator<<(std::ofstream & fout, farma & far){
    fout << far.meno;
    fout << std::endl;
    fout << far.rozloha.first;
    fout << std::endl;
    fout << far.rozloha.second;
    fout << std::endl;
    return fout;
}
std::ofstream & operator<<(std::ofstream & fout, zviera & zver){
    fout << zver.druh;
    fout << std::endl;
    fout << zver.pocet;
    fout << std::endl;
    fout << zver.pohlavie;
    fout << std::endl;
    return fout;
}
std::ostream & operator<<(std::ostream & os, const farma & far){
    os << "Nazov farmy : " << far.meno;
    os << "\nFarma ma rozlohu : " << far.rozloha.first << " * " << far.rozloha.second << "metrov." << std::endl;
    os << "Zvierata na farme : \n";
    if (far.zvery.size() <= 0){
        return os;
    }
    std::vector < zviera >::const_iterator it = far.zvery.begin();
    for (; it != far.zvery.end(); it++){
        os << *it << "\n";
    }
    return os;
}
std::istream & operator>>(std::istream & is, farma & far){
    std::cout << "Meno farmy je : ";
    is >> far.meno;
    std::cout << "Rozloha farmy je(a * b metrov) : ";
    is >> far.rozloha.first;
    is >> far.rozloha.second;
    std::cout << " metrov.";
    return is;
}

main.cpp

#include"classes.h"
#include<algorithm>
#include<stdlib.h>
using namespace std;
int main()
{
    int temp = 0;
    int tmp = 5;
    int tomp = 0;
    int len = 0;
    string nazov;
    zviera zvero;
    while (cin){
        ofstream fout;
        cout << "Hello would you like to load your farm from a file?(yes - 1, no - 0, end - 2) ";
        cin >> temp;
        switch (temp){
        case 0:{
            farma far;
            std::vector < zviera > zve;
            cout << "Write a name of a file to save your new farm : ";
            cin >> nazov;
            fout.open(nazov.c_str(), ios_base::out | ios_base::binary);
            cin >> far;
            cout << "Would you like to add any animals to your farm?(0 - no, 1 - yes) ";
            cin >> tmp;
            while (tmp == 1){
                switch (tmp){
                case 1:cin >> zvero;
                    zve.push_back(zvero);
                    cout << "Would you like to add any animals to your farm?(0 - no, 1 - yes) ";
                    cin >> tmp;
                    break;
                default:
                    break;
                }
            }
            len = zve.size();
            fout << len;
            fout << endl;
            for (int x = 0; x < len; x++){
                fout << zve[x];
            }
            fout << far;
            far.pridajZvery(zve);
            fout.close();
            cout << "Do you wanna see your farm?(0 - no, 1 - yes) ";
            cin >> tomp;
            if (tomp == 1){
                cout << far;
            }
            break;
        }
        case 1:{
            ifstream fin;
            farma kar;
            std::vector < zviera > zvert;
            cout << "Enter name of the file in which is your farm : ";
            cin >> nazov;
            fin.open(nazov.c_str(), ios_base::in | ios_base::binary);
            fin >> len;
            while (fin.get() != '\n')
                fin.get();
            zvert.resize(len);
            for (int x = 0; x < len; x++){
                fin >> zvert[x];
            }
            fin >> kar;
            kar.pridajZvery(zvert);
            cout << kar;
            fin.close();
            break;
        }
        case 2: exit(EXIT_SUCCESS);
        default: cout << "Wrong value. Enter 0,1 or 2.\n";
            break;
        }
    }

    return 0;
}


text:
Q: SQL Server trigger: limit record insert I'm doing a database for a university work. At certain point we have to create a trigger/function that can limit insertion of records on my SQL Server Management Studio 17, taking into account different foreign keys. For example we can have 100 records, but we can only have 50 records for the same foreign key.
We have this constraint:
CREATE TABLE [dbo].[DiaFerias] WITH CHECK
    ADD CONSTRAINT [Verificar22DiasFerias]
         CHECK (([dbo].[verificarDiasFerias]((22)) ='True'))

With the help of this function:
ALTER FUNCTION [dbo].[verificarDiasFerias] (@contagem INT)
RETURNS VARCHAR(5)
AS
BEGIN
    IF EXISTS (SELECT DISTINCT idFuncionario, idDiaFerias
               FROM DiaFerias
               GROUP BY idFuncionario, idDiaFerias
               HAVING COUNT(*) <= @contagem)
        RETURN 'True'

    RETURN 'False'
END

A: Would I use a trigger here? Reluctantly, yes (See Enforce maximum number of child rows for how to do it without triggers, in a way I'd never recommend). Would I use that function? No.
I'd create an indexed view:
CREATE VIEW dbo.DiaFerias_Counts
WITH SCHEMABINDING
AS
    SELECT idFuncionario, idDiaFerias, COUNT_BIG(*) as Cnt
    FROM dbo.DiaFerias
    GROUP BY idFuncionario, idDiaFerias
GO
CREATE UNIQUE CLUSTERED INDEX PK_DiaFerias_Counts on
    dbo.DiaFerias_Counts (idFuncionario, idDiaFerias)

Why do this? So that SQL Server maintains these counts for us automatically, so we don't have to write a wide-ranging query in the triggers. We can now write the trigger, something like:
CREATE TRIGGER T_DiaFerias
ON dbo.DiaFerias
AFTER INSERT, UPDATE
AS
    SET NOCOUNT ON;

    IF EXISTS (
      SELECT
         *
      FROM dbo.DiaFerias_Counts dfc
      WHERE
        dfc.Cnt > 22
      AND
        (EXISTS (select * from inserted i
         where i.idFuncionario = dfc.idFuncionario AND i.idDiaFerias = dfc.idDiaFerias)
        OR EXISTS (select * from deleted d
         where d.idFuncionario = dfc.idFuncionario AND d.idDiaFerias = dfc.idDiaFerias)
      )
    )
    BEGIN
        RAISERROR('Constraint violation',16,1)
    END

Hopefully you can see how it's meant to work - we only want to query counts for items that may have been affected by whatever caused us to trigger - so we use inserted and deleted to limit our search.
And we reject the change if any count is greater than 22, unlike your function which only starts rejecting rows if every count is greater than 22.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert itemize/enumerate blocks inside schemata? How can you insert itemize/enumerate blocks inside schemeata?
\documentclass[10pt,a4paper]{article}
\usepackage{schemata}
\newcommand\AB[2]{\schema{\schemabox{#1}}{\schemabox{#2}}}

\begin{document}

\AB{text here}
{
\AB{Some text 1}
{

%%%%%%%%%%%%%%%%%%%% With this lines instead of itemize block, all runs fine
%$\bullet$ text 1.1 \\
%$\bullet$ text 1.2 \\
%$\bullet$ text 1.3 \\
%$\bullet$ text 1.4
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{itemize}
  \item text 1.1\\
  \item text 1.2\\
  \item text 1.3\\
  \item text 1.4\\
\end{itemize}
}\\
Some text 2 \\
Some text 3 \\
\AB{Some text 4}
{
text 1.1 \\
text 1.2 \\
text 1.3 \\
text 1.4
}\\

}

\end{document}

A: One way of doing it is using a minipage environment:
\documentclass[10pt,a4paper]{article}
\usepackage{schemata}
\newcommand\AB[2]{\schema{\schemabox{#1}}{\schemabox{#2}}}

\usepackage{enumitem}
\newlength{\mywidth}
\setlength{\mywidth}{\textwidth}
\addtolength{\mywidth}{-\parindent}

\newenvironment{myitemize}
   {\begin{minipage}{\mywidth}\begin{itemize}[leftmargin=1em,itemsep=-0.5em]}
   {\end{itemize}\end{minipage}}

\begin{document}

\AB{text here}
{
\AB{Some text 1}
{

\begin{myitemize}
  \item text 1.1
  \item text 1.2
  \item text 1.3
  \item text 1.4
\end{myitemize}

}\\
Some text 2 \\
Some text 3 \\
\AB{Some text 4}
{
text 1.1 \\
text 1.2 \\
text 1.3 \\
text 1.4
}\\

}

\end{document}


text:
Q: Full Text search not working in Postgresql when Comma(,) Present in the database I've implemented the full text search by using tsvector and tsquery. It is not working when there is a comma present in the database.
I'm using the below query to search the result and it is not fetching any row.
select ndc,ln60
from rndc14_ndc_mstr
where (to_tsvector(ln60) @@ plainto_tsquery('Metformin 1000'));

Below are the data present in the database with matching of above string.


text:
Q: C# Random Function only produces one value In this for loop I keep getting same value from my Random Function.
How can I get the Random Function to be actually Random?
for (int i=0; i<50; i++){
Random random = new Random();
int randomSong = random.Next(0, songList.Count - 1);
var selectedSong = songList.ElementAt(randomSong);
}

A: You need to define Random outside of the loop.
var rand = new Random();
for (int x = 0; x<50;x++)
{
    var song = list.ElementAt(rand.Next(list.Count()));
}


text:
Q: unable to send eth to deployed smart contract // SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

contract Steezy  {

    function contractAddress() public view returns (address asd){
        return address(this);
    }

    function buy() public payable{
        uint256 listenPrice = 25000000000000000;
        (bool successs, ) = address(this).call{value: listenPrice}("");
        require(successs, "Failed");
    }

}

I was trying to send some eth to the deployed smart contract but it gives me Failed execution reverted

A: // SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

contract Steezy  {

    function contractAddress() public view returns (address asd){
        return address(this);
    }
    function buy() public payable{
        uint256 listenPrice = 25000000000000000;
        (bool successs, ) = address(this).call{value: listenPrice}("");
        require(successs, "Failed");
    }
    fallback() external payable {}
}

You were missing the fallback function try this out. It should work


text:
Q: Sharepoint Sharing configuration not available/missing In our SharePoint 2013 on-premises site permissions settings, if I click on Access Request Settings  I can see only one check box with email configuration.
I am not able to configure sharing options, as they are not available.
How can I enable these options. as referred here
Or is this available only in Office 365?


text:
Q: How to add menu subitem in magento website? I want to add menu sub item in the existing parent menu but couldn't get good resource to help me out? can we add sub-item menu through magento admin panel?

A: If you are using default theme than you can easily create menu from admin panel
or you can use custom extension for this as well.
You can use below extension:
Megamenu for Magento 1
This extension is easy to manage and you can add categories as you want.

A: *

*To start, simply go to Magento admin -> Catalog -> Manage
Categories.

*Manage categories page, you will notice 2 buttons which read 'add
root category' and 'add subcategory'. Note that a root category
serves more as a placeholder for subcategories. In other words, you
enter any categories that you want seen in your store as a
subcategory within a root category.

*By default, Magento has a 'default category' setup already. This
default category is a root category.

*You would add the category as a subcategory by clicking on a root
category and then clicking the 'add subcategory button'.

*On the next page, you will need to enter a name for your subcategory
which can be anything that you'd like.

*For 'is active', you'd want to select "Yes" if you want the category to show in your store.

*As for 'include in navigation menu', if you select "Yes", your
category will show up in the navigation menu.

*Once you have finished entering your information, move onto the
'display settings' tab.

*In the display mode, you have the option of choosing 'products
only', 'static block only' and 'static block and products'.

*As for 'is anchor', if you select "Yes", a layered navigation menu will appear on category pages.


text:
Q: Is it possible to have a planet entirely made out of liquid water? Earth is mostly covered in oceans, but they only go a few kilometres deep. It's obviously not possible to have a planet the size of the earth to be made entirely out of water, because of the kind of pressures reached in the interior.
a. But say that we did, how far down from the surface would water remain water before presumably turning to ice under the pressure?
b. How large a 'planet' could we have made entirely out of water? Would it be able to attain the size of a small dwarf planet like Ceres?

A: Suppose we assemble a large mass of water in space, then it will form a sphere held together by its gravitational field. The question is then how large this sphere can become before the pressure at the centre causes the water to solidify to ice.
The calculation of the pressure at the centre is straightforward in principle, and is described in How to find the force of the compression at the core of a planet? The problem is that to do the calculation precisely we need to know how the density of water changes with pressure. There is no simple equation for this so we would need to do a numerical calculation. However if we make the approximation that the density of the water remains constant we can get an approximate equation for the pressure:
$$ P = \frac{2}{3}\pi G \rho ^2 R^2 \tag{1} $$
We can estimate the pressure at which water solidifies by looking at the phase diagram of water. The following phase diagram comes from London South Bank University web site:

The pressure at which the water solidifies to ice is strongly temperature dependent. At everyday temperatures it's around 800MPa to a GPa, and since this is an approximate calculation let's take a GPa as being a round number. Then using equation (1) we find that value of the radius $R$ for which the pressure reaches 1GPa is about 2700km.
So there's your answer. A ball of water at room temperature larger than 2700km would contain a solid ice core. In practice the density of the water increases with depth so the radius at which ice forms would be less than this. Though the relative density of ice VI is only around $1.3$ so it wouldn't be that much smaller.

A: The related question points out that water would become ice at a depth of around sixty km. This answers the first question. And this suggests we should expect a body of water a 120km in diameter to remain water all the way through. This is far smaller than a dwarf planet and more the size of a large asteroid.


text:
Q: How to implement bank/cross-order type updates scalably and safely I'm working on a small project on Google App Engine, trying to implement a site that allows participants to buy and sell fake goods, similarly to a stock market where the system will show real time-ish BID/ASK spreads.
As a quick example:

*

*A Seller places and order to sell 10 Boxes for 8.00 (Order 1)

*A Buyer places then an order to purchase 5 boxes for up to 9.00 (Order 2)

When the second order is placed, the system will need to do multiple tasks, all contingent on all of the tasks completing successfully.

*

*Take the funds (8.00 x 5) to pay for the boxes from the Buyer and give them to the Seller

*Take the boxes (5) from the Seller and give them to the Buyer

*Update the orders as complete (OID 2 ) or update as partially filled (OID 1) so that they cannot be double matched

*Take a fee from each of the participants and add it to a system account

If all that I needed was to move funds from one participant to another, I can do that safely even if the system were to fail in the middle.  But to ensure that all of the tasks above complete correctly, and roll-back if any of them fail seems overly complex in App Engine.
Additionally, my "Order Book" and order matching engine are single threaded right now (using Mutexes for locking.) This seems to go against the whole point of using App Engine, but I'm not sure I see a way around it.
So (finally) - My questions are:

*

*Is there a best practice when using App Engine where there are multiple steps that all depend on every step completing correctly?

*Does anyone have any suggestions as how to either, allow the order book to be multi-threaded, or if it remains single threaded - is there a best practice to not have this core piece block the use of the site as it scales?  I've thought about using tasks to queue the order adds/updates/cancels to keep the book separate from direct participant input.

Thank you, I look forward to your help!

A: I think if you can sequence the orders on a commodity, then you can clear orders offline. By "offline", I mean you can come to me at the end of the day, tell me the sequence of the orders, and I can tell you which trades happened. The one snag is, what if a buyer does not have the funds when a transaction should have cleared? You can address this in two ways:

*

*Put the funds in an escrow so that any orders that can clear do.

*Drop buy orders when you try to clear them if the funds are not available.

As you suggested, you'll probably need cross-entity group transactions in order to make sure the fund transfers are correct (i.e. funds are neither created nor destroyed).
You can sequence orders by time (e.g. paced_at = db.DateTimeProperty(auto_now_add=True)). If two orders have the same time, then use something (preferably something fair and deterministic) to break the tie. Hash (for fairness) of the numeric id (for determinism) might not be a bad choice here.
App Engine is inherently multithreaded in the sense that an app can have many concurrent instances (instances are not necessarily threads within the same process though). Instances are created automatically, and there is currently no way to cap the number of instances at 1. If the state of your app is in Datastore (as opposed to local memory, memecache, or somewhere else), and your transactions are correct, then your app will be multithreaded "for free". Of course, your transactions being correct is not trivial.
Another tool to keep in mind is that tasks can be transactional. This may come in handy if you want to do offline book clearing using tasks.

A: For others that stumble upon this -
It seems that Cross-Group Transactions are now possible in Google App Engine:
https://developers.google.com/appengine/docs/python/datastore/transactions#Using_Cross_Group_Transactions
This means that you can, within a single transaction concurrently read, perform logic, and then write to multiple entities at once.
I believe that this solves the first issue that I proposed in my question.
The second question - is there was way to have an order book that is not single threaded, is still open.
Thank you!


text:
Q: Huawei Subscription Validation ResponseCode:6 ResponseMessage:Token is expired or invalid InappPurchaseData I'm trying to verify subscription purchase  in our backend servers, considering from this hms-iap-serverdemo GitHub repo.
I'm trying to connect OAuth 2.0-based authentication servers using app ID and app secret. I took ID and secret from AppGallery Connect → my app → app information.  The auth servers returns base64 encoded token. When I try to verify with this subscription purchase, I am getting ResponseCode:6 ResponseMessage:Token is expired or invalid InappPurchaseData  error from server.
The status of the application is currently draft. Is that why I'm getting this error? I believe client ID and client secret is correct.  Or something else. I do not know. Do you have an idea?
Thank you

A:
ResponseCode:6 ResponseMessage:Token is expired or invalid InappPurchaseData

The possible causes are as follows:

*

*Check whether the token is invalid.The token validity period is 1 hour. If the token expires, obtain a new token to ensure that the token is valid.

Check whether the AT is invalid and whether only the AT in the cache is obtained. If the AT is invalid, clear the cache and obtain the AT again. Generally, use the token interface to obtain the application-level AT again.
For details about how to obtain the application level AT, see docs.

*The token format is incorrect.

According to the docs:
App-level access token: Authorization: Basic Base64(APPAT:atvalue)

*

*Example: The app-level access token is thisIsAppAtValue, then APPAT:atvalue is APPAT:thisIsAppAtValue.

Therefore, replace APPAT:atvalue in Base64(APPAT:atvalue) with "APPAT:thisIsAppAtValue" to generate value QVBQQVQ6dGhpc0lzQXBwQXRWYWx1ZQ==.
The value of Authorization in the request header is as follows: Basic QVBQQVQ6dGhpc0lzQXBwQXRWYWx1ZQ==

*The site request is incorrect.

Switch to a proper site based on your location and try again.
China: https://subscr-drcn.iap.hicloud.com
Germany: https://subscr-dre.iap.hicloud.com
Singapore: https://subscr-dra.iap.hicloud.com
Russia: https://subscr-drru.iap.hicloud.com


text:
Q: What's the best way to ignore "Object reference not set to an instance of an object" errors with nested properties? I'm running across lots of cases where I want to display something along the lines of
@ev.Event.Instructor.Name

But the instructor property is allowed to be null.  In those cases the "Object reference not set to an instance of an object." error is thrown but I'd like to ignore that and have nothing returned..
Is there a better way to handle this than to create lots of ternary expressions all over the place to check for null?
The equivalent php expression would be
@$ev.Event.Instructor.Name

I've been translating some webforms views to MVC and the equivalent Eval statement would ignore null reference errors.
To clarify:
The @ev property is coming from a linq query and there are also cases where I have
@ev.mainContact.FirstName @ev.mainContact.LastName
@ev.mainContact.Company.Name

Where not only the mainContact can be null but the mainContact's company can also be null.  It seems like an equally bad solution to select every single attribute with a ternary checking for null.

A: One way is to add another property to Event:
public string InstructorName
{
    get { return Instructor == null ? string.Empty : Instructor.Name; }
}

A: There is no such thing as "ignoring exception". You should not cause exceptions or should handle them.
public class Event {
     public Event() {
          this.Instructor = new Instructor();
     }
}

or
@(ev.Event.Instructor == null ? String.Empty : ev.Event.Instructor.Name)

A: You should instantiate your objects in the constructor so you avoid null objects, example:
public class Event{
     public Event(){
          Instructor = new Instructor();
     }
}

A: Another approach I though of which is a debatable amount of nasty is:
@{try{@ev.Event.Instructor.Name}catch{}}

I decided to use this approach instead of adding 18 or so extra properties in the select all with ternary expressions.

A: Something like:
@$ev.Event.Instructor != null ? @$ev.Event.Instructor.Name : String.Empty


text:
Q: how to test ModelAttribute parameter by MockMvc I wrote this controller method:
  @RequestMapping("/submitFormAdd")
        public ModelAndView submitFormAdd(
                Model model,
                @ModelAttribute("myCandidate") @Valid Candidate myCandidate,
                BindingResult result,
                RedirectAttributes redirectAttributes) {
            if (result.hasErrors()) {
                return new ModelAndView("candidateDetailsAdd");
            }

            myCandidate.setDate(new Date());
            candidateService.add(myCandidate);

            redirectAttributes.addAttribute("message", "added Correctly at "+ new Date() );
            redirectAttributes.addAttribute("id", myCandidate.getId());
            ModelAndView modelAndView = new ModelAndView(
                    "redirect:loadCandidateById");
            return modelAndView;
        }

UPDATE
myCandidate instantiants so:
@ModelAttribute(value = "myCandidate")
    public Candidate loadCandidateById(
            @RequestParam(required = false) Integer candidateId) {
        if (candidateId != null)
            return candidateService.findById(candidateId);
        return null;
    }

What way can I test that this method gets Candidate ?
I use MockMvc.

A: You cannot test specifically that the method will receive the Candidate argument. Your options are to either send bad request data and therefore make Spring unable to correctly instantiate it and return a 400 error (but that can happen for other reasons). Or send correct data and receive what you normally expect.
Note that you shouldn't be testing Spring functionality. When you use a 3rd party framework, you assume that it has been tested properly, especially one like Spring.


text:
Q: Route::resource binding creates plural attribute routes (i.e. projects/{projects}) I am trying to set up a Route:resource for Series.

*

*When I create individual get, post, patch and delete Routes it works as expected (e.g. GET series/${serie}).

*However when I use Route::resource it creates plural attributes (e.g. GET series/${series}).

*In the laracast that I am following it creates the singular (e.g. GET projects/${project}).
I can't figure out what I am missing.
This works:
Route::get('/series', 'SeriesController@index');
Route::get('/series/create', 'SeriesController@create');
Route::get('/series/{serie}', 'SeriesController@show');
Route::post('/series', 'SeriesController@store');
Route::get('/series/{serie}/edit', 'SeriesController@edit');
Route::patch('/series/{serie}', 'SeriesController@update');
Route::delete('/series/{serie}', 'SeriesController@destroy');

The route list is:
GET|HEAD | series                | App\Http\Controllers\SeriesController@index
POST     | series                | App\Http\Controllers\SeriesController@store
GET|HEAD | series/create         | App\Http\Controllers\SeriesController@create
GET|HEAD | series/{serie}        | App\Http\Controllers\SeriesController@show
PATCH    | series/{serie}        | App\Http\Controllers\SeriesController@update
DELETE   | series/{serie}        | App\Http\Controllers\SeriesController@destroy
GET|HEAD | series/{serie}/edit   | App\Http\Controllers\SeriesController@edit

This doesn't work:
Route::resource('series', 'SeriesController');

and produces this route list:
GET|HEAD | series                | App\Http\Controllers\SeriesController@index
POST     | series                | App\Http\Controllers\SeriesController@store
GET|HEAD | series/create         | App\Http\Controllers\SeriesController@create
GET|HEAD | series/{series}       | App\Http\Controllers\SeriesController@show
PATCH    | series/{series}       | App\Http\Controllers\SeriesController@update
DELETE   | series/{series}       | App\Http\Controllers\SeriesController@destroy
GET|HEAD | series/{series}/edit  | App\Http\Controllers\SeriesController@edit

Notice the plural form {series}. Why is this happening?

A: "Series" is the plural as well as the singular of the word, therefore the routes Laravel is generating are perfectly fine.
If you have a look into Laravels pluralizer helper, you can even see that "series" is explicitely listed as uncountable: https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Pluralizer.php#L49


text:
Q: Measure on topological spaces So, given a topological space $S$ we can construct its Borel sigma-algebra $\mathcal{B}(S)$. Does it mean that we can construct a measure $\mu$ on this sigma-algebra as well? Say, discrete topology on the circle implies $\mathcal{B}(S) = 2^S$, and hence we know that we cannot construct a measure.
This leads to the idea that certainly we need some restrictions on the topological space. What are useful sufficient conditions?
I am especially interested in the conditions like
- separable;
- second countable;
- metrizable;

A: This question is an oldie, but I feel that it deserves a more elaborate answer, so here goes.
As you said, to every topological space $X$ one can associate the Borel $\sigma$-algebra $\mathcal{B}_X$, which is the $\sigma$-algebra generated by all open sets in $X$. Now $(X,\mathcal{B}_X)$ is a measurable space and it is desirable to find a natural Borel measure on it. By Borel measure I simply mean a measure defined on $\mathcal{B}_X$ and by "natural" I mean that it should be compatible with the topology of $X$ in some sense (otherwise, $X$ is just an abstract set). There are several compatibility conditions one can impose, which are motivated from the fact that the Euclidean spaces (with Lebesgue measure) satisfy all of them. The following are most often encountered:

*

*Strict positivity: this means that the measure of every nonempty open set is positive.

*Local finiteness: this means that every point has some open neighborhood $V$ with $\mu(V) < \infty$.

*Finiteness on compacta: this means that $\mu (K) < \infty$ for every compact set $K \subset X$.

*Outer regularity: This means that the measure of every Borel set $E \subset X$ is equal to the infimum of $\mu (G)$ over all open sets $G \subset X$ which contain $E$.

*(Weak) inner regularity: This means that the measure of every Borel set $E \subset X$ is equal to the supremum of $\mu (C)$ over all closed sets $C \subset X$ which are contained in $E$.

*(Strong) inner regularity, also known as tightness: The measure of every Borel set $E \subset X$ is equal to the supremum of $\mu (K)$ over all compact sets $K \subset X$ which are contained in $E$.

*Regularity: this is just outer regularity + (strong) inner regularity.

*Radon: $\mu$ is Radon if it is satisfies a certain combination of the above properties. Different texts often use different combinations, which often coincide if the topological space $X$ is nice enough (certainly if it is, say, $[0,1]$). One popular combination is "Radon = locally finite + inner regular" but some texts omit the inner regularity hypothesis, some replace it with outer regularity, some add outer regularity, etc. . The thing to keep in mind is that a Radon measure is a Borel measure which has some nice relation to the topology, but not necessarily every relation you want it to have (especially if the topology is somewhat ill-behaved).

In addition, there are some general measure-theoretical conditions one can impose on $\mu$ which ensure that it obeys to some general measure-theoretical theorems (e.g. Fubini). The most useful ones are:

*

*$\sigma$-finiteness: this means that $X$ can be written as a countable union of Borel sets such that each of these sets has finite measure.

*Finiteness:  $\mu (X) < \infty$.

Also, you probably want $\mu$ to be nondegenerate ($\mu \ne 0$).
The above conditions are certainly not mutually independent and even for the most general topological spaces there are some obvious implications. For instance:

*

*Strict positivity implies nondegeneracy.

*If $X$ is Hausdorff then strong inner regularity implies weak inner regularity.

*If $X$ is Hausdorff and locally compact then finiteness on compacta implies local finiteness.

*If $X$ is $\sigma$-compact (i.e. equal to a countable union of compact subsets) and $\mu$ is finite on compacta, then $\mu$ is $\sigma$-finite.

*If $\mu$ is finite then outer regularity is equivalent to (weak) inner regularity.

*etc.

In the highest generality (arbitrary topological spaces), there is almost nothing nontrivial one can say, and one may not be able to find any nice Borel measure on the space. Therefore one restricts to some nice class of topological spaces, in which an interesting theory can be developed. Among them we have:

*

*$\sigma$-compact, locally compact Hausdorff spaces. On such spaces there are strictly positive, finite on compacta, regular measures (which are then also $\sigma$-finite, and finite if the space is compact). In fact, there are plenty of them. A theorem of Riesz asserts that in this case, Borel measures on $X$ are in 1-1 correspondence with positive linear functionals on $C_c (X)$(the normed space of all continuous real-valued functions on $X$ with compact support) and Borel measures satisfying the above regularity conditions. Every such functional acts as integration against a measure on $X$ satisfying the above.

*Polish spaces, which are topological spaces homeomorphic to separable, complete metric spaces, e.g. infinite dimensional Banach spaces and countably infinite products of finite discrete spaces. In such spaces it is often difficult to find a geometrically appealing Borel measure, especially if you want the measure to be invariant under many isometries of a given metric. But as Tim mentioned, they frequently appear in functional analysis and probability theory, and so find their uses.

Almost any space which shows up in applications belongs to one of these two classes. For instance, real (and p-adic?) Lie groups and their homogeneous spaces always belong to the first class.
Here are some references: for the theory of measures on locally compact topological spaces, there's a book called "Measure and Integration" by König. It is somewhat technical but very general. For Polish spaces, there's a very nice book by Parthasarathy called "Probability Measures on Metric Spaces". "Handbook of measure theory" probably discusses these subjects in length too.

A: As Nate already pointed out, one can always construct a measure on a $\sigma$-algebra, but maybe you had some special applications in mind, and asked what kind of spaces people usually use for those?
One possible answer would be: Polish spaces, which are the most general spaces usually used in functional analysis and probability theory (a Polish space is isomorphic to a separable complete metric space).
Also see this blog post: ncafe.
Also see Radon measure (Wikipedia) for some reasons why general topological spaces are usually not used, but at least locally compact Hausdorff spaces.
See for example the commutative Gelfand-Naimark theorem, which says that the spectrum of a commutative $C^*$- algebra is a locally compact Hausdorff space.


text:
Q: Machine Learning in practice: Writing algorithms yourself or using Weka? I asked myself the question whether most people normally code the machine learning algorithms themselves or whether they are likely to use existing solutions like Weka or R packages.
Of course it depends on the problem - but let's say that I want to use a common solution like a neural network. Is there still a reason to code it myself? To understand the mechanism better and adapt it? Or is the thought of standardized solutions more important?

A: This is not a good question for Stackoverflow. It's an opinion question, not a programming problem.
Nevertheless, here is my take:
It depends on what you want to do.

*

*If you want to find which algorithm works best for your data problem at hand, try ELKI, Weka, R, Matlab, SciPy, whatever. Try out all the algorithms you can find, and spend even more time on preprocessing your data.

*If you know which algorithm you need and need to get it into production, many of these tools will not perform good enough or be easy enough to integrate. Instead, check if you can find low level libraries such as libSVM that provide the functionality you need. If these don't exist, roll your own optimized code.

*If you want to do research in this domain, you are best off with extending the existing tools. ELKI and Weka have APIs that you can plug into to provide extensions. R doesn't really have an API (CRAN it's a mess...) but people just dump their code somewhere and (hopefully) add a manual how to use it. Extending these frameworks can save you a lot of effort: you have comparison methods ready to use, and you can re-use a lot of their code. ELKI for example has a lot of index structures to accelerate algorithms. Most of the time, the index acceleration is much harder to write than the actual algorithm. So if you can reuse the existing indexes, this will make your algorithms much faster, too (and you will also benefit from future enhancements to these frameworks).

*If you want to learn about existing algorithms you better implement them yourself. You'll be surprised how much more there is to optimizing some algorithms than what is taught in class. E.g. APRIORI. The basic idea is quite simple. But getting all the pruning details right, I say 1 out of 20 students gets these details. If you implement APRIORI, then benchmark it against a known good implementation and try to understand why yours is much slower, then you'll actually discover the subtle details to the algorithms. And don't be surprised to see a factor of 100 performance difference between ELKI, R, Weka etc. - it's can still be the same algorithm, just implemented more or less efficiently when it comes to actual data structures used, memory layout etc.


text:
Q: QFileDialog вешает программу на несколько секунд Используя QFileDialog в своем приложении на pyqt.
Иногда после закрытия диалог вешает программу на некоторое заметное количество секунд.
Сократил код до минимума - безрезультатно:
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore

def selectDir():
    directory = QtGui.QFileDialog.getExistingDirectory(None, u"Выберите рабочую папку") + u"\\"

class TestButton(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon')

        quit = QtGui.QPushButton('Close', self)
        quit.setGeometry(10, 10, 60, 35)

        self.connect(quit, QtCore.SIGNAL('clicked()'), selectDir)

app = QtGui.QApplication(sys.argv)
qb = TestButton()
qb.show()
sys.exit(app.exec_())

Если кликнуть по кнопке, и закрыть диалог, то вы заметите задержку.
Сама проблема довольно критичная, т.к. вызывает отвращение при использовании программы

A: Из результата обсуждения в комментариях было предложено вызывать диалог не используя нативный диалог, используя флаг QFileDialog.DontUseNativeDialog:
QtGui.QFileDialog.getExistingDirectory(None, u"Выберите рабочую папку", options=QtGui.QFileDialog.DontUseNativeDialog)


text:
Q: Play/Pause Animated Vector Drawable is not working? I am trying to create a Animated Vector Drawable from here. But i can see only the play icon in the screen. If i click on the play icon it shows the pause icon at some other distance.
I hope that both the paths are compatible! According to here
I don't know where i am going wrong ?
Animated Vector
<animated-vector
    android:drawable="@drawable/ic_play"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <target
        android:animation="@animator/play_to_pause"
        android:name="play"/>
    </animated-vector>

Vector Drawable
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="240.0dp"
    android:height="240.0dp"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0">
    <path
        android:name="play"
        android:fillColor="@color/colorPrimary"
        android:pathData="M 11 10 L 17 10 L 17 26 L 11 26 M 20 10 L 26 10 L 26 26 L 20 26" />
</vector>

Object Animator
 <set xmlns:android="http://schemas.android.com/apk/res/android">
        <objectAnimator
            android:duration="100"
            android:interpolator="@android:interpolator/decelerate_cubic"
            android:repeatMode="reverse"
            android:repeatCount="1"
            android:propertyName="pathData"
            android:valueType="pathType"
            android:valueTo="M11,10 L17,10 17,26 11,26 M20,10 L26,10 26,26 20,26"
            android:valueFrom="M11,10 L18,13.74 18,22.28 11,26 M18,13.74 L26,18 26,18 18,22.28"
            />
    </set>


text:
Q: Correct way to handle swipes between UIViews I have two views that I want to show using paging control on home screen of my app.
If user swipes on UI, it should show second view which is UITableView. First view is also UITableview.
I want to know the correct way of handling this swipes and add two round images that indicate selected page.
Whether I should go for scroll view paging or use gesture recogniser.
What is better way of doing this?

A: If I understand correctly, you should use a UIPageViewController.
Class Reference
Edit
If you want to add some sort of UIPageControl to your UIPageViewController, you need to use these 2 methods (from UIPageViewControllerDataSource):
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController

Here's a complete tutorial on using UIPageViewController (with a page control, like you want).
http://mobile.tutsplus.com/tutorials/iphone/using-scrollstyle-with-uipageviewcontroller/

A: I would put the two UITableViews into a UIScrollView with pagination.
UIScrollView already handles the swipe for you and also it has the bounce animation from the pagination.
If you were to manually handle swipe gesture, you'll likely have to implement your own bounce animation and also swipe interruption in case the user swipes back the other way while the view is being transitioned across.


text:
Q: Material 3 Navigation Drawer not highlighting item for current fragment So, I'm migrating to Material 3 right now for building my app. For the first time, navigation drawer not selecting / highlighting the item I selected (It was working in material 2).
Screenshot:

This app must selecting settings item right now, but the indicator doesn't show up
This is what I'm looking for:

I followed documentation but it didn't work.
EDIT:
This is my menu.xml code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">
    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/ic_menu_read"
        android:title="@string/menu_read" />
    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_menu_settings"
        android:title="@string/menu_settings" />
    <item
        android:id="@+id/nav_about"
        android:icon="@drawable/ic_menu_about"
        android:title="@string/menu_about" />
</menu>

A: Wrap menu items into group and set attribute checkableBehavior to single.
Example:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_menu_read"
            android:title="@string/menu_read" />
        ...
    </group>
</menu>


text:
Q: Using closeclick event in infobox I am tired of searching how to apply closeclick event in infobox(google maps). I tried almost all the scenarios that I can think of but no success.
Please help me
this is my code of adding a marker:-
var ib_click = new InfoBox();
ib_click.isOpen = false;
var toShowHover = true;

function add_marker(lat,lng,icn,title,box_html) {
  var mapcode,myOptions;
  var marker = new google.maps.Marker({
    /*marker settings*/
  });

  myOptions = {
    /*option of infobox*/
  };
  marker.ibOptions = myOptions;
  google.maps.event.addListener(marker, 'click', function() {
    mapcode = /* html for showing box */
    myOptions.content = mapcode;
    myOptions.boxStyle.width = "235px";
    ib_click.setOptions(marker.ibOptions);
    ib_click.open(map, marker);
    ib_click.isOpen = true;

    toShowHover = false;
  });
  google.maps.event.addListener(marker, 'mouseover', function() {
    //this is fired
    var mapcode = /*html for showing hover*/;
    //ib_click.open(map, marker);
    myOptions.content = mapcode;
    myOptions.boxStyle.width = "205px";
    ib_click.setOptions(marker.ibOptions);
    ib_click.open(map, marker);
    // ib_click.isOpen = true;
  });
  google.maps.event.addListener(marker, 'mouseout', function() {
    //alert('mouse out');//this is fired
    //toShowHover = true;
  });

  google.maps.event.addListener(ib_click, 'closeclick', function(){
    //how to use closeclick
    //showing error here
    alert('closed');
  });
  return marker;
}

Please shed some light, thanks
Ankur ;(

A: try adding the listener for the close click to right after the box is opened, before the }); tag.  you need to include the listener for each box, when the box is created.
Below is my code using the close click listener.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: "/mapping/redmarker1.png",
title:markerClickGrid
});
markers.push(marker);
    var boxText = document.createElement("div");
    boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: gray; padding: 5px; color:white;";
    boxText.innerHTML = marker.title;
    var myOptions = {
     content: boxText
    ,disableAutoPan: false
    ,maxWidth: 0
    ,pixelOffset: new google.maps.Size(10, -50)
    ,zIndex: null
    ,boxStyle: {
    background: "url('tipbox.gif') no-repeat"
    ,opacity: 0.75
    ,width: "140px"
    }
    ,closeBoxMargin: "10px 2px 2px 2px"
    ,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
    ,infoBoxClearance: new google.maps.Size(1, 1)
    ,isHidden: false
    ,pane: "floatPane"
    ,enableEventPropagation: false
    };
    var ib = new InfoBox(myOptions);
    ib.open(map,marker);
    preventmarkermouseoutibclose = true;

google.maps.event.addListener(ib, 'closeclick', function(event) {
    preventmarkermouseoutibclose = false;
    document.getElementById('debugtext').value = "ib close click detected";
});
google.maps.event.addListener(marker, 'click', function() {
    ib.open(map,marker);
    preventmarkermouseoutibclose = true;
    document.getElementById('debugtext').value = "ib open detected";
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
    ib.close(map,marker);
    marker.setMap(null);
    preventmarkermouseoutibclose = false;
    document.getElementById('debugtext').value = "ib close on rightclick detected";
});
google.maps.event.addListener(marker, "mouseover", function() {
    document.getElementById('debugtext').value = "marker mouseover detected";
    ib.open(map,marker);
});
google.maps.event.addListener(marker, "mouseout", function() {
    if(preventmarkermouseoutibclose==true){
    }
    else if(preventmarkermouseoutibclose==false){
    ib.close(map,marker);
    }
});

ib is the name of my info box.  each time an infobox ib is opened, a listener is added, looking for "closeclick".
This works for me.  Hope it works for you.


text:
Q: xsd-makepkg package is not loading correctly through go get command $ go get -u github.com/metaleap/go-xsd/xsd-makepkg

/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:32:22: undefined: fsnotify.FileEvent
/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:64:35: undefined: fsnotify.FileEvent
/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:72:44: undefined: fsnotify.FileEvent
/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:79:18: me.Event undefined (type *Watcher has no field or method Event)
/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:83:21: cannot assign type func(<T>) to onEvt (type func(<T>)) in range
/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:97:18: me.Error undefined (type *Watcher has no field or method Error)
/home/mypc/go/src/github.com/metaleap/go-util/fs/watcher-default.go:119:15: me.Watch undefined (type *Watcher has no field or method Watch)

A: github.com/metaleap/go-xsd is "stale since 2013" so its not too suprising it no longer works. If you check github you will see the comment "MAINTAINED FOR YEARS NOW: try the forks if running into issues. link"
In this case the reason for the error you are getting is that github.com/metaleap/go-xsd/xsd-makepkg uses https://github.com/metaleap/go-util. go-util imports  github.com/go-forks/fsnotify and, on line 32 in watcher-default.go, attempts to use OnEvent []func(evt *fsnotify.FileEvent). Unfortunately in the time since go-util was released the fsnotify package has been updated and no longer has FileEvent (removed some time around 2014).
I would suggest finding an alternative package. If you really want to use this one you could retrieve an early (pre 1.0) version of fsnotify (but I would not advise it as there have probably been a lot of fixes since then).
Note: More modern packages using go modules should not suffer from this issue (because dependencies can be locked to a specific version).


text:
Q: How to build Pytorch Mobile sample HelloWorld app? https://pytorch.org/mobile/android/
I am trying to build a Pytorch demo HelloWorld app for Android. My machine is MacOS Mojave where I installed Python3 and Torchvision via conda. I am new to Pytorch, Pytorch mobile and gradlew etc.. In the past I used CMake and Make for C/C++ builds. I tried the following steps from the pytorch website but installDebug is not found. gradlew tasks definitely doesn't have any installDebug tasks.
Is the documentation old or am I missing a step or two below? I do have Android SDK and NDK installed as far as I can tell.
$ git clone https://github.com/pytorch/android-demo-app.git
$ cd android-demo-app
$ cd HelloWorldApp
$ python trace_model.py
$ ./gradlew installDebug
FAILURE: Build failed with an exception.

* What went wrong:
Task 'installDebug' not found in root project 'HelloWorldApp'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s
$ ./gradlew tasks

A: Probably Android SDK wasn't found, try:
export ANDROID_HOME=/path/to/android/sdk
Default location on linux: ~/Android/SDK/


text:
Q: Adjusting spacing before and after subparagraph with sectsty I am helping a friend that is using sectsty to format the titles in his document. How can I adjust the spacing before and after the titles, in particular the subparagraph one?
(I know that titlesec is more powerful. But for now we just need either a quick fix or the full translation of the following to titlesec.)
This is what we have now:
\usepackage{sectsty}
\allsectionsfont{\centering\normalfont\normalsize}
\subsectionfont{\noindent\normalfont\normalsize\emph}
%\subsubsectionfont{\indent\normalfont\normalsize\itshape}
\subparagraphfont{\indent\normalfont\normalsize\itshape}

As usual this is because of thesis requirements made by ignorant people.

A: sectsty only updates only the sectional unit font-related setting but still use the traditional \@startsection construction:
\renewcommand\section{\@startsection {section}{1}{\z@}%
      {-3.5ex \@plus -1ex \@minus -.2ex}%
      {2.3ex \@plus.2ex}%
%     {\normalfont\Large\bfseries}}
      {\normalfont\Large\bfseries\SS@sectfont}}
\renewcommand\subsection{\@startsection{subsection}{2}{\z@}%
      {-3.25ex\@plus -1ex \@minus -.2ex}%
      {1.5ex \@plus .2ex}%
%     {\normalfont\large\bfseries}}
      {\normalfont\large\bfseries\SS@subsectfont}}
\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}%
      {-3.25ex\@plus -1ex \@minus -.2ex}%
      {1.5ex \@plus .2ex}%
%     {\normalfont\normalsize\bfseries}}
      {\normalfont\normalsize\bfseries\SS@subsubsectfont}}
\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}%
      {3.25ex \@plus1ex \@minus.2ex}%
      {-1em}%
%     {\normalfont\normalsize\bfseries}}
      {\normalfont\normalsize\bfseries\SS@parafont}}
\renewcommand\subparagraph{\@startsection{subparagraph}{5}{\parindent}%
      {3.25ex \@plus1ex \@minus .2ex}%
      {-1em}%
%     {\normalfont\normalsize\bfseries}}
      {\normalfont\normalsize\bfseries\SS@subparafont}}

The normal font-selections are commented out and substituted with the sectsty formatting \SS@.... Read up on the meaning of each component of \@startsection in Where can I find help files or documentation for commands like \@startsection for LaTeX? and focus on arguments 4 (before skip) & 5 (after skip).
Here's an example that adjust the space before and after the \subparagraph unit:

\documentclass{article}
\usepackage{sectsty}
\allsectionsfont{\centering\normalfont\normalsize}
\subsectionfont{\noindent\normalfont\normalsize\emph}
%\subsubsectionfont{\indent\normalfont\normalsize\itshape}
\subparagraphfont{\indent\normalfont\normalsize\itshape}
\begin{document}
\section{A section}
Some text
\subsection{A subsection}
Some text
\subsubsection{A subsubsection}
Some text
\paragraph{A paragraph}
Some text
\subparagraph{A subparagraph}
Some text

\makeatletter
\renewcommand\subparagraph{\@startsection{subparagraph}{5}{\parindent}%
      {2\baselineskip \@plus1ex \@minus .2ex}%
      {\baselineskip}%
%     {\normalfont\normalsize\bfseries}}
      {\normalfont\normalsize\bfseries\SS@subparafont}}
\makeatother

\subparagraph{A subparagraph}
Some text

\end{document}

Note that sectsty is assuming that your working with a document class for which the sectional units use \@startsection without modification from the default classes, with the exclusion of KOMA-Script (from the sectsty documentation; section 1 Introduction, p 2):

The secsty package provides a set of commands for changing the font
  used for the various sectional headings in the standard LaTeX 2e document
  classes: article, book, and report. This package also works with the
  KOMA-Script classes scrartcl, scrbook, and scrreprt.

While it "will work" with other document classes, the effect is merely to overwrite the sectional units' definitions with that of the default document classes mentioned above. For example, apa6 defines
\renewcommand{\section}{\@startsection {section}{1}{\z@}%
    {\b@level@one@skip}{\e@level@one@skip}%
    {\centering\normalfont\normalsize\bfseries}}

\renewcommand{\subsection}{\@startsection{subsection}{2}{\z@}%
    {\b@level@two@skip}{\e@level@two@skip}%
    {\normalfont\normalsize\bfseries}}

\newcommand*{\addperi}[1]{#1.}

\renewcommand{\subsubsection}{\@startsection{subsubsection}{3}{\parindent}%
    {0\baselineskip \@plus 0.2ex \@minus 0.2ex}%
    {-1em}%
    {\normalfont\normalsize\bfseries\addperi}}

\renewcommand{\paragraph}{\@startsection{paragraph}{4}{\parindent}%
    {0\baselineskip \@plus 0.2ex \@minus 0.2ex}%
    {-1em}%
    {\normalfont\normalsize\bfseries\itshape\addperi}}

\renewcommand{\subparagraph}[1]{\@startsection{subparagraph}{5}{1em}%
    {0\baselineskip \@plus 0.2ex \@minus 0.2ex}%
    {-\z@\relax}%
    {\normalfont\normalsize\itshape\hspace{\parindent}{#1}\textit{.}}{\relax}}

In order to maintain the sectional unit structure, you're better off redefining the above set manually* (separate from sectsty, as was done in the first example). The same approach would hold (including a redefinition to your liking within a \makeatletter...\makeatother pair) as apa6 also uses \@startsection to define the sectional units.
* Of course, other packages could be used as well, if they are compatible with apa6, but that seems to be out of the question here.


text:
Q: nfs mounting error, nfs: Unknown parameter 'ip' I was trying to make nfs mounting by following the document of bootlin. I set the parameters as following;
setenv bootargs 'console=ttyS0,115200 root=/dev/nfs rw
nfsroot=192.168.0.1:/nfs,nfsvers=3,
ip=192.168.0.100:::::usb0 g_ether.dev_addr=f8:dc:7a:00:00:02
g_ether.host_addr=f8:dc:7a:00:00:01'

setenv bootcmd 'mmc dev 0; devnum=${mmcdev}; setenv devtype mmc;
mmc rescan; run loadimage; run findfdt; run mmcloados'
saveenv

it did not work, I get the following ;
[    8.007915] nfs: Unknown parameter 'ip'
[   18.407811] nfs: Unknown parameter 'ip'
[   38.887802] nfs: Unknown parameter 'ip'
[   68.967793] nfs: Unknown parameter 'ip'
[   99.047785] nfs: Unknown parameter 'ip'
[   99.051674] VFS: Unable to mount root fs via NFS.

any suggestions where should I look to fix it?

A: It is reading ip as a parameter of nfsroot:
setenv bootargs 'console=ttyS0,115200 root=/dev/nfs rw
nfsroot=192.168.0.1:/nfs,nfsvers=3,
                                  ^
                                  |
----------------------------------

ip=192.168.0.100:::::usb0 g_ether.dev_addr=f8:dc:7a:00:00:02
g_ether.host_addr=f8:dc:7a:00:00:01'

ip should be a separate option:
setenv bootargs 'console=ttyS0,115200 root=/dev/nfs rw ip=192.168.0.100:::::usb0 g_ether.dev_addr=f8:dc:7a:00:00:02
g_ether.host_addr=f8:dc:7a:00:00:01 nfsroot=192.168.0.1:/nfs,v3'


text:
Q: Partial differentiation using Coqelicot on Coq I want to partially differentiate functions which expects n arguments for arbitrary natural number n. I hope to differentiate arbitrary an argument only once and not the others.
Require Import Reals.
Open Scope R_scope.

Definition myFunc (x y z:R) :R:=
 x^2 + y^3 + z^4.

I expect function 3*(y^2) when I differentiate myFunc with y.
I know partial_derive in Coquelicot.
Definition partial_derive (m k : nat) (f : R → R → R) : R → R → R :=
  fun x y ⇒ Derive_n (fun t ⇒ Derive_n (fun z ⇒ f t z) k y) m x.

partial_derive can partially differentiate f:R → R → R, but not possible for arbitrary number of arguments.
I thought about using dependent type listR.
Inductive listR :nat -> Type:=
|RO : Euc 0
|Rn : forall {n}, R -> listR n -> listR (S n).

Notation "[ ]" := RO.
Notation "[ r1 , .. , r2 ]" := (Rn r1 .. ( Rn r2 RO ) .. ).
Infix ":::" := Rn (at level 60, right associativity).

Fixpoint partial_derive_nth {n} (k:nat) (f : listR n -> R) (e:listR n): listR n -> R:=

k specifies argument number to differentiate.
We can not define partial_derive_nth like partial_derive because we can not specify the name of arguments of fun in recursion.
Please tell me how to partially differentiate functions which has arbitrary number of arguments.

A: For your function myFunc, you can write the partial derivative like so:
Definition pdiv2_myFunc (x y z : R) :=
 Derive (fun y => myFunc x y z) y.

You can then prove that it has the value you expect for any choice of x, y, and z.  Most of the proof can be done automatically, thanks to the tactics provided in Coquelicot.
Lemma pdiv2_myFunc_value (x y z : R) :
   pdiv2_myFunc x y z = 3 * y ^ 2.
Proof.
unfold pdiv2_myFunc, myFunc.
apply is_derive_unique.
auto_derive; auto; ring.
Qed.

I am a bit surprised that the automatic tactic auto_derive does not handle a goal of the form Derive _ _ = _, so I have to apply theorem is_derive_unique myself.


text:
Q: xcolor command `\color` stops working in xelatex Test program:
\documentclass{article}
\usepackage{xcolor}
\begin{document}
\color{red}1
\color{blue}0
... many lines ...
\color{red}1
\color{blue}0
\end{document}

Test result:
Only first few lines are correctly colored. The rest is all blue.
Using \textcolor{...}{...} seems OK, but not with \color{...}.
The above code is MWE, with 200 repeats (400 lines) of 1 and 0. The bug appears when processed with xelatex but not pdflatex.

A: xdvipdfmx, the PDF driver for XeTeX, has a limited colour stack. Each time you use (say) \color{red}, it does \special{color push rgb 1 0 0} to push a colour to the stack, but since you don't end a group anywhere, that colour stays on the stack indefinitely (no \special{color pop} happens).
The xelatex program has an arguably bad default of running xdvipdfmx with -q, so that type of issue doesn't show up (because it isn't detected during the TeX run). If you run xelatex with xelatex --output-driver='xdvipdfmx' <file>.tex, then it will tell you:
xdvipdfmx:warning: Color stack overflow. Just ignore.

You need to use \color inside a group, or do \reset@color manually.
Here's a sample code that shows that:
\documentclass{article}
\usepackage{xcolor}
\newcount\cnta
\begin{document}
\loop
\color{red}\the\cnta\space
\advance\cnta1
\color{blue}\the\cnta\par
\advance\cnta1
\ifnum\cnta<150
\repeat
\end{document}


text:
Q: Retrofit2 обработка разных ответов от сервера Начал использовать retrofit2.
До этого по старинке парсил ответ в ручную.
У нас сервер на один запрос может вернуть два разных ответа в зависимости от ситуации на сервере, мобильное приложение должно отреагировать в зависимости от ответа.
Везде примеры как делают запрос на сервер и получают одну структуру данных в виде ответа.
А как обработать совершенно разные структуру от сервера?
Допустим полностью все данные о пользователе или структуру с описанием ошибки, которая ничего общего с структурой пользователя не имеет?
Буду признателен за небольшой пример. Спасибо!

A: Думаю, тут можно реализовать следующее: создать обертку для двух разных ответов, типа класс, который содержит внутри два возможных типа(класса), с возможностью проверки, какой тип ответа он содержит. Далее для Retrofit создать конвертер и преобразовать два разных ответа в один и вернуть его. Далее уже  в коде уже работать с оберткой, проверяя тип возвращенного ответа.
Я так предполагаю, что тут замешан RPC, когда может вернутся "нормальный" ответ, а при ошибке возвращается структура с информацией об ошибке, при этом код ответа будет 200.

A: Для того чтобы обработать ошибку при работе с Retrofit2 не обязательно создавать что-то новое или менять структуру ответа. У вас сервер может давать совершенно разные ответы, например:

*

*200 - все хорошо

*500 - проблемы на сервере

*400, 401, 402, 403 - проблема в том что вы отправляете или запрашиваете.

Вот как можно обработать негативный ответ сервера:
ResponseBody errorBody = response.errorBody();
try {
if (Objects.requireNonNull(errorBody).string().contains("refresh_token_expired")) {
}
if (Objects.requireNonNull(errorBody).string().contains("access_token_expired")) {
}
} catch (IOException e) {
e.printStackTrace();
 }

дальше вы прописываете необходимые действия при возникновении той или иной ошибки. Удачи :)

A: Самое универсальное решение: получайте результат от сервера в виде простой строки, без автоматической конвертации.
Правда придется брутфорсом перебирать все варианты конвертации строки: если преобразовалось в json - хорошо, пробуем преобразовать в gson (List<Items>, Car, Dog, Document и т.д.)
Не получилось преобразовать? Ищем ключевую подстроку (можно использовать regex) и определяем по ней, что к нам пришло. Парсим, парсим, парсим...
И т.д.


text:
Q: Delete temporary folder after returning using send_file() of flask python on Windows Server I am trying to delete a temporary folder where I save an image and do some processing on it and then return some results. I used shutil.rmtree(filepath) and it works correctly on Mac OS. However when I run it on Windows server, it fails with an error saying file is still in use.
I referred this question on stack overflow How to clean up temporary file used with send_file?
This answer using weak references helps in removing the error that was thrown on Windows, but the folder is still not deleted. Though it still works correctly on Mac OS.
How can I delete the temporary folder after the request has been completed on Windows system?
Here is my code snippet for your reference.
    def post(self):
    try:
        if 'photo' not in request.files:
            raise NoFilesError
        file = request.files['photo']
        print('file = ', file)
        if file.filename == '':
            raise NoFilesError
        if file and self._allowed_file(file.filename):
            filename = secure_filename(file.filename)
            dir_path = os.path.join(BaseAPIConfig.UPLOAD_FOLDER, get_timestamp())
            create_directory(dir_path)
            file_path = os.path.join(dir_path, filename)
            file.save(file_path)
            img_proc_main(dir_path, filename)
            image_filename = filename.rsplit('.', 1)[0]
            image_format = filename.rsplit('.', 1)[1]
            result_file = os.path.join(dir_path, image_filename + '_bb.' + image_format)
            response = make_response(send_file(result_file))
            file_remover = FileRemover()
            file_remover.cleanup_once_done(response, dir_path)
            return response
            ...

FileRemover class
class FileRemover(object):
    def __init__(self):
        self.weak_references = dict()  # weak_ref -> filepath to remove

    def cleanup_once_done(self, response, filepath):
        wr = weakref.ref(response, self._do_cleanup)
        self.weak_references[wr] = filepath

    def _do_cleanup(self, wr):
        filepath = self.weak_references[wr]
        print('Deleting %s' % filepath)
        shutil.rmtree(filepath, ignore_errors=True)

A: You are using ignore_errors=True, which hides away any exception that shutil.rmtree encounters.
There are many reasons why shutil.rmtree might fail to remove the directory—perhaps you simply don't have the correct permission on Windows. Setting ignore_errors to false will give you more indications of what's going on.


text:
Q: Rank of the matrix and adjugate relation 1) If matrix $\ A$ is of a size of $\ n (n>1)$, $\ A^*$ is it's adjugate, when $\ r_A < n - 1$, $\ A^*=$ _____.
2) If $\ A$ is a $\ 3X4 $ size matrix, $\ AA^T$ is ____ size symmetric matrix, $\ |A^TA|=$ _____.
In the first question I can only conduct that if $\ r_A < n - 1$ then there exist at least two rows of zeroes. But I don't really understand how it affects the adjugate. Something tells me that answer might be 0, but I don't really know how to show it.
In the second question the first blank is $\ 3$ obviously, but I don't know the answer for the second one.

A: 1) $A^*$ is formed from the cofactors of $A$. On the other hand, $r_A<n-1$ implies that all its minors of order $n-1$ are $0$. Since the cofactors are those minors (save for a sign), $A^*=0$.
2) $r_A\leq3$, and the rank of a product is less or equal than the minimum of the ranks of the matrices involved, so $r_{A^TA}\leq3$. As $A^TA$ is a $4\times 4$ matrix, we get that $A^TA$ is not full rank, so $|A^TA|=0$.


text:
Q: I have s str variable containing list of float values, all i want to convert into numpy array with type float64 in python s = "[-3.34 -0.34]"

s type is str and its size is 1
what is want is to convert this str into numpy float64 array into like this
s = [-3.34 -0.34]

A: np.array(list(map(float, s[1:-1].split())))

s[1:-1] will print out everything between the brackets as a string.
.split() will split the string at the spaces into a list of 2 strings.
map() will convert the strings into floats.
list() will convert the map object into a list.
np.array() will convert the list into a numpy array.
print(s[1:-1].split())
# "-3.34 -0.34"
print(map(float, s[1:-1].split()))
# <map object at 0x108146128>
print(list(map(float, s[1:-1].split())))
# [-3.34, -0.34]
print(np.array(list(map(float, s[1:-1].split()))))
# [-3.34 -0.34]

A: Not sure what you're looking for because there is no comma is your expression but, assuming that you just want to create an array, you can do this :
expr = "[-3.34, -0.34]"
s = eval(expr)


text:
Q: Groovy StreamingTemplateEngine gives error with withCredentials function I created the Jenkins pipeline which calls below function... It creates a Template variable with StreamingTemplateEngine object... But it gives an error
def call() {
    def name = "abc"
    def binding = [
        firstname: "Grace",
        lastname: "Hopper",
    ]

    def text = 'Dear <% out.print firstname %> ${lastname}'
    def template = new groovy.text.StreamingTemplateEngine().createTemplate(text)

    print template.make(binding)

    def response = template.make(binding)

    withCredentials([string(credentialsId: 'Token', variable: 'TOKEN')]) {
        println("test")
        println(response)
    }
}

Above code prints response successfully first time but at the end it gives below error
an exception which occurred:
        in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
        in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@3678d955
        in field com.cloudbees.groovy.cps.impl.CpsClosureDef.capture
        in object com.cloudbees.groovy.cps.impl.CpsClosureDef@23a3d63c
        in field com.cloudbees.groovy.cps.impl.CpsClosure.def
        in object org.jenkinsci.plugins.workflow.cps.CpsClosure2@6d8ad313
        in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures
        in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@76f2b368
        in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@76f2b368
Caused: java.io.NotSerializableException: groovy.text.StreamingTemplateEngine$StreamingTemplate

If I remove withCredentials function then it works fine.

A: Jenkins Pipeline runs Groovy code in the continuation-passing style (groovy-cps). It expects that every local variable is Serializable so it can safely serialize every computation and restore it in case of, e.g., Jenkins restart.
In case of using a non-serializable object, Jenkins Pipeline offers @NonCPS annotation that can be used with a method to mark that this part of code is not serializable and shouldn't be transformed to the CPS code interpretation.

"Pipeline scripts may mark designated methods with the annotation @NonCPS. These are then compiled normally (except for sandbox security checks), and so behave much like "binary" methods from the Java Platform, Groovy runtime, or Jenkins core or plugin code. @NonCPS methods may safely use non-Serializable objects as local variables, though they should not accept nonserializable parameters or return or store nonserializable values. You may not call regular (CPS-transformed) methods, or Pipeline steps, from a @NonCPS method, so they are best used for performing some calculations before passing a summary back to the main script. Note in particular that @Overrides of methods defined in binary classes, such as Object.toString(), should in general be marked @NonCPS since it will commonly be binary code calling them."

Source: https://github.com/jenkinsci/workflow-cps-plugin#technical-design

You can extract StreamingTemplateEngine part to the separate @NonCPS method that expects a template as text, and a map of bindings. Something like this should be safe to use:
import com.cloudbees.groovy.cps.NonCPS

def call() {
    def name = "abc"
    def binding = [
        firstname: "Grace",
        lastname: "Hopper",
    ]

    def text = 'Dear <% out.print firstname %> ${lastname}'

    def response = parseTemplate(text, binding)

    withCredentials([string(credentialsId: 'Token', variable: 'TOKEN')]) {
        println(response)
    }
}

@NonCPS
String parseTemplate(String text, Map bindings) {
    new groovy.text.StreamingTemplateEngine().createTemplate(text)
        .make(bindings)
        .toString()
}


text:
Q: JSON Literal Manupulation I have JSON literal as given below.
{
  "GB":[
        {"name":"Bob","score":9},
        {"name":"Joe","score":6},
        {"name":"Tom","score":7}
  ],
  "GP":[
        {"name":"Mahesh","score":19},
        {"name":"Anand","score":62},
        {"name":"Sawapnil","score":76}
  ]
}

How can edit or remove from above JSON. Like, If GB -> Score: 7 to Score: 73 and
remove GP -> {"name":"Anand","score":62}

A: You turn it into an array and then back to json.
var arr = $.map(obj, function(el) { return el });

arr['GB'][3]['score'] = 73;

var myJsonString = JSON.stringify(arr);

or as a javascript object:
var jsonobj = JSON.parse(json);

jsonobj.GB[3].score = 73;

var myJsonString = JSON.stringify(arr);


text:
Q: Pass fetch success response to child component I have two component parent and child.
I am passing callback function to child component like this.
<ChildComponent onFetchRecords={this.onFetchRecords} />

and inside child component I am calling this callback function like this.
this.props.onFetchRecords && this.props.onFetchRecords(0, 20).then(x => {
                // some code
            });

and on my parent component function body is like below:
    onFetchRecords(){
        return Client.sendJsonRequest("", "Records.json", "GET", "", "", this.handleResults, this.handleError, true, this.handleHttpError, "Reports");
      }

     handleResults(response){

     }

So as you can see onFetchRecords makes an fetch request to get specific file and then callback function handleResults gets called.
I want to pass the results to child components, is there any way to achieve the same?
I know, I can move whole fetch call to child itself but I don't want to do that because the callback function will keep on changing based on parent component and hence I want it to be configurable.

A: Instead of depending on the promise to pass you the updated result, you can pass the data to child using props
Render child like
<ChildComponent onFetchRecords={this.onFetchRecords}  records={this.state.records}/>

and in child call onFetchRecords
this.props.onFetchRecords && this.props.onFetchRecords(0, 20);

Now your fetch request in parent will be like
  onFetchRecords(){
    return Client.sendJsonRequest("", "Records.json", "GET", "", "", this.handleResults, this.handleError, true, this.handleHttpError, "Reports");
  }

 handleResults(response){
      this.setState({records: response});
 }

Now in child component if you want to take some action on prop change, you can implement componentDidUpdate method
componentDidUpdate(prevProps) {
   if(!_.isEqual(this.props.records, prevProps.records)) {
      // write your code here
   }
}


text:
Q: How to compare column values in Scheme I've never worked with scheme before.
I have to iterate over a table column to ensure all the values in the result set are the same. If all the values are equal, then I'll write they have been checked.
Lets say I have a db table called Car with a column called TirePressure. The select statement will return 4 TirePressure values. If the values are all the same, I need to write a result.
(if (zero? (gSelectOne stmt (string-append "SELECT TirePressure FROM Car WHERE VIN = "ABCDEF")))
     (if (= 48 (gGetInt (stmt "TirePressure")))
       (begin (gSetIntValue (mCtl "TiresChecked") 1))
    )

Please ignore the db violations, this is just an example.
Any help is appreciated.

A: An if is a special form (fancy lisp talk for non function, like if and while in any other language) that takes 3 expressions, a predicate, a consequent and an alternative. Like this:
(if predicate
    consequent
    alternative)

Every expression returns a value so if the predicate is not #f (thus true) the consequent is evaluated and is the result of the code. If not the evaluation of teh alternative is the result.
Imagine you want to check if the variables a, b, and c are zero you can do like this:
(= 0 a b c) ; ==> #t/#f

So imagine the have an expression that becomes a list of prerssures we can just make a variable res for it:
(define res '(0 0 0))
(if (apply = 0 res)
    "all zero"
    "not good")
; ==> "all zero"


text:
Q: MySQL: Reducing amount of open files So, I currently have a problem with my mySQL server opening far too many file handles.
This requires me to restart to server each day, as otherwise, I get the infamous "errno 24, too many open files" error.
I have already tried raising the system maximum count to 500k, but I still get that error.
At the time mySQL stops working, it uses about 384k file handles, far too many in my books.
System information:

VPS running on a Intel Xeon E5-2670 v3
12GB of DDR4 RAM
240GB SSD
Debian 8 64-bit, latest updates

More than enough ram.
my.cnf
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

[mysqld_safe]
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
explicit_defaults_for_timestamp

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address    = 127.0.0.1

# Fine tuning
max_allowed_packet = 16M
thread_stack       = 192K
thread_cache_size = 8
myisam_recover_options = BACKUP
max_connections = 384
key_buffer_size = 284M
tmp_table_size = 32M
max_heap_table_size = 32M

# Query cache
query_cache_type = 1
query_cache_limit = 1M
query_cache_size = 16M

# Join buffer
join_buffer_size = 600K
table_open_cache = 440

# InnoDB
innodb_buffer_pool_size = 4G
innodb_log_buffer_size = 32M

# Logging
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 10
log-error   = /var/log/mysql/error.log

# Other stuff
[isamchk]
key_buffer = 16M

[mysqldump]
quick
quote-names
max_allowed_packet = 16M

# Recommended in standard MySQL setup
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

I am looking for a way to reduce the amount of file handles used, not raise it.
Thanks!

A: SHOW VARIABLES LIKE 'open_files_limit';

That will reflect the OS's ulimit -n.  In some OSs, that limit is set too low.  Change it.
Then set table_open_cache to be about one-third of it.


text:
Q: AEM CQ5 servlet doesn't get called in local environment I'm fairly new to AEM development and I'm experiencing some problems in my local environment.
The code I'm using is the same that is currently on the server (where everything works just fine), so I guess there must be some wrong configuration on my side.
So I have this servlet that should be called when trying to download an asset:
@Component(metatype = false)
@Service
@Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"),
    @Property(name = "sling.servlet.methods", value = { "GET", "POST" }),
    @Property(name = "sling.servlet.selectors", value = "assets") })
public class AssetDownloadServlet extends SlingAllMethodsServlet

It is triggered by the "assets" selector, for example
http://localhost:4502/content/.assets.zip?path=content/folder/asset.jpg&_charset_=utf-8

Thing is, if I write an URL like this in the bar, it works just fine. The servlet gets called and downloads asset.jpg.
What isn't working is the Javascript code that when the user clicks on a button, builds the URL, puts it in a hidden form and then submits the form. In this case, the servlet doesn't get called at all (I put some breakpoints in debug mode to check) and the following page appears:
Status           200
Message          OK
Location         /content/aem/download
Parent Location  /content/aem
Path             /content/aem/download
Referer          http://localhost:4502/content/aem/download.html
ChangeLog

Go Back
Modified Resource
Parent of Modified Resource

As I said, the code shouldn't be at fault since it works on the server. I just don't even know where to look to understand what I'm doing wrong in local.
EDIT:
I opened a related question as the problem may be of another nature: CQ5 FormPanel sends HTTP POST in Chrome and HTTP GET in IE

A: As I see you don't have selectors in your url:
http://localhost:4502/content/assets.zip?path=content/folder/asset.jpg&_charset_=utf-8

Here I can see

*

*potocol+host: http://localhost:4502

*path to resource: /content/assets

*extension: .zip

*param1: path=content/folder/asset.jpg

*param2: charset=utf-8

If you want your servlet be triggered you should add selector (.assets between path and extension)
http://localhost:4502/content/assets.assets.zip?path=content/folder/asset.jpg&_charset_=utf-8

See more at documentation : Sling url decomposition


text:
Q: windows server 2003 - how to give rights for PowerUser for Services I have 6 windows servers 2003. However only 2 of them - when I connect to them as PowerUser - let me to open Services and manage them.
When I would log in to the server as Administrator, what I should change to to allow PowerUser to access Services. I could not find any security rights panel/window on Services.

A: There are several methods to do this. I prefer to use subinacl for smaller deployments:
Ex: SUBINACL /SERVICE \MachineName\ServiceName /GRANT=[DomainName]UserName[=Access]
See the MS KB here for more details: http://support.microsoft.com/kb/325349


text:
Q: Assertion failure leads to iPhone crashing when presenting modal view controller The error is as follows:

* Assertion failure in -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:], /SourceCache/UIKit_Sim/UIKit-1912.3/UIWindowController.m:188

When I click a button, it triggers my first presentModalViewController from the below function:
-(void)go{
    //this second presenting viewcontroller
    SinaWeiBoViewController *sinaviewController = [self.storyboard instantiateViewControllerWithIdentifier:@"sinaweibo"];

    [self presentModalViewController:sinaviewController animated:YES];
}

When this function runs, the second view is presented and a crash occurs. The demo code is downloadable here.

A: I am too get this error. And case in
self

value. Try set here another UIViewController class


text:
Q: emacs uses different indentation based on what's already in file I use 2-space indentation, no tabs.  When I open a file which already is indented with 8-spaces, that's what it continues to do.  I'd like emacs to change whats in the file (8-spaces) to my setting of 2-spaces.  Is there a way to do this?
This is how I've configured my tabs:
(setq-default indent-tabs-mode nil)
(setq-default tab-width 2)

If it's relevant, I'm working on python files.

A: Setting the tab-width controls how many characters the tab character will occupy when it is displayed. You need to set python-indent-offset. You should probably also do this in a mode hook as follows:
(add-hook 'python-mode-hook (lambda () (setq python-indent-offset 2)))

TAre you using python.el or python-mode.el? If you don't know, which version of emacs are you using? python-mode.el was the default in versions of emacs that were released prior to the 24.2. I only tested this on python.el so it may need to be tweaked for python-mode.el


text:
Q: Pass Angular Reactive FormControls to Children Components I have a parent component where I want to create and store my Reactive Form. There will be multiple Form Group instances in a Form Array. I want to pass the Form Controls from each Form Group to a Child Component but am having trouble figuring out how to do this.
Here's a Stackblitz demonstrating what I would like to do. Also, some fields will only apply to certain 'makes' of cars which is why i have the following line in my html:
<input type="text" *ngIf="car.make != 'ford'" formControlName="model">

I would like to move the 'Details' Form Group fields into the 'details-fields' child component but when I try to do that, it tells me that I don't have a Form Group instance so I know the parent Form Group is not registering in the child component. Any help is much appreciated.

A: It's not too tough, once you know what to look for. If you have never done it before, it can be a challenge. The error messages you get don't always help.
First, you want to add some things to your DetailsFields component. The new Inputs will allow you to pass in the instance of the form group you constructed in your parent component. The car and carIndex inputs will be used to pass in the values the child component will need in order to work like you have them now.
import { Component, OnInit, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
    selector: 'app-child',
    templateUrl: './details-fields.component.html',
    styleUrls: ['./details-fields.component.css']
})

export class DetailsFields implements OnInit {
    @Input() form: FormGroup;
    @Input() car: any;
    @Input() carIndex: number;

    ngOnInit() { }
}

Second, you want to move some of the template HTML you have in you parent component to the child component. The child component template (details-fields.component.html) will look like this in the end. The [formGroup]="form" in the first div is the real key here. That is what tells the child template what form group to use. You pass this from the parent in the code after this.

This car is a {{car.make}}

              <input type="text" formControlName="make">
              <input type="text" *ngIf="car.make != 'ford'" formControlName="model">
              <input type="number" formControlName="year">

              <input type="text" formControlName="color">

The parent component template will be only left with this. This is where you pass the carsForm form group to the child component, along with the car and the carIndex.

        <app-child [form]="carsForm" [car]="car" [carIndex]="i"></app-child>

The last thing I did was move the styles you had in the parent component out to the styles.css file, so all components could use them.
That's it! Really just moving some code around and adding some inputs so you can pass the child what it needs.


text:
Q: Neo4j auto-index, legacy index and label schema: differences for a relative-to-a-node full-text search this question is partially answered in
neo4j-legacy-indexes-and-auto-index-vs-new-label-bases-schema-indexes
and
the-difference-between-legacy-indexing-auto-indexing-and-the-new-indexing-approach
I can't comment on them yet and write a new thread here.
In my db, I have a legacy index 'topic' and label 'Topic'.
I know that:

*

*a. pattern MATCH (n:Label) will scan the nodes;

*b. pattern START (n:Index) will search on legacy index

*c. auto-index is a sort of legacy index and should gimme same results as (b) but it does not in my case

*d. START clause should be replaced by MATCH for "good practices".

I have inconsistent results between a. and b. (see below), cannot figure out how to use proper syntax with MATCH for searching on indexing insted of labels.
Here some examples:
1#
start n=node:topic('name:(keyword1 AND keyword2)') return n
6 rows, 3ms
start n=node:node_auto_index('name:(keyword1 AND keyword2)') return n;

0 rows
MATCH (n:Topic) where n.name =~ '(?i).*keyword1*.AND.*keyword2*.' return n;

0 rows, 10K ms
2#
start n=node:topic('name:(keyword1)') return n

212 rows, 122 ms [all coherent results containing substring keyword1]
start n=node:node_auto_index('name:(keyword1)') return n

0 rows
MATCH (n:Topic) where n.name =~ '(?i).*keyword1*.'return n

835 rows, 8K ms [also results not coherent, containing substring eyword]
MATCH (n:Topic) where n.name =~ 'keyword1' return n;

1 row, >6K ms [exact match]
MATCH (n:topic) where n.name =~ 'keyword1' return n;

no results (here I used an index 'topic' not a label 'Topic'!)
MATCH (node:topic) where node.name =~ 'keyword1' return node;

no results (attempt to use node "object" directly, as in auto-index syntax)
Could you help shed some light:

*

*What's the difference between a legacy index and auto-index and why inconsistent results between the two?

*How to use MATCH clause with Indexes rather than labels?
I want to reproduce results of full-text search.

*Which syntax to do a full-text search applied to ONLY the neighbor of a node, not the full-db? MATCH ? START clause? legacy-index ? label? I am confused.

A: The auto index (there is only one) is a manual (aka legacy) index having the name node_auto_index. This special index tracks changes to the graph by hooking into the transaction processing. So if you declared name as part of your auto index for nodes in the config, any change to a node having a name property is reflected to that index.
Note that auto indexes do not automatically populate on an existing dataset when you add e.g. a new property for auto indexing.
Note further that manual or auto indexes are totally independent of labels.
The only way to query a manual or auto index is by using the START clause:
START n=node:<indexName>(<lucene query expression>) // index query
START n=node:<indexName>(key='<value>') // exact index lookup

Schema indexes are completely different and are used in MATCH when appropriate.
A blog post of mine covers all the index capabilities of neo4j.
In general you use an index in graph databases to identify the start points for traversals. Once you've got a reference inside the graph you just follow relationships and do no longer do index lookups.
For full text indexing, see another blog post.
updates based on commets below
In fact MATCH (p:Topic {name: 'DNA'}) RETURN p and MATCH (n:Topic) where n.name = 'DNA' return n are both equvalent. Both result in the same query plan. If there is a schema index on label Topic and property name (by CREATE INDEX ON :Topic(name)) Cypher will implicitly use the schema index to find the specified node(s).
At the moment you cannot use full text searches based on schema indexes. Full text is only available in manual / auto indexing.
All the example you've provided with START n=node:topic(...) rely on a manual index. It's your responsibility to keep them in sync with your graph contents, so I assume the differences are due to inconsistent modifications in the graph and not reflecting the change to the manual index.
In any case if you use START n=node:topic(....) will never use a schema index.