Q: How to change convert different csv files into standard format? I have 2-3 .csv files with fields like Date, Amount, Transaction Description etc and all the csv files contains these fields but in shuffled order. I want a output file to with a standard order (like if I input the sample .csv file, then I can get the things in order in output file).
I tried to do it for one file by taking substrings from the .csv file (at that time I didn't know that other files have shuffled order fields).
I am kind of new, tell me if I am asking question in a good format!
Can I put a link for the sample input and output .csv file for the reference?
--> https://drive.google.com/drive/folders/1-NZi5OTMTbOWXAfCTsc-ahNYm1N5DG2g (just because it would be very hard to explain that how file looks like)
What I have done?
I have just tried to extract data from the fields using the BufferReader using split but it can only work for one type of file, I cant have a standard format using this!
Sorry for posting such a long code but what I have done is selected field from the file and copied them into output file corresponding to the standard fields in the output file.
Suggest me if there is any other method with which I can proceed.
File file = new File("C:\\Users\\R\\Desktop\\CSVDemo.csv");
        try {
            // create FileWriter object with file as parameter
            FileWriter outputfile = new FileWriter(file);

            CSVWriter writer = new CSVWriter(outputfile, ',',
                    CSVWriter.NO_QUOTE_CHARACTER,
                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                    CSVWriter.DEFAULT_LINE_END);

            // create a List which contains String array
            String[] header = { "Date", "Transaction Description", "Debit","Credit","Currency","CardName","Transaction","Location" };
            writer.writeNext(header);

            String splitBy = ",";
            BufferedReader br = new BufferedReader(new FileReader("G:\\US\\HDFC-Input-Case1.csv"));
            String line;
            String transaction = "",name  = "";
            while ((line = br.readLine()) != null) {
                // use comma as separator
                String[] cols = line.split(splitBy);

                if(cols.length == 2 && cols[1].equals("Domestic Transactions")) {
                    transaction  = "Domestic";
                    continue;
                }
                else if(cols.length == 2 && cols[1].equals("International Transactions")) {
                    transaction  = "International";
                    continue;
                }
                else if(cols.length == 2) {
                    name = cols[1];
                    continue;
                }
                else if(cols.length<1){
                    continue;
                }
                else if(cols.length>2) {
                    if(cols[0].contains("Date")){
                        continue;
                    }
                    String[] data1 = new String[header.length];
                        data1[0] = cols[0];
                        String curr ;
                        if(cols[1].substring(cols[1].length()-3).equals("USD") || cols[1].substring(cols[1].length()-3).equals("EUR")) {
                            data1[4] = cols[1].substring(cols[1].length()-3);
                            curr = cols[1].substring(0,cols[1].length()-4);
                            data1[1] = curr;
                        }
                        else {
                            data1[4] = "INR";
                            data1[1] = cols[1];
                        }

                        if(cols[2].contains("cr")){
                            data1[3] = cols[2].substring(0,cols[2].length()-2);
                            data1[2] = "0";
                        }
                        else {
                            data1[2] = cols[2];
                            data1[3] = "0";
                        }

                        data1[5] = name;
                        data1[6] = transaction;
                        writer.writeNext(data1);
                }
                System.out.println();
            }

            // closing writer connection
            writer.close();
        }

A: You can read the header of your input csv files first and find the indexes of required field in this given csv file.
Once you have required indexes for every header, read those fields using indexes in the standard order you want for your output csv file.
sample codes:
`CSVReader reader = new CSVReader(new FileReader(fileName ));
String[] header = reader.readNext();
List<String> list= Arrays.asList(header);
int indexOfFieldTransaction=list.indexOf("transaction");`

Now make a List and insert the field in order you want to write in output file.you will get -1 if the field you are trying to get index of is not present in the input file.


Q: Printing items selected from Knapsack Unbounded algorithm? I know how standard knapsack works, and i can afford to print the items selected in the 2D matrix, but from what i figured, unbounded knapsack is a 1D array. How do you print items selected by unbounded knapsack algorithm?

A: Unbounded Knapsack can be solved using 2D matrix, which will make printing the included items easy. The items included in the knapsack can be backtracked from the matrix in the same way as in 0/1 Knapsack.
After the dp[][] matrix is populated, this will print the included items:
// dp[val.length+1][sackWeight+1] is the matrix for caching.
// val[] is the array that stores the values of the objects
// and wt[] is the array that stores the weight of the corresponding objects.
int x = val.length, y = sackWeight;
    while (x > 0 && y > 0) {
        if (dp[x][y] == dp[x - 1][y])
            x--;
        else if (dp[x - 1][y] >= dp[x][y - wt[x - 1]] + val[x - 1])
            x--;
        else {
            System.out.println("including wt " + wt[x - 1] + " with value " + val[x - 1]);
            y -= wt[x - 1];
        }
    }

A: Assuming dp[][] is a matrix that is populated correctly.
We can backtrack to find selected weights

def print_selected_items(dp, weights, capacity):
    idxes_list = []
    print("Selected weights are: ", end='')
    n = len(weights)
    i = n - 1
    while i >= 0 and capacity >= 0:
        if i > 0 and dp[i][capacity] != dp[i - 1][capacity]:
            # include this item
            idxes_list.append(i)
            capacity -= weights[i]
        elif i == 0 and capacity >= weights[i]:
            # include this item
            idxes_list.append(i)
            capacity -= weights[i]
        else:
            i -= 1
    weights = [weights[idx] for idx in idxes_list]
    print(weights)
    return weights

For details on how to generate this DP array from bottom up DP.
def solve_knapsack_unbounded_bottomup(profits, weights, capacity):
    """
    :param profits:
    :param weights:
    :param capacity:
    :return:
    """
    n = len(profits)
    # base checks
    if capacity <= 0 or n == 0 or len(weights) != n:
        return 0
    dp = [[-1 for _ in range(capacity + 1)] for _ in range(n)]
    # populate the capacity=0 columns
    for i in range(n):
        dp[i][0] = 0
    # process all sub-arrays for all capacities
    for i in range(n):
        for c in range(1, capacity + 1):
            profit1, profit2 = 0, 0
            if weights[i] <= c:
                profit1 = profits[i] + dp[i][c - weights[i]]
            if i > 0:
                profit2 = dp[i - 1][c]
            dp[i][c] = max(profit1, profit2)
    # maximum profit will be in the bottom-right corner.
    print_selected_items(dp, weights, capacity)
    return dp[n - 1][capacity]


Q: printing float, preserving precision I am writing a program that prints floating point literals to be used inside another program.
How many digits do I need to print in order to preserve the precision of the original float?
Since a float has 24 * (log(2) / log(10)) = 7.2247199 decimal digits of precision, my initial thought was that printing 8 digits should be enough. But if I'm unlucky, those 0.2247199 get distributed to the left and to the right of the 7 significant digits, so I should probably print 9 decimal digits.
Is my analysis correct? Is 9 decimal digits enough for all cases? Like printf("%.9g", x);?
Is there a standard function that converts a float to a string with the minimum number of decimal digits required for that value, in the cases where 7 or 8 are enough, so I don't print unnecessary digits?
Note: I cannot use hexadecimal floating point literals, because standard C++ does not support them.

A:
24 * (log(2) / log(10)) = 7.2247199

That's pretty representative for the problem.  It makes no sense whatsoever to express the number of significant digits with an accuracy of 0.0000001 digits.  You are converting numbers to text for the benefit of a human, not a machine.  A human couldn't care less, and would much prefer, if you wrote

24 * (log(2) / log(10)) = 7

Trying to display 8 significant digits just generates random noise digits.  With non-zero odds that 7 is already too much because floating point error accumulates in calculations.  Above all, print numbers using a reasonable unit of measure.  People are interested in millimeters, grams, pounds, inches, etcetera.  No architect will care about the size of a window expressed more accurately than 1 mm.  No window manufacturing plant will promise a window sized as accurate as that.
Last but not least, you cannot ignore the accuracy of the numbers you feed into your program.  Measuring the speed of an unladen European swallow down to 7 digits is not possible.  It is roughly 11 meters per second, 2 digits at best.  So performing calculations on that speed and printing a result that has more significant digits produces nonsensical results that promise accuracy that isn't there.

A: If you have a C library that is conforming to C99 (and if your float types have a base that is a power of 2 :) the printf format character %a can print floating point values without lack of precision in hexadecimal form, and utilities as scanf and strod will be able to read them.

A: If the program is meant to be read by a computer, I would do the simple trick of using char* aliasing.

*

*alias float* to char*

*copy into an unsigned (or whatever unsigned type is sufficiently large) via char* aliasing

*print the unsigned value

Decoding is just reversing the process (and on most platform a direct reinterpret_cast can be used).

A: In order to guarantee that a binary->decimal->binary roundtrip recovers the original binary value, IEEE 754 requires

The original binary value will be preserved by converting to decimal and back again using:[10]

    5 decimal digits for binary16
    9 decimal digits for binary32
    17 decimal digits for binary64
    36 decimal digits for binary128

For other binary formats the required number of decimal digits is

    1 + ceiling(p*log10(2))

where p is the number of significant bits in the binary format, e.g. 24 bits for binary32.

In C, the functions you can use for these conversions are snprintf() and strtof/strtod/strtold().
Of course, in some cases even more digits can be useful (no, they are not always "noise", depending on the implementation of the decimal conversion routines such as snprintf() ). Consider e.g. printing dyadic fractions.

A: The floating-point-to-decimal conversion used in Java is guaranteed to be produce the least number of decimal digits beyond the decimal point needed to distinguish the number from its neighbors (more or less).
You can copy the algorithm from here: http://www.docjar.com/html/api/sun/misc/FloatingDecimal.java.html
Pay attention to the FloatingDecimal(float) constructor and the toJavaFormatString() method.

A: If you read these papers (see below), you'll find that there are some algorithm that print the minimum number of decimal digits such that the number can be re-interpreted unchanged (i.e. by scanf).
Since there might be several such numbers, the algorithm also pick the nearest decimal fraction to the original binary fraction (I named float value).
A pity that there's no such standard library in C.

*

*http://www.cs.indiana.edu/~burger/FP-Printing-PLDI96.pdf

*http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf

A: You can use sprintf. I am not sure whether this answers your question exactly though, but anyways, here is the sample code
#include <stdio.h>
int main( void )
{
float d_n = 123.45;
char s_cp[13] = { '\0' };
char s_cnp[4] = { '\0' };
/*
* with sprintf you need to make sure there's enough space
* declared in the array
*/
sprintf( s_cp, "%.2f", d_n );
printf( "%s\n", s_cp );
/*
* snprinft allows to control how much is read into array.
* it might have portable issues if you are not using C99
*/
snprintf( s_cnp, sizeof s_cnp - 1 , "%f", d_n );
printf( "%s\n", s_cnp );
getchar();
return 0;
}
/* output :
* 123.45
* 123
*/

A: With something like
def f(a):
    b=0
    while a != int(a): a*=2; b+=1
    return a, b

(which is Python) you should be able to get mantissa and exponent in a loss-free way.
In C, this would probably be
struct float_decomp {
    float mantissa;
    int exponent;
}

struct float_decomp decomp(float x)
{
    struct float_decomp ret = { .mantissa = x, .exponent = 0};
    while x != floor(x) {
        ret.mantissa *= 2;
        ret.exponent += 1;
    }
    return ret;
}

But be aware that still not all values can be represented in that way, it is just a quick shot which should give the idea, but probably needs improvement.


Q: How to redirect .htaccess My old website has 3 url's that lead to same place.
http://hemodialysis-krk.com/
http://www.hemodialysis-krk.com/
http://hemodialysis-krk.com/index.php?l=HR

I plan delete old website and put new one with totally different url's. Including index.html.
So what would be solution for that situation?
Should I 301 redirect some off them to index.html? Will first two automaticly link to new index.html file in public_html without redirecting?
Thanks.

A: Use this to redirect all traffic to new site using .htaccess of old sites.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} .*hemodialysis-krk.com
    RewriteRule (.*) http://www.newsite.com/ [R=301,L]
</IfModule>

Or create more rules, if you can map sections of pages from old to new site. If you use:
RewriteRule (.*) http://www.newsite.com/$1 [R=301,QSA,L]

original path and get query will be used in redirection too. This is always handy working on unique url to reach better position in search engines results.
EDIT:
If you need to redirect only urls, which don't exists anymore, then use (not tested):
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.*) / [R=301,L]
</IfModule>


Q: Scipy maximizing linear programming doesn't work I have the following:
ball = scipy.optimize.linprog(array([0,0,1]), A, b)

where
A =
array([[-1.0,  0.0,  1.0],
   [ 1.0,  0.0,  1.0],
   [ 0.0, -1.0,  1.0],
   [ 0.0,  1.0,  1.0]], dtype=float128)

b = array([ 0.0,  1.0,  0.0,  1.0], dtype=float128)

We can maximize this by hand to get the answer x = [0.5, 0.5, 0.5]. Yet scipy gives me
  status: 0
   slack: array([ 0.,  1.,  0.,  1.])
 success: True
     fun: -0.0
       x: array([ 0.,  0.,  0.])
 message: 'Optimization terminated successfully.'
     nit: 0

Which is simply the wrong answer! Is my code wrong, or did I find a bug?
EDIT:
To verify that the solution given by scipy is not optimal, do
np.all(np.dot(A, np.array([0.5,0.5,0.5])) <= b)

to see that my solution satisfies the constraints. Then note that
np.dot(np.array([0,0,1]), np.array([0.5,0.5,0.5])) > np.dot(np.array([0,0,1]), np.array([0,0,0]))

to see it is at least a better solution. In fact, it is the optimal solution.
EDIT 2:
scipy.__version__ = 0.16.0

A: According to the docs, linprog finds the minimum, while your proposed solution is the maximum.


Q: How to kill an android app from another app? i wanna know how to kill an android app from another, i'm developing a tasker, and i wanna to be able to kill an app selected by the user when an event occurs, i readed about Process.killProcess() but only allows me to kill apps in the same package, and that's not the idea! So, in my case, my kill section will request root rights, calling su before accept a kill request, but i don't know how to kill an app using a script! Anyones knows some script to do that??
EDIT:
The solution is in this thread:
ANDROID: How to gain root access in an Android application?
Please close.


Q: Reading an XML from a JavaFX application I would like to import an XML file via a pop-up window in my JavaFX application. After the importing, I would like to read it. For example I want to store, for every <testbus> the <index> and the <tb_name> in a List or something similar, where the <index> is the index of the List and the <tb_name> is the elementof the List. I also would like that for every <testbus> I can access the bitfields and their name. So I was thinking about List of List. I have found a java Library called JAXB that can parse XML files, but I do not know how to achieve what I want.
This is the XML file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testbuses>
    <testbus>
        <index>00</index>
        <tb_name>buffermngr00</tb_name>
            <bitfield0>
                <bitf_name>aaa_00</bitf_name>
            </bitfield0>
            <bitfield1>
                <bitf_name>aaa_01</bitf_name>
            </bitfield1>
            <bitfield2>
                <bitf_name>aaa_02</bitf_name>
            </bitfield2>
            <bitfield3>
                <bitf_name>aaa_03</bitf_name>
            </bitfield3>
            <bitfield4>
                <bitf_name>aaa_03</bitf_name>
            </bitfield4>
            <bitfield5>
                <bitf_name>aaa_04</bitf_name>
            </bitfield5>
            <bitfield6>
                <bitf_name>aaa_04</bitf_name>
            </bitfield6>
            <bitfield7>
                <bitf_name>aaa_05</bitf_name>
            </bitfield7>
    </testbus>
    <testbus>
        <index>01</index>
        <tb_name>buffermngr01</tb_name>
            <bitfield0>
                <bitf_name>bbb_00</bitf_name>
            </bitfield0>
            <bitfield1>
                <bitf_name>bbb_00</bitf_name>
            </bitfield1>
            <bitfield2>
                <bitf_name>bbb_00</bitf_name>
            </bitfield2>
            <bitfield3>
                <bitf_name>bbb_00</bitf_name>
            </bitfield3>
            <bitfield4>
                <bitf_name>bbb_01</bitf_name>
            </bitfield4>
            <bitfield5>
                <bitf_name>bbb_01</bitf_name>
            </bitfield5>
            <bitfield6>
                <bitf_name>bbb_02</bitf_name>
            </bitfield6>
            <bitfield7>
                <bitf_name>bbb_03</bitf_name>
            </bitfield7>
    </testbus>
</testbuses>

Anyway the structure of this XML is not strict, so if you have a suggestion for a better structure in order to make the reading easily, I will be happy to hear your solution.

A: For your xml provided in the XML.
First create a java POJO class with fields as:
String index;
String tb_name;
List<String> bitf_names;

Use the class below for that:
import java.util.List;

class TestBus {
        private String index;
        private String tb_name;
        private List<String> bitf_names;

        public String getIndex() {
            return index;
        }

        public void setIndex(String index) {
            this.index = index;
        }

        public String getTb_name() {
            return tb_name;
        }

        public void setTb_name(String tb_name) {
            this.tb_name = tb_name;
        }

        public List<String> getBitf_names() {
            return bitf_names;
        }

        public void setBitf_names(List<String> bitf_name) {
            this.bitf_names = bitf_name;
        }

        @Override
        public String toString() {
            return "TestBus [index=" + index + ", tb_name=" + tb_name + ", bitf_name=" + bitf_names + "]";
        }
    }

After that, use the code below to create a list of TestBus classes:
i.e List<TestBus> testBusList = new ArrayList<>();
Use this class for the complete code and logic:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile {
    public static List<TestBus> testBuses = new ArrayList<>();

    public static void main(String argv[]) {

        try {
            File fXmlFile = new File("D:\\ECLIPSE-WORKSPACE\\demo-xml-project\\src\\main\\resources\\testbus.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList testBusNodeList = doc.getElementsByTagName("testbus");

            for (int parameter = 0; parameter < testBusNodeList.getLength(); parameter++) {
                TestBus testBus = new TestBus();
                Node node = testBusNodeList.item(parameter);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node;
                    String index = eElement.getElementsByTagName("index").item(0).getTextContent();
                    String tb_name = eElement.getElementsByTagName("tb_name").item(0).getTextContent();
                    NodeList bitf_name = eElement.getElementsByTagName("bitf_name");
                    List<String> bitf_namesList = new ArrayList<>();
                    IntStream.range(0, bitf_name.getLength()).forEach(bName -> {
                        bitf_namesList.add(bitf_name.item(bName).getTextContent());
                    });
                    testBus.setIndex(index);
                    testBus.setTb_name(tb_name);
                    testBus.setBitf_names(bitf_namesList);

                    testBuses.add(testBus);
                }
            }
        } catch (Exception e) {
            System.out.println("!!!!!!!!  Exception while reading xml file :" + e.getMessage());
        }

        testBuses.forEach(bus -> System.out.println(bus));  // in single line
        System.out.println("###################################################");

        // using getters
        testBuses.forEach(bus -> {
            System.out.println("index = " + bus.getIndex());
            System.out.println("tb_name = " + bus.getTb_name());
            System.out.println("bitf_names = " + bus.getBitf_names());
            System.out.println("#####################################################");
        });
    }
}


Q: MySQL substatements with more than one column Given a fake example where there are contacts and for each contact there can be one or zero Sms records; I can do this
SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id.

But I it needs to show a row even if there is no SMS number for that contact.
I know of two ways to accomplish this. One is with a UNION of two selects
(SELECT Contact.id, Contact.name, Sms.provider, Sms.number FROM Contact, Sms WHERE Sms.contactId = Contact.id) UNION (SELECT id, name, null provider, null number FROM Contact WHERE (SELECT 1 FROM Sms WHERE contactId = Contact.id) IS NULL).

and another is two substatements
SELECT id, name, (SELECT provider FROM Sms WHERE contactId = Contact.id) provider, (SELECT number FROM Sms WHERE contactId = Contact.id) number FROM Contact

The UNION method requires going through the database twice and the substatements method requires two lookups on the same table.
I run into this often and I prefer to have all the code in MySQL and not to work with the software code to accomplish this. Working with MySQL usually turns out to be more efficient as well as simpler. Many of the real situations I work with involve large databases.
Is there a way to get two fields from a related table with one query?

A:
But I it needs to show a row even if
  there is no SMS number for that
  contact.

Then use a LEFT OUTER JOIN, which returns a row from the left table even if there is no corresponding row in the right table.
It's a good idea to learn to always use JOIN syntax instead of the pseudo-inner-join when you just list tables with commas.
SELECT
  Contact.id,
  Contact.name,
  Sms.provider,
  Sms.number
FROM
  Contact
LEFT OUTER JOIN
  Sms
ON
  Sms.contactId = Contact.id


Q: Javascript: prevent internal element "scrolling" in an element I have a script that has a div with a width larger than its' parent, with the parent being set to overflow: hidden;. I have javascript that is setting the left positioning of the big div to create "pages". You can click a link to move between pages.
All of that works great, but the problem is if you tab from one "page" element to another, it completely messes up all the left positioning to move between the pages.
You can recreate this bug in the fiddle I set up by setting your focus to one of the input boxes on page ONE and tabbing until it takes you to page two.
I've set up a demo here.
The code that is important is as follows:
HTML:

Page One

            [... Page 1 Content here...]

Page Two

            [... Page  Content here...]

CSS:
.form {
    width: 400px;
    position: relative;
    overflow: hidden;
    border: 1px solid #000;
    float: left;
}

    .pagesContainer {
        position: relative; /*Width set to 10,000 px in js
    }

    .form .page {
        width: 400px;
        float: left;
    }

JS:
slidePage: function(page, direction, currentPage) {
    if (direction == 'next') {
        var animationDirection = '-=';
        if (page.index() >= this.numPages) {
            return false;
        }
    }
    else if (direction == 'previous') {
        var animationDirection = '+=';
        if (page.index() < 0) {
            return false;
        }
    }

    //Get page height
    var height = page.height();
    this.heightElement.animate({
        height: height
    }, 600);

    //Clear active page
    this.page.removeClass('active');
    this.page.eq(page.index()).addClass('active');

    //Locate the exact page to skip to
    var slideWidth = page.outerWidth(true) * this.difference(this.currentPage.index(), page.index());

    this.container.animate({
        left: animationDirection + slideWidth
    }, 600);

    this.currentPage = page;
}

The primary problem is that whatever happens when you tab from say, an input box on page one to something on page 2, it takes you there, but css still considers you to be at left: 0px;. I've been looking all over for a solution but so far all google has revealed to me is how to stop scrollbar scrolling.
Any help or suggestions would be appreciated, thanks!
P.S. The html was set up like this so that if javascript is disabled it will still show up all on one page and still function properly.

A: I updated your fiddle with a fix for the first tab with the form: http://jsfiddle.net/E7u9X/1/
. Basically, what you can do is to focus on the first "tabbable" element in a tab after the last one gets blurred, like so:
$('.form input').last().blur(function(){
    $('.form input').first().focus();
});

(This is just an example, the first active element could be any other element)

A: Elements with overflow: hidden still have scrolling, just no scroll bars. This can be useful at times and annoying at others. This is why your position left is at zero, but your view of the element has changed. Set scrollLeft to zero when you change "pages", should do the trick.


Q: Query: table name specified more than once i'm trying to fix a vue filter. I have to change a query, but i can't find it in the laravel directory.
SELECT
    count(*) AS aggregate
FROM (
    SELECT
        ST_asGeoJSON(elements.geom) AS geometry
    FROM
        "elements"
    LEFT JOIN subsidies ON elements.subsidy_id = subsidies.id
    LEFT JOIN owners ON elements.owner_id = owners.id
    LEFT JOIN locations ON elements.location_id = locations.id
    LEFT JOIN element_type ON elements.element_type_id = element_type.id
    LEFT JOIN shapes ON elements.shape_id = shapes.id
    LEFT JOIN objectives ON elements.objective_id = objectives.id
    LEFT JOIN diameters ON elements.diameter_id = diameters.id
    LEFT JOIN maintenances ON maintenances.element_id = elements.id
    LEFT JOIN maintenances ON elements.id = maintenances.element_id
WHERE
    elements.organisation_id = 14
    and(elements.deleted_at) IS NULL
GROUP BY
    elements.id,
    maintenances.element_id,
    subsidies.id,
    owners.id,
    locations.id,
    element_type.id,
    shapes.id,
    objectives.id,
    diameters.id,
    maintenances.id
HAVING
    COUNT(element_id) < 1) count_row_table

above is the query that is executed when then checkbox is checked:

SQLSTATE[42712]: Duplicate alias: 7 ERROR: table name "maintenances" specified more that once (SQL: select count(*) as...

['parent_table' => 'elements', 'join_table' => 'element_type', 'filter_column' => 'element_type_id', 'filter_value' => 'element_type_' . \Config::get('app.locale')],
['parent_table' => 'elements', 'join_table' => 'shapes', 'filter_column' => 'shape_id', 'filter_value' => 'shape_' . \Config::get('app.locale')],
['parent_table' => 'elements', 'join_table' => 'objectives', 'filter_column' => 'objective_id', 'filter_value' => 'objective_' . \Config::get('app.locale')],
['parent_table' => 'elements', 'join_table' => 'diameters', 'filter_column' => 'diameter_id', 'filter_value' => 'diameter', 'order_by' => 'diameters.id'],
['parent_table' => 'element_flora', 'join_table' => 'flora', 'filter_column' => 'flora_id', 'filter_value' => 'flora_' . \Config::get('app.locale'), 'additional_wheres' => ['element_flora.deleted_at is null']],
['parent_table' => 'element_fauna', 'join_table' => 'fauna', 'filter_column' => 'fauna_id', 'filter_value' => 'fauna_' . \Config::get('app.locale'), 'additional_wheres' => ['element_fauna.approval_pending is not TRUE', 'element_fauna.deleted_at is null']],
['parent_table' => 'elements', 'join_table' => 'owners', 'filter_column' => 'owner_id', 'filter_value' => 'owner'],
['parent_table' => 'maintenances', 'join_table' => 'elements', 'filter_column' => 'id', 'filter_value' => 'id', 'havingRaw' => 'COUNT(maintenances.element_id) < 1', 'join_type' => 'left', 'filter_null' => true],
['parent_table' => 'elements', 'join_table' => 'projects', 'filter_column' => 'project_id', 'filter_value' => 'project', 'order_by' => 'projects.id'],


Q: Xamarin IOS file picker : unable to get selected file from icloud drive I've installed filepicker control from Nuget and added tried adding reference from MonoTouch10 folder and later from github to my xamarin.ios project.
FileData file = await CrossFilePicker.Current.PickFile();

if (file != null) { }

this is the code i added to my browse button, after selecting a file from iCloud drive, control never comes to "if condition".
and again when i click on browse button for second time, app crashes saying "only one operation can be active at a time".

A: Modifying the source code of the FilePickerImplementation plugin for the iOS platform worked, in this way:
using Foundation;
using MobileCoreServices;
using Plugin.FilePicker.Abstractions;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UIKit;
using System.Diagnostics;

namespace Plugin.FilePicker
{
    /// <summary>
    /// Implementation for FilePicker
    /// </summary>
    public class FilePickerImplementation : NSObject, IUIDocumentMenuDelegate, IFilePicker
    {
        private int _requestId;
        private TaskCompletionSource<FileData> _completionSource;

        /// <summary>
        /// Event which is invoked when a file was picked
        /// </summary>
        public EventHandler<FilePickerEventArgs> Handler
        {
            get;
            set;
        }

        private void OnFilePicked(FilePickerEventArgs e)
        {
            Handler?.Invoke(null, e);
        }

        public void DidPickDocumentPicker(UIDocumentMenuViewController documentMenu, UIDocumentPickerViewController documentPicker)
        {
            documentPicker.DidPickDocument += DocumentPicker_DidPickDocument;
            documentPicker.WasCancelled += DocumentPicker_WasCancelled;
            documentPicker.DidPickDocumentAtUrls += DocumentPicker_DidPickDocumentAtUrls;
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(documentPicker, true, null);
        }

        private void DocumentPicker_DidPickDocumentAtUrls(object sender, UIDocumentPickedAtUrlsEventArgs e)
        {
            var control = (UIDocumentPickerViewController)sender;
            foreach (var url in e.Urls)
                DocumentPicker_DidPickDocument(control, new UIDocumentPickedEventArgs(url));

            control.Dispose();
        }

        private void DocumentPicker_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
        {
            var securityEnabled = e.Url.StartAccessingSecurityScopedResource();
            var doc = new UIDocument(e.Url);
            var data = NSData.FromUrl(e.Url);
            var dataBytes = new byte[data.Length];

            System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

            string filename = doc.LocalizedName;
            string pathname = doc.FileUrl?.ToString();

            // iCloud drive can return null for LocalizedName.
            if (filename == null)
            {
                // Retrieve actual filename by taking the last entry after / in FileURL.
                // e.g. /path/to/file.ext -> file.ext

                // filesplit is either:
                // 0 (pathname is null, or last / is at position 0)
                // -1 (no / in pathname)
                // positive int (last occurence of / in string)
                var filesplit = pathname?.LastIndexOf('/') ?? 0;

                filename = pathname?.Substring(filesplit + 1);
            }

            OnFilePicked(new FilePickerEventArgs(dataBytes, filename, pathname));
        }

        /// <summary>
        /// Handles when the file picker was cancelled. Either in the
        /// popup menu or later on.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DocumentPicker_WasCancelled(object sender, EventArgs e)
        {
            {
                var tcs = Interlocked.Exchange(ref _completionSource, null);
                tcs.SetResult(null);
            }
        }

        /// <summary>
        /// Lets the user pick a file with the systems default file picker
        /// For iOS iCloud drive needs to be configured
        /// </summary>
        /// <returns></returns>
        public async Task<FileData> PickFile()
        {
            var media = await TakeMediaAsync();

            return media;
        }

        private Task<FileData> TakeMediaAsync()
        {
            var id = GetRequestId();

            var ntcs = new TaskCompletionSource<FileData>(id);

            if (Interlocked.CompareExchange(ref _completionSource, ntcs, null) != null)
                throw new InvalidOperationException("Only one operation can be active at a time");

            var allowedUtis = new string[] {
                UTType.UTF8PlainText,
                UTType.PlainText,
                UTType.RTF,
                UTType.PNG,
                UTType.Text,
                UTType.PDF,
                UTType.Image,
                UTType.UTF16PlainText,
                UTType.FileURL
            };

            var importMenu =
                new UIDocumentMenuViewController(allowedUtis, UIDocumentPickerMode.Import)
                {
                    Delegate = this,
                    ModalPresentationStyle = UIModalPresentationStyle.Popover
                };

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(importMenu, true, null);

            var presPopover = importMenu.PopoverPresentationController;

            if (presPopover != null)
            {
                presPopover.SourceView = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
                presPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
            }

            Handler = null;

            Handler = (s, e) => {
                var tcs = Interlocked.Exchange(ref _completionSource, null);

                tcs?.SetResult(new FileData(e.FilePath, e.FileName, () => { var url = new Foundation.NSUrl(e.FilePath); return new FileStream(url.Path, FileMode.Open, FileAccess.Read); }));
            };

            return _completionSource.Task;
        }

        public void WasCancelled(UIDocumentMenuViewController documentMenu)
        {
            var tcs = Interlocked.Exchange(ref _completionSource, null);

            tcs?.SetResult(null);
        }

        private int GetRequestId()
        {
            var id = _requestId;

            if (_requestId == int.MaxValue)
                _requestId = 0;
            else
                _requestId++;

            return id;
        }

        public async Task<bool> SaveFile(FileData fileToSave)
        {
            try
            {
                var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var fileName = Path.Combine(documents, fileToSave.FileName);

                File.WriteAllBytes(fileName, fileToSave.DataArray);

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public void OpenFile(NSUrl fileUrl)
        {
            var docControl = UIDocumentInteractionController.FromUrl(fileUrl);

            var window = UIApplication.SharedApplication.KeyWindow;
            var subViews = window.Subviews;
            var lastView = subViews.Last();
            var frame = lastView.Frame;

            docControl.PresentOpenInMenu(frame, lastView, true);
        }

        public void OpenFile(string fileToOpen)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var fileName = Path.Combine(documents, fileToOpen);

            if (NSFileManager.DefaultManager.FileExists(fileName))
            {
                var url = new NSUrl(fileName, true);
                OpenFile(url);
            }
        }

        public async void OpenFile(FileData fileToOpen)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var fileName = Path.Combine(documents, fileToOpen.FileName);

            if (NSFileManager.DefaultManager.FileExists(fileName))
            {
                var url = new NSUrl(fileName, true);

                OpenFile(url);
            }
            else
            {
                await SaveFile(fileToOpen);
                OpenFile(fileToOpen);
            }
        }
    }
}

A: To answer my own question, i customized in plugin, like

*

*Used DocumentPicker_DidPickDocumentAtUrls event instead of DocumentPicker_DidPickDocument.

*while returning selected file used
 new FileData(e.FilePath, e.FileName, () =>
        {
            var url = new Foundation.NSUrl(e.FilePath);
            return new FileStream(url.Path, FileMode.Open, FileAccess.Read);
        })

This solved my issue. Thanks.

A: There are several forks of the FilePicker Xamarin plugin. I recommend the following project, since it's the most actively maintained one:
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows (note: I'm one of the contributors to the project).
With this version of the plugin file picking should work. The example code from sandeep's answer was already incorporated into the latest version of the plugin. Be sure to read the README.md's Troubleshooting page in case you're getting problems.


Q: Creating a .jar in Android I have a Android project with some classes that I would like to compress to a JAR.
I create the JAR by right clicking my project - export - JAR - and the JAR gets created without any warnings.
I can access all classes from the JAR in my code but when I try to build the project get this exception :
java.lang.NoClassDefFoundError: name.of.class.in.package

Does anyone know what resources should be exported with the JAR? The options you get is
.class path
.prject
AndroidManifest.xml
proguard.cfg
project.properties

Right now I have included all of the above.

Making the JAR into a library project is not an option. And just to make it clear I don't have anything in the RES folder of my JAR project.

A: Just add your JAR to classpath or build your project with Maven and include dependencies

A: Open the project properties -> Java Build Path -> Order and Export and check item Android Dependencies are checked to be exported to the result APK.
And if .jar exist in Library tab under Android Dependencies item.
If you have .jar in the "libs" folder it should be included by default.

A: Try generating the jar in a different way. Basically jar is a zipped file of all class files with an extension of .jar.

*

*Select all your class files that needs to be included in a jar file.

*Right click and send to compressed (Zip File).

*you will have a zipped file which will contain all the class files.

*Rename this zipped file with having an extension .jar

Now include this jar file into your project whichever you want to use.
Or if you want to zip all the files by a different method then make sure all the files are zipped together without a folder. So when you unzip the files you should get all the files without contained in a folder.

A: It looks similar with this topic. Follow the very clear instructions written by Russ Bateman.


Q: Changing focus from one input to the next with a barcode scanner I am using a barcode scanner to enter data into input fields on a webpage. I set up the form and autofocus on the first input field. When the first barcode is entered into the first input field I would like focus to jump to the next input field. However, as soon as I enter the first barcode the form 'submits'. Here is the html I am using:
    <form id="barcode1" name="barcode" method="Post" action="#">

          Barcode 1
          <input id="S1" class="bcode" type="text" name="S1" autofocus/>
          Barcode 2
          <input id="S2" class="bcode" type="text" name="S2" />
          Barcode 3
          <input id="S3" class="bcode" type="text" name="S3" />

<input type="submit" name="Submit" value="Submit">

    </form>

I have tried solutions from similar SO questions here and [here] (http://jsfiddle.net/davidThomas/ZmAEG/), but they don't seem to work.
Ideally I would like to have a solution something like this (the second link above), so please let me know where or why this is not working and what I can do to fix it.
    $('form').on('keypress','input',function(e){
        var eClassName = this.className,
            index = $(this).index('.' + eClassName) + 1;
        if (e.which === 13){
            e.preventDefault();
            $('input.' + eClassName)
                .eq(index)
                .focus();
        }
    });

A: If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB.
It seems like, by default, your scanner is trailing with an ENTER (carriage return).
Another option would be to also check for a LF (decimal 10) in your javascript code.

A: You need to return false in order to prevent the enter key from submitting the form.
The answer to this question will help you: Prevent form submission with enter key
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
        return false;
    }
});

No need to make any changes to your bar scanner.

A: Looks like your function will never get called because browser submits the form on Enter. You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first.
$( "form" ).submit(function( event ) {
  if(/*all req. fields are filled -> submit the form*/)
     $(this).submit();
  event.preventDefault();
});


Q: Struts 2 token is not working with display tag pagination I have a Struts 2 application, I have created some reports with display tag  pagination, it works fine but when I apply CSRF token to that page, only first page displays properly and when I try to navigate other paginated pages application shows invalid.token error.
Can anyone please suggest how to apply CSRF token with display tag ?


Q: Facebook php ads sdk CurlLogger.php Warning: fwrite() expects parameter 1 to be resource, string given in /var/www/myapp/vendor/facebook/php-ads-sdk/src/FacebookAds/Logger/CurlLogger.php on line 182

I have this error... how fix that ?  and this code is in on that line
fwrite($this->handle, $buffer.PHP_EOL.PHP_EOL);

I tried to debug and return this:
curl -G \ -d 'level=account' \ -d 'filtering=[]' \ -d 'breakdowns=["age","gender"]' \ -d 'time_range={"since":"2017-09-06","until":"2017-10-06"}' \ -d 'fields=results,result_rate,reach,frequency,impressions,delivery,social_reach,social_impressions,total_actions,total_unique_actions,relevance_score:score,relevance_score:positive_feedback,relevance_score:negative_feedback,spend,today_spend,cost_per_result,cpp,cpm,cost_per_total_action,actions:page_engagement,actions:like,actions:mention,actions:tab_view,actions:comment,actions:post_engagement,actions:post_reaction,actions:post,actions:photo_view,actions:rsvp,actions:receive_offer,actions:checkin,cost_per_action_type:page_engagement,cost_per_action_type:like,cost_per_action_type:mention,cost_per_action_type:tab_view,cost_per_action_type:comment,cost_per_action_type:post_engagement,cost_per_action_type:post_reaction,cost_per_action_type:post,cost_per_action_type:photo_view,cost_per_action_type:rsvp,cost_per_action_type:receive_offer,cost_per_action_type:checkin,actions:video_view,video_10_sec_watched_actions:video_view,video_30_sec_watched_actions:video_view,video_p25_watched_actions:video_view,video_p50_watched_actions:video_view,video_p75_watched_actions:video_view,video_p95_watched_actions:video_view,video_p100_watched_actions:video_view,video_avg_time_watched_actions:video_view,video_avg_percent_watched_actions:video_view,canvas_avg_view_time,canvas_avg_view_percent,canvas_component_avg_pct_view:canvas_view,cost_per_action_type:video_view,cost_per_10_sec_video_view:video_view,actions:link_click,unique_actions:link_click,outbound_clicks:outbound_click,website_ctr:link_click,unique_link_clicks_ctr,call_to_action_clicks,clicks,unique_clicks,ctr,unique_ctr,social_clicks,unique_social_clicks,cost_per_action_type:link_click,cost_per_unique_action_type:link_click,cpc,cost_per_unique_click,estimated_ad_recallers,estimated_ad_recall_rate,cost_per_estimated_ad_recallers' \ -d 'access_token=aaaaaaaaa' \ -d 'appsecret_proof=aaaaaa' \ https://graph.facebook.com/v2.8/act_aaaaaaa/insights

Code of my file:
   <?php

require __DIR__ . '/vendor/autoload.php';

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdsInsights;
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;

$access_token = 'hidden';
$ad_account_id = 'hidden';
$app_secret = 'hidden';

$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());

$fields = array(
  'actions:link_click',
  'unique_actions:link_click',
  'clicks',
);
$params = array(
  'level' => 'account',
  'filtering' => array(),
  'breakdowns' => array('age','gender'),
  'time_range' => array('since' => '2017-09-06','until' => '2017-10-06'),
);
echo json_encode((new AdAccount($ad_account_id))->getInsights($fields,$params)->getResponse()->getContent(), JSON_PRETTY_PRINT);

This code is generated by facebook  marketing api
Screenshot here https://prnt.sc/gtqbf5 and use php php 5.6.3


Q: How do you convert between polar coordinates and cartesian coordinates assuming north is zero radians? I've been trying to make a simple physics engine for games. I am well aware that this is re-inventing the wheel but it's more of a learning exercise than anything else. I never expect it to be as complete as box2d for instance.
I'm having issues with my implementation of 2d Vectors. The issue is related to the fact that in the game world I want to represent north as being zero radians and east as being 1/2 PI Radians, or 0 and 90 degrees respectively. However in mathematics (or maybe more specifically the Math class of Java), I believe trigonometry functions like sine and cosine assume that "east" is zero radians and I think north is 1/2 PI Radians?
Anyway I've written a small version of my vector class that only demonstrates the faulty code.
public class Vector {
    private final double x;
    private final double y;

    public Vector(double xIn, double yIn) {
        x = xIn;
        y = yIn;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getR() {
        return Math.sqrt((x * x) + (y * y));
    }

    public double getTheta() {
        return Math.atan(y / x);
    }

    public double bearingTo(Vector target) {
        return (Math.atan2(target.getY() - y, target.getX() - x));
    }

    public static Vector fromPolar(double magnitude, double angle) {
        return new Vector(magnitude * Math.cos(angle),
                          magnitude * Math.sin(angle));
    }
}

And here is the test code to demonstrate the issue:
public class SOQuestion {
public static void main(String[] args) {
    //This works just fine
    Vector origin = new Vector(0, 0);
    Vector target = new Vector(10, 10);

    double expected = Math.PI * 0.25;
    double actual = origin.bearingTo(target);

    System.out.println("Expected: " + expected);
    System.out.println("Actual: " + actual);

    //This doesn't work
    origin = new Vector(0, 0);
    target = new Vector(10, 0);

    expected = Math.PI * 0.5; //90 degrees, or east.
    actual = origin.bearingTo(target); //Of course this is going to be zero, because in mathematics right is zero

    System.out.println("Expected: " + expected);
    System.out.println("Actual: " + actual);

    //This doesn't work either
    Vector secondTest = Vector.fromPolar(100, Math.PI * 0.5); // set the vector to the cartesian coordinates of (100,0)
    System.out.println("X: " + secondTest.getX()); //X ends up being basically zero
    System.out.println("Y: " + secondTest.getY()); //Y ends up being 100
} }

The requirements are:

*

*fromPolar(magnitude,angle) should return a vector with x and y initialized to the appropriate values assuming north is at zero radians and east is at 1/2 PI radians. for example fromPolar(10,PI) should construct a vector with x: 0 and y: -1

*getTheta() should return a value greater than or equal to zero and less than 2 PI. Theta is the angular component of the vector it's called on. For example a vector with x:10 and y:10 would return a value of 1/4 PI when getTheta() is called.

*bearingTo(target) should return a value that is greater than or equal to zero and less than 2 PI. The value represents the bearing to another vector.
The test code demonstrates that when you try to get the bearing of one point at (0,0) to another point at (10,0), it doesn't produce the intended result, it should be 90 degrees or 1/2 PI Radians.
Likewise, trying to initialize a vector from polar coordinates sets the x and y coordinate to unexpected values. I'm trying to avoid saying "incorrect values" since it' not incorrect, it just doesn't meet the requirements.
I've messed around with the code a lot, adding fractions of PI here or taking it away there, switching sine and cosine, but all of these things only fix parts of the problem and never the whole problem.
Finally I made a version of this code that can be executed online  http://tpcg.io/OYVB5Q

A: Typical polar coordinates 0 points to the East and they go counter-clockwise. Your coordinates start at the North and probably go clockwise. The simplest way to fix you code is to first to the conversion between angles using this formula:
flippedAngle = π/2 - originalAngle

This formula is symmetrical in that it converts both ways between "your" and "standard" coordinates. So if you change your code to:
    public double bearingTo(Vector target) {
        return Math.PI/2 - (Math.atan2(target.getY() - y, target.getX() - x));
    }

    public static Vector fromPolar(double magnitude, double angle) {
        double flippedAngle = Math.PI/2 - angle;
        return new Vector(magnitude * Math.cos(flippedAngle),
                magnitude * Math.sin(flippedAngle));
    }

It starts to work as your tests suggest. You can also apply some trigonometry knowledge to not do this Math.PI/2 - angle calculation but I'm not sure if this really makes the code clearer.
If you want your "bearing" to be in the [0, 2*π] range (i.e. always non-negative), you can use this version of bearingTo (also fixed theta):
public class Vector {
    private final double x;
    private final double y;

    public Vector(double xIn, double yIn) {
        x = xIn;
        y = yIn;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getR() {
        return Math.sqrt((x * x) + (y * y));
    }

    public double getTheta() {
        return flippedAtan2(y, x);
    }

    public double bearingTo(Vector target) {
        return flippedAtan2(target.getY() - y, target.getX() - x);
    }

    public static Vector fromPolar(double magnitude, double angle) {
        double flippedAngle = flipAngle(angle);
        return new Vector(magnitude * Math.cos(flippedAngle),
                magnitude * Math.sin(flippedAngle));
    }

    // flip the angle between 0 is the East + counter-clockwise and 0 is the North + clockwise
    // and vice versa
    private static double flipAngle(double angle) {
        return Math.PI / 2 - angle;
    }

    private static double flippedAtan2(double y, double x) {
        double angle = Math.atan2(y, x);
        double flippedAngle = flipAngle(angle);
        //  additionally put the angle into [0; 2*Pi) range from its [-pi; +pi] range
        return (flippedAngle >= 0) ? flippedAngle : flippedAngle + 2 * Math.PI;
    }
}


Q: How to use pair correctly in C++ I am trying to insert an object into a map. You can ignore most of the code here, but I'll include it to help. It's the line mymap.insert(pair(name, myobj(num1, num2))); That is giving me the error.
struct ap_pair {
    ap_pair(float tp, float tm) : total_price(tp), total_amount(tm) {};
    ap_pair & operator+=(const ap_pair &);
    float total_price;
    float total_amount;
};

void APC :: compute_total ()
{

    string name;
    map<string, ap_pair> :: iterator my_it;
    float num1, num2, num3;

    while (!fs.eof() )
    {
        fs >> name >> num1 >> num2; //read in file

        ap_pair myobj(num1, num2); //send the weight/count and per unit price ap_pair

        my_it = mymap.find(name); //returns iterator

        if (fs.eof()) break; //makes it so the last line is not repeated

    mymap.insert(pair<string,ap_pair>(name, myobj(num1, num2))); //ERROR IS HERE

        num3= num1*num2;
        total_amount+=num1;
        total_price+= num3;

    }

}

I am getting an error when compiling saying " error: no match for call to '(ap_pair) (float&, float&)". Why is that? What is wrong with doing what I did? I've been working on this for over an hour with no solution in sight. Any ideas? I can give some more ideas of what I am trying to do if needed. I think this might be a simple syntax issue I am looking over though.

A: myobj(num1, num2)

This attempts to call your myobj object like a functor. Instead you just want to pass myobj:
mymap.insert(pair<string,ap_pair>(name, myobj));


Q: Thread Pool of workers in a Window service? I'm creating a Windows service with 2 separate components:
1 component creates jobs and inserts them to the database (1 thread)
The 2nd component processes these jobs (multiple FIXED # of threads in a thread pool)
These 2 components will always run as long as the service is running.
What I'm stuck on is determining how to implement this thread pool. I've done some research, and there seems to be many ways of doing this such as creating a class that overriddes the method "ThreadPoolCallback", and using ThreadPool.QueueUserWorkItem to queue a work item. http://msdn.microsoft.com/en-us/library/3dasc8as.aspx
However in the example given, it doesn't seem to fit my scenario. I want to create a FIXED number of threads in a thread pool initially. Then feed it jobs to process. How do I do this?
// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
    int threadIndex = (int)threadContext;
    Console.WriteLine("thread {0} started...", threadIndex);
    _fibOfN = Calculate(_n);
    Console.WriteLine("thread {0} result calculated...", threadIndex);
    _doneEvent.Set();
}

Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
const int FibonacciCalculations = 10;

for (int i = 0; i < FibonacciCalculations; i++)
{
      ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
}

A: Create a BlockingCollection of work items. The thread that creates jobs adds them to this collection.
Create a fixed number of persistent threads that read items from that BlockingCollection and process them. Something like:
BlockingCollection<WorkItem> WorkItems = new BlockingCollection<WorkItem>();

void WorkerThreadProc()
{
    foreach (var item in WorkItems.GetConsumingEnumerable())
    {
        // process item
    }
}

Multiple worker threads can be doing that concurrently. BlockingCollection supports multiple readers and writers, so there's no concurrency problems that you have to deal with.
See my blog post Simple Multithreading, part 2 for an example that uses one consumer and one producer. Adding multiple consumers is a very simple matter of spinning up a new task for each consumer.
Another way to do it is to use a semaphore that controls how many jobs are currently being processed. I show how to do that in this answer. However, I think the shared BlockingCollection is in general a better solution.

A: The .NET thread pool isn't really designed for a fixed number of threads. It's designed to use the resources of the machine in the best way possible to perform multiple relatively small jobs.
Maybe a better solution for you would be to instantiate a fixed number of BackgroundWorkers instead? There are some reasonable BW examples.


Q: How to edit NavItem of Navbar component in Bootstrap Studio? Problem: I am using Stylish Portfolio template to design a quick website in Bootstrap Studio. I am unable to edit the default NavItem (Home, About, Services and so on) from the Navbar component as shown in image below.

Other components can be easily edited by double clicking on that component. But, the NavBar is hidden by default and shows only when we click on a hamburger icon. So, I am unable to edit the default fields of NavBar.
Here is the screenshot of the Bootstrap Studio editor.

What I have tried: By converting the component into HTML by Convert to HTML option, Bootstrap Studio gives the corresponding raw HTML file to edit and I was able to change the values from there. But, I think there must be a better way to edit the elements directly in Bootstrap studio instead. What am I missing? Please help!

A: I couldn't find a way to make the NavBar visible for editing. But, a way around is to double click on the NavItem component and type the text you want for NavItem can change the NavItem.

A: Click on "Show Toolbar" then "Open", this will show  the items.


Q: SQL How to find average of many sums of groups only if the groups follow certain rules Here is my current code:
SELECT
AVG(famTotal)

FROM `OmniHealth.new2015Data`, (
SELECT
SUM( TOTEXP15 ) as famTotal
FROM `OmniHealth.new2015Data`

GROUP BY DUID
)
WHERE BMINDX53 BETWEEN 0 AND 25 AND
ADSMOK42 = -1 AND
FCSZ1231 = 7

What I want to do is find the average cost per family where the family has all members with BMI between 0 and 25, don't smoke, and the family is an arbitrary size.
The spending data is on a per person basis in the table, so I'm trying to sum it based on the "dwelling unit ID" (DUID) being the same for all of the people, and then averaging the total per family as long as the family only has the properties I stated in the last paragraph.
Thank you for the replies! I'm new at SQL.

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT DUID, AVG(TOTEXP15) AS famAverage
FROM `OmniHealth.new2015Data`
GROUP BY DUID
HAVING MIN(BMINDX53) >=0 AND MAX(BMINDX53) <=25
AND MIN(ADSMOK42) = -1 AND MAX(ADSMOK42) = -1
AND MIN(FCSZ1231) = 7 AND MAX(FCSZ1231) = 7

A: Consider joining two aggregate query derived tables that matches on count to align all household members to all household members with specific conditions.
SELECT AVG(t1.famTotal) as famTotal

FROM
  (SELECT DUID, Count(*) As GrpCount, SUM(TOTEXP15) as famTotal
   FROM `OmniHealth.new2015Data`
   GROUP BY DUID) As t1

INNER JOIN

  (SELECT DUID, Count(*) As GrpCount
   FROM `OmniHealth.new2015Data`
   WHERE BMINDX53 BETWEEN 0 AND 25
     AND ADSMOK42 = -1
     AND FCSZ1231 = 7
   GROUP BY DUID) As t2

ON t1.DUID = t2.DUID AND t1.GrpCount = t2.GrpCount


Q: How to restrict the acess to a few users in pyTelegramBotAPI? I'm using telebot (https://github.com/eternnoir/pyTelegramBotAPI) to create a bot to send photos to its users. The point is I didn't see a way to restrict the access to this bot as I intend to share private images through this bot.
I read in this forum that through python-telegram-bot there is a way to limit the access from the sender's message (How To Limit Access To A Telegram Bot), but I didn't know if via pyTelegramBotAPI it is possible.
Do you know how can I solve it?

A: A bit late tot the party - perhaps for future post readers.  You can wrap the function to disallow access.
An example below:
from functools import wraps

def is_known_username(username):
    '''
    Returns a boolean if the username is known in the user-list.
    '''
    known_usernames = ['username1', 'username2']

    return username in known_usernames

def private_access():
    """
    Restrict access to the command to users allowed by the is_known_username function.
    """
    def deco_restrict(f):

        @wraps(f)
        def f_restrict(message, *args, **kwargs):
            username = message.from_user.username

            if is_known_username(username):
                return f(message, *args, **kwargs)
            else:
                bot.reply_to(message, text='Who are you?  Keep on walking...')

        return f_restrict  # true decorator

    return deco_restrict

Then where you are handling commands you can restrict access to the command like this:
@bot.message_handler(commands=['start'])
@private_access()
def send_welcome(message):
    bot.reply_to(message, "Hi and welcome")

Keep in mind, order matters.  First the message-handler and then your custom decorator - or it will not work.

A: The easiest way is probably a hard coded check on the user id.
# The allowed user id
my_user_id = '12345678'

# Handle command
@bot.message_handler(commands=['picture'])
def send_picture(message):

    # Get user id from message
    to_check_id = message.message_id

    if my_user_id = to_check_id:
        response_message = 'Pretty picture'
    else:
        response_message = 'Sorry, this is a private bot!'

    # Send response message
    bot.reply_to(message, response_message)


Q: Compiling 32-bit programs and calling 64-bit programs on 64-bit systems My system is 64 bit.
I have a program calls a command "bcdedit.exe"
c++ code：
ShellExecuteA(NULL, "open", "cmd.exe", "/c bcdedit.exe /?", NULL, SW_SHOWNORMAL);

I compiled to 32 bit
When I run it back "file not find"
When I compiled to 64 bit, run passed
The same problem exists in go
go code:
cmd := exec.Command("cmd.exe","/c","bcdedit.exe /?")
out, err := cmd.CombinedOutput()
if err != nil {
    fmt.Println(err)
}
fmt.Println(string(out))

I found "bcdedit.exe" in another directory:
C:\\Windows\\WinSxS\\amd64_microsoft-windows-b..iondata-cmdlinetool_31bf3856ad364e35_10.0.17134.471_none_69b0e05efb5a4702\\bcdedit.exe

When I call the command in this directory, all passed
This directory is different on every PC
How do I run the 32-bit compiled program for this command on each PC

A: So your code attempts to launch "bcdedit.exe".  From the command line, the only location of bcdedit.exe in your PATH environment is the Windows System directory, c:\Windows\System32.
When you compile your code as 32-bit and run it on a 64-bit system, your process's view of the file system will change.  Namely, the process view of the C:\Windows\System32 is replaced by the contents of C:\Windows\SysWOW64 - where only 32-bit DLLs and EXEs are located. However.... There is no 32-bit version bcdedit.exe located in this folder. (If you want to simulate this, go run c:\windows\syswow64\cmd.exe - you won't be able to find bcdedit.exe in the c:\windows\system32 folder anymore).
You probably need something like this: How to retrieve correct path of either system32 or SysWOW64?
Format your ShellExecute function to directly specificy the SysWow64 path for both bcdedit.exe and cmd.exe.  Or as others have suggested, just compile for 64-bit.


Q: Generic class instantiation using a bounded wildcard Based on the code snippet listed in my previous question (copied from a Java tutorial on generics by Gilad Bracha), I wrote the following code which tries to populate a custom generic list called history with objects of different types conforming to the bound ? extends Shape. However, my program doesn't compile. Why? How is it different from the code snippet in my other question?
import java.util.ArrayList;

class Shape {}
class Circle extends Shape {}
class Rectangle extends Shape {}

class MyArrayList<T>
{
    private ArrayList<T> items = new ArrayList<>();

    public T get(int idx)
    {
        return items.get(idx);
    }

    public void add(T item)
    {
        items.add(item);
    }

    @Override
    public String toString()
    {
        String str = "A box of [";
        for (T item : items) { str += item; }
        str += ']';
        return str;
    }
}

public class Shapes
{
    private static MyArrayList<? extends Shape>
       history = new MyArrayList<>();
    public static void main(String[] args)
    {
        history.add(new Circle());
        history.add(new Rectangle());
        System.out.println(history);
    }
}

A: In your previous example, you had a List<List<? extends Shape>>. Here you have a List<? extends Shape>. Completely different things.
Given a MyArrayList<? extends Shape>, that is a REFERENCE (like a page in an address book, not like a house), and the 'page in the address book' (that'd be your variable) promises that the house you get to will be guaranteed to be one of a few different style. Specifically, it'll be a List<Shape>. Or it could be a List<Rectangle>. Or perhaps a List<Circle>. But it'll be either a list of all sorts of shapes, or a list of some sort of specific shape.
This is different from just 'it's a list of all sorts of shapes' - that would be a List<Shape>, not a List<? extends Shape>.
Given that it could be a list of circles, and it could also be a list of squares, everything you do with history needs to be a thing you could do to either one.
.add(new Circle()) is not something that is valid for a List<Rectangle>. Hence, you can't do that, and history.add(new Circle()) is a compilation error.
So why did the previous snippet work? Because that was about List<List<? extends Shape>> which is a completely different thing to a List<? extends Shape>. One stores shapes. One stores a list of shapes.


Q: custom inputAccessoryView as UIView from nib giving error: returned 0 width, assuming UIViewNoIntrinsicMetric I am using an inputAccessoryView which is loaded from a nib using the following UIView subclass:
class CustomInputAccessoryView: UIView {

    @IBOutlet var containerView: UIView!
    @IBOutlet var contentView: UIView!
    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var textView: UITextView!

    override var intrinsicContentSize: CGSize {
        return CGSize.zero
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupInputAccessoryView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupInputAccessoryView()
    }

    func setupInputAccessoryView() {
        self.translatesAutoresizingMaskIntoConstraints = false
        Bundle.main.loadNibNamed("CustomInputAccessoryView", owner: self, options: nil)
        addSubview(containerView)
        containerView.frame = self.bounds
    }

}

I assign the view to the inputAccessoryView and set it up just by the following:
var customInputAccessoryView = CustomInputAccessoryView()

The inputAccessoryView loads properly and displays correctly.  The problem is when I press inside the textView of the inputAccessoryView and the keyboard displays, I get the following error:
<_UIKBCompatInputView: ...; frame = (0 0; 0 0); layer = <CALayer: ...>> returned 0 width, assuming UIViewNoIntrinsicMetric

I have two files, a .swift file which is the subclass of UIView displayed above and the nib file by the same name.  In the file owner of the nib I select the sub class (CustomInputAccessoryView) and wire up the outlets.
I don't really know what is happening other than maybe the input accessory view automatically resizing to zero frame whenever the keyboard is displayed before going to the correct size.  If so I'm assuming I need to change some AutoLayout priorities but what I have tried is not working.  The only hard width constraints are the buttons which have fixed widths.
The inputAccessoryView width should always be the width of the window it is displayed in.


Q: SwiftUI List color background I can't change background color of a view if i List static items. this my code:
NavigationView {
    ZStack {
        Color("AppBackgroundColor").edgesIgnoringSafeArea(.all)
        List {
            Section(header: Text("Now in theaters")) {
                ScrollMovies(type: .currentMoviesInTheater)
            }
            Section(header: Text("Popular movies")) {
                ScrollMovies(type: .popularMovies)
            }
        }.listStyle(.grouped)
    }
}

A: List cannot be "painted". Please use the following instead:
List of items:
ForEach(items) { item in
    HStack {
        Text(item)
    }
}.background(Color.red)

Scrollable list of items:
ScrollView {
    ForEach(items) { item in
        HStack {
            Text(item)
        }
    }.background(Color.red)
}

In your case:
VStack { // or HStack for horizontal alignment
    Section(header: Text("Now in theaters")) {
        ScrollMovies(type: .currentMoviesInTheater)
    }
    Section(header: Text("Popular movies")) {
        ScrollMovies(type: .popularMovies)
    }
}.background(Color.red)

A: Using UITableView.appearance().backgroundColor can affect the background colour of all List controls in the app. If you only want one particular view to be affected, as a workaround, you can set it onAppear and set it back to the default onDisappear.
import SwiftUI
import PlaygroundSupport

struct PlaygroundRootView: View {
    @State var users: [String] = ["User 1",
                                  "User 2",
                                  "User 3",
                                  "User 4"]
    var body: some View {
        Text("List")
        List(users, id: \.self){ user in
            Text(user)
        }
        .onAppear(perform: {
            // cache the current background color
            UITableView.appearance().backgroundColor = UIColor.red
        })
        .onDisappear(perform: {
            // reset the background color to the cached value
            UITableView.appearance().backgroundColor = UIColor.systemBackground
        })
    }
}
PlaygroundPage.current.setLiveView(PlaygroundRootView())

A: You can provide a modifier for the items in the list
NavigationView {
        ZStack {
            Color("AppBackgroundColor").edgesIgnoringSafeArea(.all)
            List {
                Section(header: Text("Now in theaters")) {
                    ScrollMovies(type: .currentMoviesInTheater)
                    .listRowBackground(Color.blue) // << Here
                }
                Section(header: Text("Popular movies")) {
                    ScrollMovies(type: .popularMovies)
                    .listRowBackground(Color.green)  // << And here
                }
            }.listStyle(.grouped)
        }
    }

A: For SwiftUI on macOS this works :
extension NSTableView {
    open override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()

        // set the background color of every list to red
        backgroundColor = .red
    }
}

It will set the background color of every list to red (in that example).

A: iOS 16
Since Xcode 14 beta 3, You can change the background of all lists and scrollable contents using this modifier:
.scrollContentBackground(.hidden)

You can pass in .hidden to make it transparent. So you can see the color or image underneath.

iOS 15 and below
All SwiftUI's Lists are backed by a UITableView (until iOS 16). so you need to change the background color of the tableView. You make it clear so other views will be visible underneath it:
struct ContentView: View {

    init(){
        UITableView.appearance().backgroundColor = .clear
    }

    var body: some View {
        Form {
            Section(header: Text("First Section")) {
                Text("First cell")
            }
            Section(header: Text("Second Section")) {
                Text("First cell")
            }
        }
        .background(Color.yellow)
    }
}

Now you can use Any background (including all Colors) you want

Note that those top and bottom white areas are the safe areas and you can use the .edgesIgnoringSafeArea() modifier to get rid of them.
Also note that List with the .listStyle(GroupedListStyle()) modifier can be replaced by a simple Form. But keep in mind that SwiftUI controls behave differently depending on their enclosing view.
Also you may want to set the UITableViewCell's background color to clear as well for plain tableviews

A: Easiest way to do this for now is just to use UIAppearance proxy. SwiftUI is young so there's a couple of features not fully implemented correctly by Apple yet.
UITableView.appearance().backgroundColor = .red

A: @State var users: [String] = ["User 1",
                              "User 2",
                              "User 3",
                              "User 4"]

init(){
    UITableView.appearance().backgroundColor = .red
    UITableViewCell.appearance().backgroundColor = .red
    UITableView.appearance().tableFooterView = UIView()
}

var body: some View {
    List(users, id: \.self){ user in
        Text(user)
    }
    .background(Color.red)
}

PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())

A: A bit late to the party, but this may help. I use a combination of:

*

*Setting the UITableView.appearance appearance

*Setting the UITableViewCell.appearance appearance

*Settings the List listRowBackground modifier.

Setting the appearance affects the entire app, so you may want to reset it to other values where applicable.
Sample code:
struct ContentView: View {
    var body: some View {

        let items = ["Donald", "Daffy", "Mickey", "Minnie", "Goofy"]

        UITableView.appearance().backgroundColor = .clear
        UITableViewCell.appearance().backgroundColor = .clear

        return ZStack {
            Color.yellow
                .edgesIgnoringSafeArea(.all)
            List {
                Section(header: Text("Header"), footer: Text("Footer")) {
                    ForEach(items, id: \.self) { item in
                        HStack {
                            Image(systemName: "shield.checkerboard")
                                .font(.system(size: 40))
                            Text(item)
                                .foregroundColor(.white)
                        }
                        .padding([.top, .bottom])
                    }
                    .listRowBackground(Color.orange))
                }
                .foregroundColor(.white)
                .font(.title3)
            }
            .listStyle(InsetGroupedListStyle())
        }

    }
}

A: since, you are asking for changing the background color of view,
you can use .colorMultiply() for that.
Code:
var body: some View {
        VStack {
            ZStack {
                List {
                    Section(header: Text("Now in theaters")) {
                        Text("Row1")
                    }
                    Section(header: Text("Popular movies")) {
                        Text("Row2")
                    }

                    /*Section(header: Text("Now in theaters")) {
                        ScrollMovies(type: .currentMoviesInTheater)
                    }
                    Section(header: Text("Popular movies")) {
                        ScrollMovies(type: .popularMovies)
                    } */
                }.listStyle(.grouped)
            }.colorMultiply(Color.yellow)
        }
}

Output:


Q: Error in my c++ code using linkedlist "Stop working" my code stop working in that test case, i think that the error in function Checktables but i'm not sure and i can't fix the error please help me to tun this code correctly.
image of a test case and the error
this is a cpp file with main .cpp
    #include"Header.h"
string Name;
string namess;

customer::customer()
{
    name = "";
    gsize = status = 0;
    next = NULL;
}

customer::customer(string name1, int gsize1, int status1)
{
    name = name1;
    gsize = gsize1;
    status = status1;
    next = NULL;
}

waitinglist::waitinglist()
{
    chairnum =50 ;
    totalcustomers = tables = 0;
    head = tail = NULL;
}

waitinglist::waitinglist(int val)
{
    chairnum = 50;
    totalcustomers = 0;
    tables = 0;
    head = tail = NULL;
}

void waitinglist::change()
{
    customer*temp ;
    temp = head;
    cout << "enter the name: ";
    cin >> namess;

        while (temp != NULL)
        {
            if (namess == temp->name)
            {
                if (temp->status==2)
                {
                    temp->status=1;
                    cout << "done!  " << endl ;
                    break ;
                }
            }
            else if (namess != temp->name)
            {
                temp = temp->next;
            }
        }

      if (temp == NULL)
    {
        cout << "can't found! " << endl;
    }
}

void waitinglist::newcustomer()
{

    customer*tmp = new customer;
    cout << "enter the name: ";  cin >> tmp->name;
    customer*tmpo=new customer;
    tmpo=head ;
    while (tmpo != NULL)
        {

            if (tmp->name != tmpo->name)
            {
                tmpo = tmpo->next;
            }
            else if (tmp->name == tmpo->name)
            {
                cout<<"The Name already exist! " << endl ;
                cout << "enter the name: ";  cin >> tmp->name;
                tmpo=head;
            }

    }

    cout << "enter the group number: ";  cin >> tmp->gsize;
    cout << "enter the status: ";  cin >> tmp->status;
    if (head == NULL)            // linkedlist is empty
    {
        head = tail = tmp;
        totalcustomers++;
    }
    else
    {
        tail->next = tmp;
        tail=tail->next;
        totalcustomers++;
    }

}

void waitinglist::checktables()
{
        float c=5.00;
        customer*temp=head;
        customer*found;
        cout<<"enter number of tables: ";
        cin >> tables ;

        while (tables>=1 && temp!=NULL)
        {
            int x;
            float y;

            y=((temp->gsize)/c);
            x=(temp->gsize)/c;

            if (tables<y)
            {
                temp=temp->next;
            }
            else if (tables>=y)
            {
                if (x==y)
                {
                    tables=tables-x ;           //   Correct Table!
                    cout<<temp->name<<endl;

                }
                else if (x!=y)
                {
                    tables=tables-(x+1);
                    cout<<temp->name<<endl;
                }

                found=temp ;
                delete found;               // Discard
                break ;
            }

        }
    }

void waitinglist::displayall()
{
    customer *tmp;
    tmp = head;
    if (tmp == NULL)
    {
        cout << "Empty!";
    }
    while (tmp != NULL)
    {
        cout << "Name: " << tmp->name <<endl;
        cout << "group number: " << tmp->gsize << endl;
        tmp = tmp->next;
    }
    cout << endl;
}

void waitinglist::diplaycustomer()

{

    customer*tmp;
    tmp = head;
    cout << "enter the name: ";
    cin >> Name;

        while (tmp != NULL)
        {
            if (Name == tmp->name)
            {
                cout << "the name : " << tmp->name << endl;
                cout << "the group size = " << tmp->gsize << endl;
                cout << "the status = " << tmp->status << endl;
                break;
            }
            else if (Name != tmp->name)
            {
                tmp = tmp->next;
            }
        }

      if (tmp == NULL)
    {
        cout << "can't found!" << endl;
    }
}

int main()
{
    int choice;
    string name1 = "";
    int gsize1 = 0;
    int status1 = 0;
    waitinglist mylist;

    cout << "Note: 1 in status means the customer not here and 2 means the customer is here.\n";
    cout << "Select your option.\n\n";
    cout << "(1) Add a new Customer.\n";
    cout << "(2) Display information based on Name.\n";
    cout << "(3) List all Names.\n";
    cout << "(4) to change the status. \n" ;
    cout << "(5) Check tables by name. \n";
    cout << "(6) quit. \n";
    do
    {
        cout << "\n";
        cout << "Enter your choice: -->  ";
        cin >> choice;
        if (1 <= choice && choice <= 5)
        {
            switch (choice)
            {
            case 1:
                mylist.newcustomer();
                break;
            case 2:
                mylist.diplaycustomer();
                break;
            case 3:
                mylist.displayall();
                break;
            case 4:
                mylist.change() ;
                break;
            case 5 :
                mylist.checktables();
                break;

            default:
                cout << "Invalid choice.  Enter again.\n\n";
                break;
            }
        }
        else if (choice>6)
        {
            cout << "Invalid choice.  Enter again.\n\n";
            break;
        }

    } while (choice != 6);

    return 0;
}

and this is the header file .h
        #include<iostream>
    #include<string>
    using namespace std;

    class customer
    {
    public:
        string name;
        int gsize;
        int status;
        customer* next;

        customer();
        customer(string,int,int);

    };

    class waitinglist
    {
    public:
        int tables; //number of occupied tables
        int chairnum;
        int totalcustomers;
        customer*head,*tail;
        waitinglist();
        waitinglist(int);
        void newcustomer();
        void diplaycustomer();
        void displayall();
        void change () ;
        void checktables();

    };

A: One error is that your checktables function corrupts your linked list structure by calling delete on one of the nodes:
        found = temp;
        delete found;               // Discard

What you've just done in those lines above is to have a linked list with a broken (invalid) link in it.  Any functions that now traverses the list (like displaytables) will now hit the broken link, and things start to go haywire.
To delete a node from a linked list, you have to not just call delete, but adjust the link in waitinglist that used to point to that deleted node and have it point to the next node after the deleted one.
Think of it like a real chain -- if one of the links in the chain needs to be removed, you have to physically remove it, and hook the link before it to the next good link.  You didn't do this step.
I won't write the code for that, but this is what you should have seen much earlier in the development of your program.  Better yet would have been to write a singly-linked list class that adds and removes nodes correctly first.  Test it, and then once it can add and remove nodes successfully without error, then use it in your larger program.


Q: How to mock other class functions in testing controller in Laravel I am trying to test a controller in Laravel that uses another class as a helper which calls an API and returns the result.
To avoid external API calls, I need to mock this helper.
I tried to mock the class inside the controller and run the test but I didn't get what I expected in mock class.
this is my controller method:
public function A(Request $request){
  $helper = new TheHelper();
  $result = $helper->getResult($request->email);
  if($result){
    return response()->json([
                'success' => true,
                'message' => "result found",
            ], 200);
  }else{
    return response()->json([
                'success' => false,
                'message' => "no result",
            ], 500);
  }

}

My helper method simply calls an API and returns the result.
class TheHelper
{
    public function getResult($email){
      // some api calls
      return $result;
    }
}

Here is my test:
public function testExample()
    {

        $helperMock = Mockery::mock(TheHelper::class);

        // Set expectations
        $helperMock ->shouldReceive('getResult')
            ->once()
            ->with('testemail@test.com')
            ->andReturn([
                'id' => '100'
            ]);

        $this->app->instance(TheHelper::class, $helperMock);

        $this->json(
            'POST',
            '/api/test_method',
            ['email' => 'testemail@test.com'])
            ->assertStatus(200);
}

My mock function never called. it only checks with the real API inside TheHelper method

A: Your test is creating a mock object and binding that mock object into the Laravel service container. However, your controller is not pulling a TheHelper instance from the Laravel service container; it is manually instantiating it with the new keyword. Using the new keyword is core PHP, and does not involve Laravel at all.
Your test is showing you an issue in your code. TheHelper is a dependency of your method, and should therefore be passed into the method instead of being created inside the method.
You either need to update your controller method to use dependency injection, so that Laravel can automatically resolve the TheHelper dependency from its container, or you need to replace your new keyword with a call into the Laravel container.
Using dependency injection:
public function A(Request $request, TheHelper $helper)
{
    $result = $helper->getResult($request->email);
    // rest of function...
}

Manually pull from the container:
public function A(Request $request)
{
    $helper = app(TheHelper::class);
    $result = $helper->getResult($request->email);
    // rest of function...
}


Q: Changes in the fxml file are not visible Basically when i update my .fxml file, i can't see the new stuff...it's like showing the old version of the .fxml...with the old stuff... and yes i save the file...
This is my Main.java
package Library.Assistant.Ui.Main;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainLoader extends Application {

    public static void main(String arg[]) {
        launch(arg);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
}

This is my Main.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>

<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="548.0" prefWidth="617.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Library.Assistant.Ui.Main.MainController">
   <children>
      <MenuBar maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
              <MenuItem mnemonicParsing="false" text="Close" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Edit">
            <items>
              <MenuItem mnemonicParsing="false" text="Delete" />
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem mnemonicParsing="false" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
      <GridPane fx:id="grid" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <TabPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" tabClosingPolicy="UNAVAILABLE" GridPane.rowSpan="2147483647">
              <tabs>
                <Tab text="Book Issue">
                     <content>
                        <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0">
                           <children>
                              <HBox alignment="CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS">
                                 <children>
                                    <TextField fx:id="enterBookID" promptText="Enter Book ID" />
                                    <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
                                       <children>
                                          <Label text="Book Name" />
                                          <Label text="Author" />
                                       </children>
                                    </VBox>
                                 </children>
                              </HBox>
                              <HBox alignment="CENTER" layoutX="10.0" layoutY="10.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS">
                                 <children>
                                    <TextField promptText="Enter Member ID" />
                                    <VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" HBox.hgrow="ALWAYS">
                                       <children>
                                          <Label text="Member Name" />
                                          <Label text="Contact" />
                                       </children>
                                    </VBox>
                                 </children>
                              </HBox>
                              <HBox alignment="CENTER" layoutX="10.0" layoutY="404.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS">
                                 <children>
                                    <JFXButton maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Issue" HBox.hgrow="ALWAYS" />
                                 </children>
                              </HBox>
                           </children>
                        </VBox>
                     </content>
                </Tab>
                <Tab text="Renew / Submission">
                     <content>
                        <VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308">
                           <children>
                              <BorderPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" VBox.vgrow="ALWAYS">
                                 <top>
                                    <JFXTextField alignment="CENTER" promptText="Enter Book ID" BorderPane.alignment="CENTER">
                                       <BorderPane.margin>
                                          <Insets bottom="20.0" left="10.0" right="10.0" top="10.0" />
                                       </BorderPane.margin>
                                    </JFXTextField>
                                 </top>
                                 <center>
                                    <ListView maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER" />
                                 </center>
                                 <bottom>
                                    <HBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER">
                                       <children>
                                          <JFXButton maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Renew" HBox.hgrow="ALWAYS" />
                                          <JFXButton maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" text="Submission" HBox.hgrow="ALWAYS" />
                                       </children>
                                       <BorderPane.margin>
                                          <Insets />
                                       </BorderPane.margin>
                                    </HBox>
                                 </bottom>
                              </BorderPane>
                           </children>
                        </VBox>
                     </content>
                </Tab>
              </tabs>
            </TabPane>
            <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Add Member" GridPane.columnIndex="1">
               <graphic>
                  <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@add_mem.png" />
                     </image>
                  </ImageView>
               </graphic>
            </Button>
            <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Add Book" GridPane.columnIndex="1" GridPane.rowIndex="1">
               <graphic>
                  <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@add_book.png" />
                     </image>
                  </ImageView>
               </graphic>
            </Button>
            <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="View Members" GridPane.columnIndex="1" GridPane.rowIndex="2">
               <graphic>
                  <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@list_mem.png" />
                     </image>
                  </ImageView>
               </graphic>
            </Button>
            <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="View Books" GridPane.columnIndex="1" GridPane.rowIndex="3">
               <graphic>
                  <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@list_book.png" />
                     </image>
                  </ImageView>
               </graphic>
            </Button>
            <Button contentDisplay="TOP" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Settings" GridPane.columnIndex="1" GridPane.rowIndex="4">
               <graphic>
                  <ImageView fitHeight="50.0" fitWidth="50.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@settings.png" />
                     </image>
                  </ImageView>
               </graphic>
            </Button>
         </children>
      </GridPane>
   </children>
</VBox>

I just can't understand why it's showing the old version of the file...yesterday everything was working fine.I was adding new stuff and it was showing them properly, but today it keeps showing the version from yesterday...no matter how many stuff i change..