问:
jquery years months and days variable
when the system appears, I see that it is very complicated, but I have a problem, I found this code from somewhere, but I am writing because I do not have much knowledge, thank you in advance to those who help.

http://jsfiddle.net/8qbjh3z2/

function dateAgo(date) {

    var startDate = new Date( date + " " + '12:00 AM');
    var endDate = new Date();

    var diffDate  = new Date(new Date() - startDate);

    var yearDiff  = diffDate.toISOString().slice(0, 4) - 1970;
    var monthDiff = diffDate.getMonth();
    var dayDiff   = diffDate.getDate()-1;

    var msec  = endDate - startDate;
    var mins  = Math.floor(msec / 60000);
    var hrs   = Math.floor(mins / 60);
    var days  = Math.floor(hrs / 24);

    var label = 'Posted ';
    if( mins <= 30 ){
        label += ' Just Now';
    }else if( hrs <= 24 ){
        label += ' Just Today';
    }else{
        if( yearDiff > 0  ){
            label += ( yearDiff > 1 ) ? yearDiff+' years, ' : yearDiff+' year, ';
        }

        if( monthDiff > 0 ){
            label += ( monthDiff > 1 ) ? monthDiff+' months, ' : monthDiff+' month, ';
        }

        if( dayDiff > 0 ){
            label += ( dayDiff > 1 ) ? dayDiff+' days ' : dayDiff+' day ';
        }

        label += 'ago';
    }

    return label;

}

(function() {
    var elements = document.body.getElementsByClassName('iso-date');
    for (var i = 0; i < elements.length; i++) {
        var date  = elements[i].innerHTML;
        var label = dateAgo(date);
        elements[i].nextElementSibling.innerHTML = label;
    }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="iso-date">2019-09-30</div>
<div class="display-date"></div></code>```

The codes in the above code file are like this. The system I want to be done automatically adds the month, year or day when the date is changed. I want the week part to be added as an extra. If it is something that is not seen in the system, I want the system to be added in the class and id section that I have specified. I would appreciate your help.

答:
function getAge(dateString) {
  var now = new Date();
  var today = new Date(now.getYear(),now.getMonth(),now.getDate());

  var yearNow = now.getYear();
  var monthNow = now.getMonth();
  var dateNow = now.getDate();

  var dob = new Date(dateString.substring(6,10),
                     dateString.substring(0,2)-1,
                     dateString.substring(3,5)
                     );

  var yearDob = dob.getYear();
  var monthDob = dob.getMonth();
  var dateDob = dob.getDate();
  var age = {};
  var ageString = "";
  var yearString = "";
  var monthString = "";
  var dayString = "";

  yearAge = yearNow - yearDob;

  if (monthNow >= monthDob)
    var monthAge = monthNow - monthDob;
  else {
    yearAge--;
    var monthAge = 12 + monthNow -monthDob;
  }

  if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    var dateAge = 31 + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

  age = {
      years: yearAge,
      months: monthAge,
      days: dateAge
      };

  if ( age.years > 1 ) yearString = " years";
  else yearString = " year";
  if ( age.months> 1 ) monthString = " months";
  else monthString = " month";
  if ( age.days > 1 ) dayString = " days";
  else dayString = " day";

  if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
    else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) );
  else if ( (age.years > 0) && (age.months > 0))
    ageString = age.years + yearString + " and " + age.months + monthString + " old.";

  else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
    ageString = age.years + yearString ;
  else if ( (age.years == 0) && (age.months > 0))
    ageString = age.months + monthString + " old.";
  else ageString = "Oops! Could not calculate age!";

  return ageString;
}

document.getElementById('test').innerHTML += "
" + (getAge('02/09/2019'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">

</div></code>```

There was a solution in this way, but I could not do this. The system, for example: 2 years, 11 months, and 30 days old. gives. I want the registration date in the system to be 1 year and 2 months after 1 year, so I cannot cancel the number of days.

Title: jquery years months and days variable

Body:
when the system appears, I see that it is very complicated, but I have a problem, I found this code from somewhere, but I am writing because I do not have much knowledge, thank you in advance to those who help.

http://jsfiddle.net/8qbjh3z2/

function dateAgo(date) {

    var startDate = new Date( date + " " + '12:00 AM');
    var endDate = new Date();

    var diffDate  = new Date(new Date() - startDate);

    var yearDiff  = diffDate.toISOString().slice(0, 4) - 1970;
    var monthDiff = diffDate.getMonth();
    var dayDiff   = diffDate.getDate()-1;

    var msec  = endDate - startDate;
    var mins  = Math.floor(msec / 60000);
    var hrs   = Math.floor(mins / 60);
    var days  = Math.floor(hrs / 24);

    var label = 'Posted ';
    if( mins <= 30 ){
        label += ' Just Now';
    }else if( hrs <= 24 ){
        label += ' Just Today';
    }else{
        if( yearDiff > 0  ){
            label += ( yearDiff > 1 ) ? yearDiff+' years, ' : yearDiff+' year, ';
        }

        if( monthDiff > 0 ){
            label += ( monthDiff > 1 ) ? monthDiff+' months, ' : monthDiff+' month, ';
        }

        if( dayDiff > 0 ){
            label += ( dayDiff > 1 ) ? dayDiff+' days ' : dayDiff+' day ';
        }

        label += 'ago';
    }

    return label;

}

(function() {
    var elements = document.body.getElementsByClassName('iso-date');
    for (var i = 0; i < elements.length; i++) {
        var date  = elements[i].innerHTML;
        var label = dateAgo(date);
        elements[i].nextElementSibling.innerHTML = label;
    }
})();

2019-09-30

The codes in the above code file are like this. The system I want to be done automatically adds the month, year or day when the date is changed. I want the week part to be added as an extra. If it is something that is not seen in the system, I want the system to be added in the class and id section that I have specified. I would appreciate your help.

Body:
function getAge(dateString) {
  var now = new Date();
  var today = new Date(now.getYear(),now.getMonth(),now.getDate());

  var yearNow = now.getYear();
  var monthNow = now.getMonth();
  var dateNow = now.getDate();

  var dob = new Date(dateString.substring(6,10),
                     dateString.substring(0,2)-1,
                     dateString.substring(3,5)
                     );

  var yearDob = dob.getYear();
  var monthDob = dob.getMonth();
  var dateDob = dob.getDate();
  var age = {};
  var ageString = "";
  var yearString = "";
  var monthString = "";
  var dayString = "";

  yearAge = yearNow - yearDob;

  if (monthNow >= monthDob)
    var monthAge = monthNow - monthDob;
  else {
    yearAge--;
    var monthAge = 12 + monthNow -monthDob;
  }

  if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    var dateAge = 31 + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

  age = {
      years: yearAge,
      months: monthAge,
      days: dateAge
      };

  if ( age.years > 1 ) yearString = " years";
  else yearString = " year";
  if ( age.months> 1 ) monthString = " months";
  else monthString = " month";
  if ( age.days > 1 ) dayString = " days";
  else dayString = " day";

  if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
    else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) );
  else if ( (age.years > 0) && (age.months > 0))
    ageString = age.years + yearString + " and " + age.months + monthString + " old.";

  else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
    ageString = age.years + yearString ;
  else if ( (age.years == 0) && (age.months > 0))
    ageString = age.months + monthString + " old.";
  else ageString = "Oops! Could not calculate age!";

  return ageString;
}

document.getElementById('test').innerHTML += "<br />" + (getAge('02/09/2019'));

<div id="test">

</div>

There was a solution in this way, but I could not do this. The system, for example: 2 years, 11 months, and 30 days old. gives. I want the registration date in the system to be 1 year and 2 months after 1 year, so I cannot cancel the number of days.


来源: stackexchange

问:
Android Studio, Java, drawing multiple lines
In a LineView class i tried to declare two arrays of points: pointArrayStart and pointArrayEnd like:

```<code>private final Point[] pointArrayStart = new Point[12];
private final Point[] pointArrayEnd = new Point[12];
</code>```

In a protected void onDraw(Canvas canvas) I initialised the lines like:

```<code>for (int i = 0; i < 12; i++) {
            canvas.drawLine(pointArrayStart[i].x, pointArrayStart[i].y, pointArrayEnd[i].x, pointArrayEnd[i].y, paint);  }
</code>```

The setters I declared as:

```<code>public void setPointArrayStart(Point pointArrayStart) {
    for (int i = 0; i < 12; i++) {
        this.pointArrayStart[i] = pointArrayStart;
    }
}

public void setPointArrayEnd(Point pointArrayEnd) {
    for (int i = 0; i < 12; i++) {
        this.pointArrayEnd[i] = pointArrayEnd;
    }
}
</code>```

In the MainActivity the lineView class is declared as:

```<code>private LineView mLineView;
</code>```

in a loop the lines are initialised as:

```<code>for (int i = 0; i < 12; i++) {
    myLines(100, 100 + (20 * i), 600, 120 + (20 * i));
}
</code>```

I called the LineView class with the code:

```<code>public void myLines(int e, int f, int g, int h) {
    Point pointArrayStart = new Point(e, f);
    Point pointArrayEnd = new Point(g, h);
    mLineView.setPointArrayStart(pointArrayStart);
    mLineView.setPointArrayEnd(pointArrayEnd);
}
</code>```

But calling the LineView in this way every call overwrites the call before.

How can I call the lineview keeping the lines visible drawed in earlier calls

答:
I solved it myself. This works:
In the lineviewClass:

```<code>public class LineView extends View {
    private Paint paint = new Paint();
    int i;
    public LineView(Context context) {
        super(context);
    }
    public LineView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    public LineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void onDraw(Canvas canvas) {

        paint.setStrokeWidth(5);

        for (i=0; i<25; i++) {
            paint.setColor(Color.argb(255, 10*i,255-(10*i),255-(5*i)));
            canvas.drawLine(MainActivity.pointArrayStart[i].x, MainActivity.pointArrayStart[i].y, MainActivity.pointArrayEnd[i].x, MainActivity.pointArrayEnd[i].y, paint);
        }
        super.onDraw(canvas);
    }

    public void setPointArrayStart(Point[] pointArrayStartSet) {
        MainActivity.pointArrayStart[i] = pointArrayStartSet[i];
    }

    public void setPointArrayEnd(Point[] pointArrayEndSet) {
        MainActivity.pointArrayEnd[i] = pointArrayEndSet[i];
    }
}
</code>```

In the mainactivity:

```<code>public class MainActivity extends AppCompatActivity {
    public static Point[] pointArrayStart = new Point[100];
    public static Point[] pointArrayEnd = new Point[100];

    int a = 0;
    private LineView mLineView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLineView = findViewById(R.id.lineView);
        for (a = 0; a < 25; a++) {
            meerLijnen(600 + (30 * a), 700 - (20 * a), 50 + (10 * a), 50 + (100 * a));
        }
    }

    public void meerLijnen(int e, int f, int g, int h) {
        pointArrayStart[a] = new Point(e, f);
        pointArrayEnd[a] = new Point(g, h);
        mLineView.setPointArrayStart(new Point[]{pointArrayStart[a]});
        mLineView.setPointArrayEnd(new Point[]{pointArrayEnd[a]});

    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In a LineView class i tried to declare two arrays of points: pointArrayStart and pointArrayEnd like:

private final Point[] pointArrayStart = new Point[12];
private final Point[] pointArrayEnd = new Point[12];

In a protected void onDraw(Canvas canvas) I initialised the lines like:

for (int i = 0; i < 12; i++) {
            canvas.drawLine(pointArrayStart[i].x, pointArrayStart[i].y, pointArrayEnd[i].x, pointArrayEnd[i].y, paint);  }

The setters I declared as:

public void setPointArrayStart(Point pointArrayStart) {
    for (int i = 0; i < 12; i++) {
        this.pointArrayStart[i] = pointArrayStart;
    }
}

public void setPointArrayEnd(Point pointArrayEnd) {
    for (int i = 0; i < 12; i++) {
        this.pointArrayEnd[i] = pointArrayEnd;
    }
}

In the MainActivity the lineView class is declared as:

private LineView mLineView;

in a loop the lines are initialised as:

for (int i = 0; i < 12; i++) {
    myLines(100, 100 + (20 * i), 600, 120 + (20 * i));
}

I called the LineView class with the code:

public void myLines(int e, int f, int g, int h) {
    Point pointArrayStart = new Point(e, f);
    Point pointArrayEnd = new Point(g, h);
    mLineView.setPointArrayStart(pointArrayStart);
    mLineView.setPointArrayEnd(pointArrayEnd);
}

But calling the LineView in this way every call overwrites the call before.

How can I call the lineview keeping the lines visible drawed in earlier calls

Body:
I solved it myself. This works:
In the lineviewClass:

public class LineView extends View {
    private Paint paint = new Paint();
    int i;
    public LineView(Context context) {
        super(context);
    }
    public LineView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    public LineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void onDraw(Canvas canvas) {

        paint.setStrokeWidth(5);

        for (i=0; i<25; i++) {
            paint.setColor(Color.argb(255, 10*i,255-(10*i),255-(5*i)));
            canvas.drawLine(MainActivity.pointArrayStart[i].x, MainActivity.pointArrayStart[i].y, MainActivity.pointArrayEnd[i].x, MainActivity.pointArrayEnd[i].y, paint);
        }
        super.onDraw(canvas);
    }

    public void setPointArrayStart(Point[] pointArrayStartSet) {
        MainActivity.pointArrayStart[i] = pointArrayStartSet[i];
    }

    public void setPointArrayEnd(Point[] pointArrayEndSet) {
        MainActivity.pointArrayEnd[i] = pointArrayEndSet[i];
    }
}

In the mainactivity:

public class MainActivity extends AppCompatActivity {
    public static Point[] pointArrayStart = new Point[100];
    public static Point[] pointArrayEnd = new Point[100];

    int a = 0;
    private LineView mLineView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLineView = findViewById(R.id.lineView);
        for (a = 0; a < 25; a++) {
            meerLijnen(600 + (30 * a), 700 - (20 * a), 50 + (10 * a), 50 + (100 * a));
        }
    }

    public void meerLijnen(int e, int f, int g, int h) {
        pointArrayStart[a] = new Point(e, f);
        pointArrayEnd[a] = new Point(g, h);
        mLineView.setPointArrayStart(new Point[]{pointArrayStart[a]});
        mLineView.setPointArrayEnd(new Point[]{pointArrayEnd[a]});

    }
}


问:
How to sum value in javascript array obj from specific search category to useState
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

```<code>const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]
</code>```

How can i interate arr to get this effect ?

```<code>const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)
</code>```

Thanks you for your help ;-)

答:
Just filter and reduce:

const arr = [{id: '222', cost: 2, category: 'fit'},{id: '333', cost: 3, category: 'fat'},{id: '11', cost: 1, category: 'fat'},{id: '11', cost: 0, category: 'fit'},{id: '33', cost: 55, category: 'slim'},{id: '55', cost: 33, category: 'slim'},{id: '123', cost: 4, category: 'slim'}]

const sumBy = (arr, targetCat) => arr
    .filter(({ category }) => category === targetCat)
    .reduce((sum, { cost }) => sum + cost, 0);

console.log(sumBy(arr, 'fit'))
console.log(sumBy(arr, 'fat'))
console.log(sumBy(arr, 'slim'))
console.log(sumBy(arr, 'test'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

or you can create a reduced object once and receive amounts from it

const arr = [{id: '222', cost: 2, category: 'fit'},{id: '333', cost: 3, category: 'fat'},{id: '11', cost: 1, category: 'fat'},{id: '11', cost: 0, category: 'fit'},{id: '33', cost: 55, category: 'slim'},{id: '55', cost: 33, category: 'slim'},{id: '123', cost: 4, category: 'slim'}]

const reducedObj = arr.reduce((acc, { category, cost }) => ({
  ...acc,
  [category]: acc[category] ? acc[category] + cost : cost
}), {});

// reducedObj looks like:
// {
// "fit": 2,
// "fat": 4,
// "slim": 92
// }
// there is no 'test' so we make a guard while get values

console.log(reducedObj['fit'] ?? 0)
console.log(reducedObj['fat'] ?? 0)
console.log(reducedObj['slim'] ?? 0)
console.log(reducedObj['test'] ?? 0)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

Body:
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]

How can i interate arr to get this effect ?

const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)

Thanks you for your help ;-)

Body:
Just filter and reduce:

const arr = [{id: '222', cost: 2, category: 'fit'},{id: '333', cost: 3, category: 'fat'},{id: '11', cost: 1, category: 'fat'},{id: '11', cost: 0, category: 'fit'},{id: '33', cost: 55, category: 'slim'},{id: '55', cost: 33, category: 'slim'},{id: '123', cost: 4, category: 'slim'}]

const sumBy = (arr, targetCat) => arr
    .filter(({ category }) => category === targetCat)
    .reduce((sum, { cost }) => sum + cost, 0);

console.log(sumBy(arr, 'fit'))
console.log(sumBy(arr, 'fat'))
console.log(sumBy(arr, 'slim'))
console.log(sumBy(arr, 'test'))

.as-console-wrapper{min-height: 100%!important; top: 0}

or you can create a reduced object once and receive amounts from it

const arr = [{id: '222', cost: 2, category: 'fit'},{id: '333', cost: 3, category: 'fat'},{id: '11', cost: 1, category: 'fat'},{id: '11', cost: 0, category: 'fit'},{id: '33', cost: 55, category: 'slim'},{id: '55', cost: 33, category: 'slim'},{id: '123', cost: 4, category: 'slim'}]

const reducedObj = arr.reduce((acc, { category, cost }) => ({
  ...acc,
  [category]: acc[category] ? acc[category] + cost : cost
}), {});

// reducedObj looks like:
// {
// "fit": 2,
// "fat": 4,
// "slim": 92
// }
// there is no 'test' so we make a guard while get values

console.log(reducedObj['fit'] ?? 0)
console.log(reducedObj['fat'] ?? 0)
console.log(reducedObj['slim'] ?? 0)
console.log(reducedObj['test'] ?? 0)

.as-console-wrapper{min-height: 100%!important; top: 0}


问:
Inner join three tables out of which one is not connected with other
I have three tables client_invoices ,contract_additional_info and contract out of which
client_invoices is connected with contract_additional_info  and contract_additional_info is connected with contract table .

contract table and client_invoices table don't have any relations.

Now I am running following query

```<code>SELECT   client_invoices.markup_type,
         client_invoices.supplier_invoice_number,
         client_invoices.client_payment_req_id,
         client_invoices.net_amount,
         client_invoices.markup_value,
         client_invoices.net_qty,
         client_invoices.markup_value,
         contract.clientId as buyerClientId,
         contract_additional_info.buyer_contract_id as contract_id
FROM client_invoices
INNER JOIN contract_additional_info ON contract_additional_info.contract_id =client_invoices.contract_id
INNER JOIN contract ON contract_additional_info.buyer_contract_id = contract.id
WHERE  client_invoices.status=3 ;
</code>```

It is giving me duplicate records ,how to fix the query such that it only gives unique records (unique client_invoice.supplier_invoice_number)

答:
You can start by assuming that one of the joins is returning multiple results which causes the duplicates:

Either multiple contract_additional_info returned for each invoice or multiple contracts for each contract_additional_info.

Based on their names, I would say the former is causing this.  If this is true, ask yourself if that is correct.  Maybe the database structure is your problem.

If it is correct and you can have the same invoice for multiple contract_additional_info entries, then GROUP BY the column(s) you expect to be unique (check that they are unique at the column level as well). E.g. supplier invoice number and/or client_invoices.contract_id.

You could also join with a SELECT DISTINCT sub query from the contract_additional_info table.

Body:
I have three tables client_invoices ,contract_additional_info and contract out of which
client_invoices is connected with contract_additional_info  and contract_additional_info is connected with contract table .

contract table and client_invoices table don't have any relations.

Now I am running following query

SELECT   client_invoices.markup_type,
         client_invoices.supplier_invoice_number,
         client_invoices.client_payment_req_id,
         client_invoices.net_amount,
         client_invoices.markup_value,
         client_invoices.net_qty,
         client_invoices.markup_value,
         contract.clientId as buyerClientId,
         contract_additional_info.buyer_contract_id as contract_id
FROM client_invoices
INNER JOIN contract_additional_info ON contract_additional_info.contract_id =client_invoices.contract_id
INNER JOIN contract ON contract_additional_info.buyer_contract_id = contract.id
WHERE  client_invoices.status=3 ;

It is giving me duplicate records ,how to fix the query such that it only gives unique records (unique client_invoice.supplier_invoice_number)


问:
Nvidia Quadro P2000 and Quadro K5000 compatibility with tensorflow 2.x version
I have Nvidia Quadro P2000 and Quadro K5000 on my computer and I've been trying to use them to run TensorFlow-GPU, but so far TensorFlow doesn't recognize them. I've updated the GPU drivers, installed Cuda toolkit 10.1 and 11, neither one worked.

I was wondering if these two GPUs are not compatible at all with Tensorflow 2.x. I've used Quadro P2000 before, with Tensorflow 1.13, however, I developed my code using Tensorflow 2.x so Keras and Tensorflow are merged, it would be a headache to write everything from scratch based on Tensorflow.1.13.

if they are compatible, what might be the issue?

Thanks in advance,

答:
I just set-up my Quadro K5000 to work with tensorflow 2.1 (on Windows 10). It only worked for me with version 2.0 and 2.1; my understanding is that K5000 compute capability is too low for later versions - see https://developer.nvidia.com/cuda-gpus for the list of compute capability per cards.
You may want to try with tensorflow 2.0 or 2.1</p>


问:
How to know when a table has finished updating
I have a data table that I update with the following code

ActiveWorkbook.Connections("Query - My_Table").Refresh

This data feed the data of some pivot tables.

And I have two buttons. One to update the data table and one to update the pivot tables. I was wondering, if there any way to know when a data table has finished refreshing so I know then I can press the button to refresh the pivot tables?

Update: some people have been asking why I don't update the data table and the pivot table in the same piece of code.

The issue with that is if for example I do the following

```<code>ActiveWorkbook.Connections("Query - My_Table").Refresh
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
</code>```

then the code will start updating the data table and then update the pivot table. so it doesn't wait until my data table has finished refreshing.

答: I had similar problem. I solved it by disabling the background refresh in the connection properties of the query. This forces the query to finish before the next step of the code is performed. I suppose you could put this also on the code itself (disabling first, enabling after)</p>

Body:
I have a data table that I update with the following code

ActiveWorkbook.Connections("Query - My_Table").Refresh

This data feed the data of some pivot tables.

And I have two buttons. One to update the data table and one to update the pivot tables. I was wondering, if there any way to know when a data table has finished refreshing so I know then I can press the button to refresh the pivot tables?

Update: some people have been asking why I don't update the data table and the pivot table in the same piece of code.

The issue with that is if for example I do the following

ActiveWorkbook.Connections("Query - My_Table").Refresh
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh

then the code will start updating the data table and then update the pivot table. so it doesn't wait until my data table has finished refreshing.


问:
Print details of an employee by entering the name of employee in Python
I am getting input of details of the employee from the user and then asking the user to enter the name of the employee, he wants to retrieve information of. I am saving all the entered data in a dictionary with employee name as its key and [employee_id, salary, address] as the values. Now whatever name I enter to retrieve the details, the output is always the details of the last entered employee.

```<code>    n = int(input('Enter the number of employee: '))
    employees = {}

    for i in range(n):
        name = input('Enter the name of the employee: ')
        emp_id = input("Enter employee Id: ")
        sal = int(input("Enter the employee salary: "))
        address = input('Enter the employee address: ')
        employees[name] = [emp_id, sal, address]

    while True:
        name = input('Enter employee name: ')
        info = employees.get(name, -1)
        if info == -1:
            print('Employee does not exist')
        else:
            print('Employee details are: \n Employee Id: ', emp_id, '\n Salary: ', sal, '\n Address: ', address)

        exit_choice = input('Do you want to exit [Yes|No]: ')
        if exit_choice == 'No' or exit_choice == 'no':
            break
</code>```

I want to get the output as the details of the employee whose name is entered. Please can you help me get out of this situation?

答:
You're not printing the information you got from the dictionary. You need to get that from info.

```<code>   while True:
        name = input('Enter employee name: ')
        info = employees.get(name, -1)
        if info == -1:
            print('Employee does not exist')
        else:
            emp_id sal, address = info
            print('Employee details are: \n Employee Id: ', emp_id, '\n Salary: ', sal, '\n Address: ', address)

        exit_choice = input('Do you want to exit [Yes|No]: ')
        if exit_choice == 'No' or exit_choice == 'no':
            break
</code>```

Body:
I am getting input of details of the employee from the user and then asking the user to enter the name of the employee, he wants to retrieve information of. I am saving all the entered data in a dictionary with employee name as its key and [employee_id, salary, address] as the values. Now whatever name I enter to retrieve the details, the output is always the details of the last entered employee.

    n = int(input('Enter the number of employee: '))
    employees = {}

    for i in range(n):
        name = input('Enter the name of the employee: ')
        emp_id = input("Enter employee Id: ")
        sal = int(input("Enter the employee salary: "))
        address = input('Enter the employee address: ')
        employees[name] = [emp_id, sal, address]

    while True:
        name = input('Enter employee name: ')
        info = employees.get(name, -1)
        if info == -1:
            print('Employee does not exist')
        else:
            print('Employee details are: \n Employee Id: ', emp_id, '\n Salary: ', sal, '\n Address: ', address)

        exit_choice = input('Do you want to exit [Yes|No]: ')
        if exit_choice == 'No' or exit_choice == 'no':
            break

I want to get the output as the details of the employee whose name is entered. Please can you help me get out of this situation?

Body:
You're not printing the information you got from the dictionary. You need to get that from info.

   while True:
        name = input('Enter employee name: ')
        info = employees.get(name, -1)
        if info == -1:
            print('Employee does not exist')
        else:
            emp_id sal, address = info
            print('Employee details are: \n Employee Id: ', emp_id, '\n Salary: ', sal, '\n Address: ', address)

        exit_choice = input('Do you want to exit [Yes|No]: ')
        if exit_choice == 'No' or exit_choice == 'no':
            break


问:
Django admin: How to display the field marked as "editable=False" in the model?
Even though a field is marked as 'editable=False' in the model, I would like the admin page to display it. Currently, it hides the field altogether.. How can this be achieved?

答:
You can try this</p>
```<code>@admin.register(AgentLinks)
class AgentLinksAdmin(admin.ModelAdmin):
    readonly_fields = ('link', )
</code>```

Body:
You can try this

@admin.register(AgentLinks)
class AgentLinksAdmin(admin.ModelAdmin):
    readonly_fields = ('link', )


问:
How to zip two lists with duplicate elements?
There are two lists

```<code>l1 = ['k1','k2','k3','k3','k4', 'k5']
l2 = ["1.2.3","abc-2.3.4","xyz-def-5.6.8", "xyz-def-5.6.7","ghjb-5.6.7","7.8.9"]
</code>```

I need to get these items as key:value pair in a dictionary, along with highest value of duplicate elements. Since dictionary holds the unique keys, one of the duplicate elements will be overridden.

```<code>print(dict(zip(l1, l2)))
{'k1': '1.2.3', 'k2': 'abc-2.3.4', 'k3': 'xyz-def-5.6.7', 'k4': 'ghjb-5.6.7', 'k5': '7.8.9'}
</code>```

but from above output, i need highest value xyz-def-5.6.8 instead of xyz-def-5.6.7

Tried, print(list(zip(l1, l2))), output as below

```<code>[('k1', '1.2.3'), ('k2', 'abc-2.3.4'), ('k3', 'xyz-def-5.6.8'), ('k3', 'xyz-def-5.6.7'), ('k4', 'ghjb-5.6.7'), ('k5', '7.8.9')]
</code>```

How do I achieve it ?

Is it possible to format this list of tuples or any other way to get desired ?

```<code>l1 = ['k1','k2','k3','k3','k4', 'k5', 'k6', 'k7', 'k6']
l2 = ["1.2.3","abc-2.3.4","xyz-def-5.6.8", "xyz-def-5.6.7","ghjb-5.6.7","7.8.9", "1:2.3.4-3ubuntu0.1", "1.2.3-1.2build3", "1:2.3.4-3ubuntu0.2"]
</code>```

These can't be same format across all the keys but it can be same across the certain duplicate keys, Say k6 has one format, k3 has another format.

Body:
There are two lists

l1 = ['k1','k2','k3','k3','k4', 'k5']
l2 = ["1.2.3","abc-2.3.4","xyz-def-5.6.8", "xyz-def-5.6.7","ghjb-5.6.7","7.8.9"]

I need to get these items as key:value pair in a dictionary, along with highest value of duplicate elements. Since dictionary holds the unique keys, one of the duplicate elements will be overridden.

print(dict(zip(l1, l2)))
{'k1': '1.2.3', 'k2': 'abc-2.3.4', 'k3': 'xyz-def-5.6.7', 'k4': 'ghjb-5.6.7', 'k5': '7.8.9'}

but from above output, i need highest value xyz-def-5.6.8 instead of xyz-def-5.6.7

Tried, print(list(zip(l1, l2))), output as below

[('k1', '1.2.3'), ('k2', 'abc-2.3.4'), ('k3', 'xyz-def-5.6.8'), ('k3', 'xyz-def-5.6.7'), ('k4', 'ghjb-5.6.7'), ('k5', '7.8.9')]

How do I achieve it ?

Is it possible to format this list of tuples or any other way to get desired ?

l1 = ['k1','k2','k3','k3','k4', 'k5', 'k6', 'k7', 'k6']
l2 = ["1.2.3","abc-2.3.4","xyz-def-5.6.8", "xyz-def-5.6.7","ghjb-5.6.7","7.8.9", "1:2.3.4-3ubuntu0.1", "1.2.3-1.2build3", "1:2.3.4-3ubuntu0.2"]

These can't be same format across all the keys but it can be same across the certain duplicate keys, Say k6 has one format, k3 has another format.

Body:
l1 = ['k1','k2','k3','k3','k4', 'k5']
l2 = ["1.2.3","abc-2.3.4","xyz-def-5.6.8", "xyz-def-5.6.7","ghjb-5.6.7","7.8.9"]

let zipYourArray = zip(l1, l2)

for pair in zipYourArray {

 print("\(pair.0): \(pair.1)")

}

// output : {

 'k1': '1.2.3',
 'k2': 'abc-2.3.4',
 'k3': 'xyz-def-5.6.8',
 'k4': 'ghjb-5.6.7',
 'k5': '7.8.9'

}


问:
What’s the best way to load a JSONObject from a json text file?
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

```<code>XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));
</code>```

The output is:

```<code>Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)
</code>```

答:
```<code>import org.springframework.transaction.annotation.Transactional;
import org.springframework.core.io.ByteArrayResource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.minidev.json.JSONObject;

    String filename = "xyz.json";

    @Transactional
        public Object getFileInternalJsonData(String filename) {
            try {
                ByteArrayResource inputStream = new ByteArrayResource(Files.readAllBytes(Paths.get("D:\MyData\test\" + File.separator + filename)));
                return new ObjectMapper().readValue(inputStream.getInputStream(), Object.class);
            } catch (Exception e) {
                return new JSONObject().appendField("error", e.getMessage());
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));

The output is:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)


问:
How to run 'rebuild project' from the command line

Some Context:

I am working on a Continuous Integration pipeline with MSBuild for a large project that includes an Android application.  This application includes some automatically generated files that need to be integrated into the project regularly.  This is usually accomplished by manually copying them over and selecting Build->rebuild project in android studio.

This step is necessary since the project also makes use of AndroidAnnotations, which generates classes at compile time.

The Problem:

I haven't found any documentation for what is run when you select 'rebuild project' in android studio.

What I Have Tried:

How to Rebuild and Run android project from command line

as well as:

What is happened after I run rebuild project in Android studio?

But the doccumentation here doesn't talk about the rebuild command, and a 6 week udacity course isn't a helpful resource either.

When I hit 'rebuild project' the Android Studio event log reads:

Executing tasks: [clean, :app:generateDevelopmentDebugSources, :app:generateDevelopmentDebugAndroidTestSources, :app:prepareDevelopmentDebugUnitTestDependencies, :app:mockableAndroidJar, :app:compileDevelopmentDebugSources, :app:compileDevelopmentDebugAndroidTestSources, :app:compileDevelopmentDebugUnitTestSources]

Which I have run in the command line as follows:

gradlew.bat clean :app:generateDevelopmentDebugSources :app:generateDevelopmentDebugAndroidTestSources :app:prepareDevelopmentDebugUnitTestDependencies :app:mockableAndroidJar :app:compileDevelopmentDebugSources :app:compileDevelopmentDebugAndroidTestSources :app:compileDevelopmentDebugUnitTestSources

The command executes, but the build finishes with several hundred errors, which also occur when you try to compile or clean without first running rebuild.  Obviously this command is incomplete.

When I look at the Gradle Console in Android Studio I see a couple of dozen targets that are run, but I'm hesitant to copy-paste those, as I have no idea what small changes to the project will necessitate different targets to be run.

I've narrowed down my issue to the :app:compileDevelopmentDebugUnitTestJavaWithJavac target.  This target requires one of the other targets listed in the Gradle Console, but I don't know which one.

Those targets have to be coming from somewhere, but where?

tl;dr:

How can I do all the things that Android Studio does when I run 'rebuild project' from the command line?

答:
Please open build view in Android Studio, when you select from menu: Build -> Rebuild Project on the top in build view you will see which tasks were triggered by Android Studio: Executing tasks: [clean, :assembleDebug] in project ...

And now you can try to do this from command line:

./gradlew clean assembleRelease


问:
Variables get corrupted
I’m developing an iPhone App using Objective-C, based on Apple’s UIKit.

I’ve created some class instance in UIViewController and found my class instance pointer get corrupted randomly. Due to class instance pointer corrupted, I always get an EXC_BAD_ACCESS crash like this:
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Codes: KERN_INVALID_ADDRESS at 0xa095633c
    Crashed Thread:  0

It shows that when my code is trying to access the class instance, it’s already turned into a ridiculous address:0xa095633c, which is beyond memory space and even binary image space.

Does any have any suggestion what kind of incorrect coding could possibly lead to class instance get corrupted?

答: The most likely cause of this kind of error is the object getting deallocated prematurely and some other memory is getting written in its place. Try turning on Zombies in Instruments and it will tell you if this is the case.</p>

Title: Variables get corrupted


问:
Receive numbers till the input is number that % 7 is without remainder
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

```<code>let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }
</code>```

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?

答:
Either bring out the else if (num == 0) part before while loop

since 0 % 7 == 0 is true it should satisfy the excersise even if it's not in the loop.

```<code>if (num == 0) {
  // do stuff
}
while (/* condition */) {
  // do other stuff
}
</code>```

Or add num == 0 constraint in while condition.

```<code>while (num == 0 || num % 7 != 0) {
  // do stuff
}
</code>```

The former will not get into the loop, the latter will cause the loop to exit on num == 0 because both implies that it's a correct modulo division.

You can do both if you want to optimize memory usage (obviously it wouldn't be a problem in this scale).

Body:
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?

Body:
Either bring out the else if (num == 0) part before while loop

since 0 % 7 == 0 is true it should satisfy the excersise even if it's not in the loop.

if (num == 0) {
  // do stuff
}
while (/* condition */) {
  // do other stuff
}

Or add num == 0 constraint in while condition.

while (num == 0 || num % 7 != 0) {
  // do stuff
}

The former will not get into the loop, the latter will cause the loop to exit on num == 0 because both implies that it's a correct modulo division.

You can do both if you want to optimize memory usage (obviously it wouldn't be a problem in this scale).


问:
Redux State is set also to other State that is not Related
Programming is weird, if you think not then check this case , I'm using createSlices as Redux and I have two slices with their own states.

First one is orderSlice:

export const orderSlice = createSlice({
  name: 'order',
  initialState: {
    order: null,
    message: null,
    isLoading: true,
  }
})
```
<p>While the second slice is <code>ordersSlice</code>:</p>
<pre class="lang-js prettyprint-override"><code>export const orderSlice = createSlice({
  name: 'orders',
  initialState: {
    orders: null,
    message: null,
    isLoading: true,
  }
})
</code>```

And I have this method to fetch the order and the fulfilled phase where the state is set from:

Fetching the order:

export const fetchOrder = createAsyncThunk('', async ({ token, id }) => {
  const requestOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
    },
  };
  try {
    const response = await fetch(`${api}/orders/view/${id}`, requestOptions);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
});
```
<p>Filling the order state:</p>
<pre class="lang-js prettyprint-override"><code>extraReducers: {
    [fetchOrder.fulfilled]: (state, action) => {
      state.order = action.payload.data;
      state.message = 'Succesfully fetched the Order.';
      state.isLoading = false;
    }
  }
</code>```

While here is method for fetching the orders:

export const fetchAllOrders = createAsyncThunk('', async (token) => {
  const requestOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
    },
  };
  try {
    const response = await fetch(`${api}/orders/all`, requestOptions);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
});
```
<p>And here updating the orders state:</p>
<pre class="lang-js prettyprint-override"><code>extraReducers: {
    [fetchAllOrders.fulfilled]: (state, action) => {
      state.orders = action.payload.data;
      state.message = 'Succesfully fetched all Orders.';
      state.isLoading = false;
    }
  }
</code>```

So the case is that I'm calling the fetchAllOrders in the Order page with UseEffect, here is how:

  import { fetchAllOrders } from '../redux/ordersSlice';
  useEffect(() => dispatch(fetchAllOrders(user.token)), [user]);
```
<p>So this is how i run the method to fetch orders with dispatch and it works. But the problem is that when I run this function beside the <code>orders</code> state that is filled with the same data, also the <code>order</code> state is filled with the same data and this is impossible as I've cheked all the cases where I could misstyped a user,users typo but there is none I found, and I don't know.</p>
<p>And here is the store:</p>
<pre class="lang-js prettyprint-override"><code>import orderSlice from './redux/orderSlice';
import ordersSlice from './redux/ordersSlice';

const store = configureStore({
  reducer: {
    order: orderSlice,
    orders: ordersSlice
  },
});

</code>```

答:
You have to give your thunks an unique name: If you name both '' they will be handled interchangably.

Also, you should be using the builder notation for extraReducers. We will deprecate the object notation you are using soon.

Body:
Programming is weird, if you think not then check this case , I'm using createSlices as Redux and I have two slices with their own states.

First one is orderSlice:

export const orderSlice = createSlice({
  name: 'order',
  initialState: {
    order: null,
    message: null,
    isLoading: true,
  }
})

While the second slice is ordersSlice:

export const orderSlice = createSlice({
  name: 'orders',
  initialState: {
    orders: null,
    message: null,
    isLoading: true,
  }
})

And I have this method to fetch the order and the fulfilled phase where the state is set from:

Fetching the order:

export const fetchOrder = createAsyncThunk('', async ({ token, id }) => {
  const requestOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
    },
  };
  try {
    const response = await fetch(`${api}/orders/view/${id}`, requestOptions);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
});

Filling the order state:

extraReducers: {
    [fetchOrder.fulfilled]: (state, action) => {
      state.order = action.payload.data;
      state.message = 'Succesfully fetched the Order.';
      state.isLoading = false;
    }
  }

While here is method for fetching the orders:

export const fetchAllOrders = createAsyncThunk('', async (token) => {
  const requestOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
    },
  };
  try {
    const response = await fetch(`${api}/orders/all`, requestOptions);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
});

And here updating the orders state:

extraReducers: {
    [fetchAllOrders.fulfilled]: (state, action) => {
      state.orders = action.payload.data;
      state.message = 'Succesfully fetched all Orders.';
      state.isLoading = false;
    }
  }

So the case is that I'm calling the fetchAllOrders in the Order page with UseEffect, here is how:

  import { fetchAllOrders } from '../redux/ordersSlice';
  useEffect(() => dispatch(fetchAllOrders(user.token)), [user]);

So this is how i run the method to fetch orders with dispatch and it works. But the problem is that when I run this function beside the orders state that is filled with the same data, also the order state is filled with the same data and this is impossible as I've cheked all the cases where I could misstyped a user,users typo but there is none I found, and I don't know.

And here is the store:

import orderSlice from './redux/orderSlice';
import ordersSlice from './redux/ordersSlice';

const store = configureStore({
  reducer: {
    order: orderSlice,
    orders: ordersSlice
  },
});


问:
Identify Folders in Sub-Folder
I have a working directory with the following content

```<code>readdir()

6-element Vector{String}:
 "Manifest.toml"
 "Project.toml"
 "Report"
 "main.jl"
 "src"
 "test.jl"
</code>```

I can identify folders here:

```<code>filter(isdir, readdir())

2-element Vector{String}:
 "Report"
 "src"
</code>```

And I can show the content of the sub-folder Report:

```<code>readdir("Report/")

3-element Vector{String}:
 "jl_ACKKIu"
 "jl_zfa8Ys"
 "test.pdf"
</code>```

So, why can I not identify folders in the sub-folder?

```<code>filter(isdir, readdir("Report/"))

String[]
</code>```

答:
readdir contains paths relative to the input directory and isdir then interprets these paths as relative to the current working directory (see pwd).

Since Julia 1.4 you can pass join=true as a keyword argument to readdir, such that the returned paths are joined with the input path:

```<code>shell> tree .
.
├── DirectoryB
│   ├── DirectoryC
│   └── FileB
└── FileA

2 directories, 2 files

julia> readdir("DirectoryB")
2-element Vector{String}:
 "DirectoryC"
 "FileB"

julia> readdir("DirectoryB"; join=true)
2-element Vector{String}:
 "DirectoryB/DirectoryC"
 "DirectoryB/FileB"

julia> filter(isdir, ans)
1-element Vector{String}:
 "DirectoryB/DirectoryC"
</code>```

Title: Identify Folders in Sub-Folder

Body:
I have a working directory with the following content

readdir()

6-element Vector{String}:
 "Manifest.toml"
 "Project.toml"
 "Report"
 "main.jl"
 "src"
 "test.jl"

I can identify folders here:

filter(isdir, readdir())

2-element Vector{String}:
 "Report"
 "src"

And I can show the content of the sub-folder Report:

readdir("Report/")

3-element Vector{String}:
 "jl_ACKKIu"
 "jl_zfa8Ys"
 "test.pdf"

So, why can I not identify folders in the sub-folder?

filter(isdir, readdir("Report/"))

String[]

Body:
readdir contains paths relative to the input directory and isdir then interprets these paths as relative to the current working directory (see pwd).

Since Julia 1.4 you can pass join=true as a keyword argument to readdir, such that the returned paths are joined with the input path:

shell> tree .
.
├── DirectoryB
│   ├── DirectoryC
│   └── FileB
└── FileA

2 directories, 2 files

julia> readdir("DirectoryB")
2-element Vector{String}:
 "DirectoryC"
 "FileB"

julia> readdir("DirectoryB"; join=true)
2-element Vector{String}:
 "DirectoryB/DirectoryC"
 "DirectoryB/FileB"

julia> filter(isdir, ans)
1-element Vector{String}:
 "DirectoryB/DirectoryC"


问:
Using regex to drop duplicated elements in columns of an R dataframe
I have a dummy dataframe df which has dimensions 6 X 4.

```<code>df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5", "Hit6"),
 GO = c("GO:0005634~nucleus,", "", "GO:0005737~cytoplasm,", "GO:0005634~nucleus,GO:0005737~cytoplasm,", "",
            "GO:0005634~nucleus,GO:0005654~nucleoplasm,"),
 KEGG = c("", "", "", "", "", ""),
 SMART = c("SM00394:RIIa,", "SM00394:RIIa,", "", "SM00054:EFh,",
            "", "SM00394:RIIa,SM00239:C2,"))
</code>```

df looks like this

The elements in the columns consist of two parts:

an identifier (e.g. GO:0005634~, SM00394: etc.)

a term (e.g. nucleus, EFh etc.)

For each column I want to retain a row if it contains atleast one term which is not present in any row above it. e.g. in the column GO rows 1 and 3 contain unique terms, so these should be retained. Row 4 contains terms which are already present in rows 1 and 3, so it should be dropped. Row 6 has one term which is not present in any row above it, hence it should also be retained.

I have been able to come up with regular expressions to extract the terms from the columns GO and SMART

```<code>Regex for GO: (?<=~).*?(?=,(?:GO:\\d+~|$))
Regex for SMART: (?<=:).*?(?=,(?:\\w+\\d+:|$))
</code>```

But I'm unable to figure out a way to integrate the regex and the conditions mentioned above into a solution. The output should look like this

Any suggestions on how to solve this?

答:
The following algorithm is applied to each term (GO, SMART, KEGG):

extract the identifier+term list as comma-separated. See stringr::str_split etc.

extract the term as regex

cumulate all the terms along the dataframe as they appear

extract the difference between each row and the row immediately preceding

replace the string with "" if no new term is introduced

filter rows where not all the terms are ""

library(dplyr)
library(stringr)
library(purrr)

termred <- function(terms, rx) {
  terms |>
    stringr::str_split(",") |>
    purrr::map(stringr::str_trim) |>
    purrr::map(~{.x[.x != ""]}) |>
    purrr::map(~stringr::str_extract(.x, rx)) |>
    purrr::accumulate(union) %>%
    {mapply(setdiff, ., lag(., 1), SIMPLIFY = TRUE)} %>%
    {ifelse(sapply(., length) > 0, terms, "")}
}

df |>
  transform(GO = termred(GO, "~.*$")) |>
  transform(SMART =  termred(SMART, ":.*$")) |>
  filter(GO != "" | SMART != ""| KEGG != "")
##>  Hits                                         GO KEGG                    SMART
##>1 Hit1                        GO:0005634~nucleus,                 SM00394:RIIa,
##>2 Hit3                      GO:0005737~cytoplasm,
##>3 Hit4                                                             SM00054:EFh,
##>4 Hit6 GO:0005634~nucleus,GO:0005654~nucleoplasm,      SM00394:RIIa,SM00239:C2,
```

Body:
I have a dummy dataframe df which has dimensions 6 X 4.

df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5", "Hit6"),
 GO = c("GO:0005634~nucleus,", "", "GO:0005737~cytoplasm,", "GO:0005634~nucleus,GO:0005737~cytoplasm,", "",
            "GO:0005634~nucleus,GO:0005654~nucleoplasm,"),
 KEGG = c("", "", "", "", "", ""),
 SMART = c("SM00394:RIIa,", "SM00394:RIIa,", "", "SM00054:EFh,",
            "", "SM00394:RIIa,SM00239:C2,"))

df looks like this

The elements in the columns consist of two parts:

an identifier (e.g. GO:0005634~, SM00394: etc.)

a term (e.g. nucleus, EFh etc.)

For each column I want to retain a row if it contains atleast one term which is not present in any row above it. e.g. in the column GO rows 1 and 3 contain unique terms, so these should be retained. Row 4 contains terms which are already present in rows 1 and 3, so it should be dropped. Row 6 has one term which is not present in any row above it, hence it should also be retained.

I have been able to come up with regular expressions to extract the terms from the columns GO and SMART

Regex for GO: (?<=~).*?(?=,(?:GO:\\d+~|$))
Regex for SMART: (?<=:).*?(?=,(?:\\w+\\d+:|$))

But I'm unable to figure out a way to integrate the regex and the conditions mentioned above into a solution. The output should look like this

Any suggestions on how to solve this?


问:
Run artisan command in laravel 5
I have controller like this

```<code> public function store(Request $request)
{
   Artisan::call("php artisan infyom:scaffold {$request['name']} --fieldsFile=public/Product.json");
}
</code>```

Show me error

There are no commands defined in the "php artisan infyom" namespace.

When I run this command in CMD it work correctly

答:
Remove php artisan part and try:</p>
```<code>Route::get('/run', function () {
    Artisan::call("migrate");
});
</code>```

Title: Run artisan command in laravel 5

Body:
I have controller like this

 public function store(Request $request)
{
   Artisan::call("php artisan infyom:scaffold {$request['name']} --fieldsFile=public/Product.json");
}

Show me error

There are no commands defined in the "php artisan infyom" namespace.

When I run this command in CMD it work correctly

Body:
Remove php artisan part and try:

Route::get('/run', function () {
    Artisan::call("migrate");
});


问:
Is there any way to represent any number as sum of 4 squares?
Is there any way to represent any number as sum of 4 squares.

For example 29 can be represented as 5^2+2^2+0^2+0^2

I tried the following code but some numbers giving 5terms for example 23 as 4^2+2^2+1^2+1^2+1^2

the code i tried is :

```<code> x=0;
 while(num!=0){
          x=(int)Math.floor(Math.sqrt(num));
         num=num-(x*x);
}
</code>```

答:
There is nothing wrong with the code.

23 simply requires 5 terms to solve.

Try counting the number of terms and terminating the loop if the limit of 4 is reached.

EDITED:

See my other (better) answer

Body:
Is there any way to represent any number as sum of 4 squares.

For example 29 can be represented as 5^2+2^2+0^2+0^2

I tried the following code but some numbers giving 5terms for example 23 as 4^2+2^2+1^2+1^2+1^2

the code i tried is :

 x=0;
 while(num!=0){
          x=(int)Math.floor(Math.sqrt(num));
         num=num-(x*x);
}


问:
How to position content beside sidebar?
I am not very well versed in HTML and CSS. I am currently building a web application using Django and I integrated a sidebar into my web application using Bootstrap, but it has messed my layouts, and I can't seem to figure out how to move the content in a block to the left of side of my sidebar.

As seen in the pictures above, my sidebar is located at the top and my content is located at the bottom. Below are my codes for my sidebar and the base template.

sidebar_template.html

```<code><div class="d-flex flex-column vh-100 flex-shrink-0 p-3 text-white bg-dark sidebar-height" style="width: 250px;"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <svg class="bi me-2" width="40" height="32"> </svg> <span class="fs-4">CPRS Admin</span> </a>
    <hr>
    <ul class="nav nav-pills flex-column mb-auto">
        <li class="nav-item"> <a href="#" class="nav-link active" aria-current="page"> <i class="fa fa-home"></i><span class="ms-2">Home</span> </a> </li>
        <li> <a href="{% url 'coordinator_dashboard' %}" class="nav-link text-white"> <i class="fa fa-dashboard"></i><span class="ms-2">Dashboard</span> </a> </li>
        <li> <a href="{% url 'coordinator_view_students' %}" class="nav-link text-white"> <i class="fa fa-first-order"></i><span class="ms-2">Students</span> </a> </li>
        <li> <a href="#" class="nav-link text-white"> <i class="fa fa-cog"></i><span class="ms-2">Settings</span> </a> </li>
        <li> <a href="#" class="nav-link text-white"> <i class="fa fa-bookmark"></i><span class="ms-2">Bookmarks</span> </a> </li>
    </ul>
    <hr>
    <div class="dropdown"> <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false"> <img src="https://github.com/mdo.png" alt="" width="32" height="32" class="rounded-circle me-2"> <strong> John W </strong> </a>
        <ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
            <li><a class="dropdown-item" href="#">New project</a></li>
            <li><a class="dropdown-item" href="#">Settings</a></li>
            <li><a class="dropdown-item" href="#">Profile</a></li>
            <li>
                <hr class="dropdown-divider">
            </li>
            <li><a class="dropdown-item" href="#">Sign out</a></li>
        </ul>
    </div>
</div>
</code>```

base.html

```<code>{% load static %}

<!DOCTYPE html>
<html>
<head>
    <title>Capstone Project</title>
    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <link href="{% static 'css/main.css' %}" rel="stylesheet">
    <link href="{% static 'css/profile.css' %}" rel="stylesheet">
    <link href="{% static 'css/sidebar.css' %}" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

</head>

<body>

    <div class="page-container">
        <div class="content-wrap">
            <div class="">
                {% if user.is_authenticated and user.is_superuser %}
                        {% include 'HOD/sidebar_template.html' %}
                {% endif %}
            </div>
            <div class="col">
                {% block content %}
                {% endblock content %}
            </div>
        </div>
    </div>
    <!-- Optional Javascript -->
    {% block custom_js %}
    {% endblock custom_js %}

</body>
 <!-- Site footer -->
    <footer class="footer">
        <div class="container text-center">
            <small>Copyright © Your Website</small>
        </div>
    </footer>
</html>
</code>```

Can someone help me fix the layouts ? Thanks.

答:
This is a bootstrap issue, not a django issue.
You have to wrap your head around how the bootstrap grid works.

You have to first create a row element which can contain one or more columns. When you create the columns you get to decide their behavior according to screen size, or to just let them figure out their sizing by themselves.

This will create two equally sized columns that will take up whatever width space available.

```<code><div class="row">
    <div class="col">
        content
    </div>
    <div class="col">
        content
    </div>
</div>
</code>```

If you want to define the width of each column in relation to the total width of the page, you can define that when you create the columns. Here you can specify different behaviors for different screen sizes in order to make your site responsive.

```<code> <div class="row">
        <div class="col-3 col-lg-2">
           This column will be 3/12 of the screen on small and medium screens. Or 2/12 of the screen on large screens and up.
        </div>
        <div class="col-9 col-lg-10">
            This column will be 9/12 of the screen on small and medium screens. Or 10/12 of the screen on large screens and up.
        </div>
    </div>
</code>```

And in your specific case i'd suggest something like this:

```<code><div class="page-container">
    <div class="content-wrap">
        <div class="row">
            <div class="col-3">
                {% if user.is_authenticated and user.is_superuser %}
                        {% include 'HOD/sidebar_template.html' %}
                {% endif %}
            </div>
            <div class="col-9">
                {% block content %}
                {% endblock content %}
            </div>
        </div>
    </div>
</div>
</code>```

Title: How to position content beside sidebar?

Body:
I am not very well versed in HTML and CSS. I am currently building a web application using Django and I integrated a sidebar into my web application using Bootstrap, but it has messed my layouts, and I can't seem to figure out how to move the content in a block to the left of side of my sidebar.

As seen in the pictures above, my sidebar is located at the top and my content is located at the bottom. Below are my codes for my sidebar and the base template.

sidebar_template.html

  <svg class="bi me-2" width="40" height="32"> </svg> CPRS Admin

  Home

  Dashboard

  Students

  Settings

  Bookmarks

    John W

New project

Settings

Profile

Sign out

base.html

{% load static %}

<!DOCTYPE html>

    <title>Capstone Project</title>
    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">

    <link href="{% static 'css/main.css' %}" rel="stylesheet">
    <link href="{% static 'css/profile.css' %}" rel="stylesheet">
    <link href="{% static 'css/sidebar.css' %}" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

                {% if user.is_authenticated and user.is_superuser %}
                        {% include 'HOD/sidebar_template.html' %}
                {% endif %}

                {% block content %}
                {% endblock content %}

    {% block custom_js %}
    {% endblock custom_js %}

            Copyright © Your Website

Can someone help me fix the layouts ? Thanks.

Body:
This is a bootstrap issue, not a django issue.
You have to wrap your head around how the bootstrap grid works.

You have to first create a row element which can contain one or more columns. When you create the columns you get to decide their behavior according to screen size, or to just let them figure out their sizing by themselves.

This will create two equally sized columns that will take up whatever width space available.

<div class="row">
    <div class="col">
        content
    </div>
    <div class="col">
        content
    </div>
</div>

If you want to define the width of each column in relation to the total width of the page, you can define that when you create the columns. Here you can specify different behaviors for different screen sizes in order to make your site responsive.

 <div class="row">
        <div class="col-3 col-lg-2">
           This column will be 3/12 of the screen on small and medium screens. Or 2/12 of the screen on large screens and up.
        </div>
        <div class="col-9 col-lg-10">
            This column will be 9/12 of the screen on small and medium screens. Or 10/12 of the screen on large screens and up.
        </div>
    </div>

And in your specific case i'd suggest something like this:

<div class="page-container">
    <div class="content-wrap">
        <div class="row">
            <div class="col-3">
                {% if user.is_authenticated and user.is_superuser %}
                        {% include 'HOD/sidebar_template.html' %}
                {% endif %}
            </div>
            <div class="col-9">
                {% block content %}
                {% endblock content %}
            </div>
        </div>
    </div>
</div>


问:
Would you please explain me. What is the following R operation
```<code>dt_modAdstocked[, (all_media) := mediaAdstocked]
</code>```

Context
https://github.com/facebookexperimental/Robyn/blob/main/R/R/model.R#L455

Details
I am new to R, reading the code and lost what this operation is doing, is it assignment? something else?

答:
This is syntax used by the R package data.table. Refer to the documentation here.
Your pattern is of type DT[i, (colvector) := val] and it is to assign a value val to multiple columns colvector at the rows ì. Here is an example to assign greatness and fanciness to all rows (DT[, (colvector) := val]) of the iris flowers:

library(data.table)

data <- data.table(iris)
data
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#>   1:          5.1         3.5          1.4         0.2    setosa
#>   2:          4.9         3.0          1.4         0.2    setosa
#>   3:          4.7         3.2          1.3         0.2    setosa
#>   4:          4.6         3.1          1.5         0.2    setosa
#>   5:          5.0         3.6          1.4         0.2    setosa
#>  ---
#> 146:          6.7         3.0          5.2         2.3 virginica
#> 147:          6.3         2.5          5.0         1.9 virginica
#> 148:          6.5         3.0          5.2         2.0 virginica
#> 149:          6.2         3.4          5.4         2.3 virginica
#> 150:          5.9         3.0          5.1         1.8 virginica
colvector <- c("is_fancy", "is_great")
data[, (colvector) := TRUE]
data
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species is_fancy
#>   1:          5.1         3.5          1.4         0.2    setosa     TRUE
#>   2:          4.9         3.0          1.4         0.2    setosa     TRUE
#>   3:          4.7         3.2          1.3         0.2    setosa     TRUE
#>   4:          4.6         3.1          1.5         0.2    setosa     TRUE
#>   5:          5.0         3.6          1.4         0.2    setosa     TRUE
#>  ---
#> 146:          6.7         3.0          5.2         2.3 virginica     TRUE
#> 147:          6.3         2.5          5.0         1.9 virginica     TRUE
#> 148:          6.5         3.0          5.2         2.0 virginica     TRUE
#> 149:          6.2         3.4          5.4         2.3 virginica     TRUE
#> 150:          5.9         3.0          5.1         1.8 virginica     TRUE
#>      is_great
#>   1:     TRUE
#>   2:     TRUE
#>   3:     TRUE
#>   4:     TRUE
#>   5:     TRUE
#>  ---
#> 146:     TRUE
#> 147:     TRUE
#> 148:     TRUE
#> 149:     TRUE
#> 150:     TRUE
```

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
dt_modAdstocked[, (all_media) := mediaAdstocked]

Context
https://github.com/facebookexperimental/Robyn/blob/main/R/R/model.R#L455

Details
I am new to R, reading the code and lost what this operation is doing, is it assignment? something else?

Body:
This is syntax used by the R package data.table. Refer to the documentation here.
Your pattern is of type DT[i, (colvector) := val] and it is to assign a value val to multiple columns colvector at the rows ì. Here is an example to assign greatness and fanciness to all rows (DT[, (colvector) := val]) of the iris flowers:

library(data.table)

data <- data.table(iris)
data
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#>   1:          5.1         3.5          1.4         0.2    setosa
#>   2:          4.9         3.0          1.4         0.2    setosa
#>   3:          4.7         3.2          1.3         0.2    setosa
#>   4:          4.6         3.1          1.5         0.2    setosa
#>   5:          5.0         3.6          1.4         0.2    setosa
#>  ---
#> 146:          6.7         3.0          5.2         2.3 virginica
#> 147:          6.3         2.5          5.0         1.9 virginica
#> 148:          6.5         3.0          5.2         2.0 virginica
#> 149:          6.2         3.4          5.4         2.3 virginica
#> 150:          5.9         3.0          5.1         1.8 virginica
colvector <- c("is_fancy", "is_great")
data[, (colvector) := TRUE]
data
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species is_fancy
#>   1:          5.1         3.5          1.4         0.2    setosa     TRUE
#>   2:          4.9         3.0          1.4         0.2    setosa     TRUE
#>   3:          4.7         3.2          1.3         0.2    setosa     TRUE
#>   4:          4.6         3.1          1.5         0.2    setosa     TRUE
#>   5:          5.0         3.6          1.4         0.2    setosa     TRUE
#>  ---
#> 146:          6.7         3.0          5.2         2.3 virginica     TRUE
#> 147:          6.3         2.5          5.0         1.9 virginica     TRUE
#> 148:          6.5         3.0          5.2         2.0 virginica     TRUE
#> 149:          6.2         3.4          5.4         2.3 virginica     TRUE
#> 150:          5.9         3.0          5.1         1.8 virginica     TRUE
#>      is_great
#>   1:     TRUE
#>   2:     TRUE
#>   3:     TRUE
#>   4:     TRUE
#>   5:     TRUE
#>  ---
#> 146:     TRUE
#> 147:     TRUE
#> 148:     TRUE
#> 149:     TRUE
#> 150:     TRUE

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
express-session req.session.touch not a function?
I'm working on a personal project, recently included express-session and cookie-session. Though i'm having a problem when navigating to localhost:3000/, i get an error telling me that req.session.touch is not a function in express-session module. Below you can find a snippet of the code:

```<code>const express = require('express');
const bodyParser = require('body-parser');
const _ = require('lodash');
const passport = require('passport')
const LocalStrategy = require('passport-local')
const cookieParser = require('cookie-parser');
const session = require('express-session')
let cookieSession = require('cookie-session')
const pug = require('pug');
require('./db/mongoose');
const mongoose = require('mongoose');
const Todo = mongoose.model('Todo');
const User = mongoose.model('User');
let app = express();
const ObjectID = require('valid-objectid');

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

//Use session
app.use(session({ secret: 'secretomitted', cookie: { maxAge: 0 } }))

//Set cookie session
app.use(cookieParser())
app.use(cookieSession({ name: 'session', secret: 'secretomitted', maxAge: 0 }))

//Set views folder and view engine
app.set('views', './views');
app.set('view engine', 'pug');

passport.use(new LocalStrategy(
  function (email, password, done) {
    User.findOne({ 'email': email }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, console.log('Wrong username'));
      }
      if (!user.validatePassword(password)) {
        return done(null, false, console.log('Wrong Password'));
      }
      return done(null, user);
    });
  }
));

//FE Requests

app.get('/', (req, res) => {
  res.send(pug.renderFile('index.pug'))
  console.log('index rendered')
})
</code>```

and this is the error i'm getting:

```<code>[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server/server.js`
express-session deprecated undefined resave option; provide resave option server/server.js:24:9
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option server/server.js:24:9
Started on port 3000
/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/express-session/index.js:326
        req.session.touch()
                    ^

TypeError: req.session.touch is not a function
    at ServerResponse.end (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/express-session/index.js:326:21)
    at Array.write (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/finalhandler/index.js:297:9)
    at listener (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/on-finished/index.js:169:15)
    at onFinish (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/on-finished/index.js:100:5)
    at callback (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/ee-first/index.js:55:10)
    at IncomingMessage.onevent (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/ee-first/index.js:93:5)
    at IncomingMessage.emit (events.js:197:13)
    at endReadableNT (_stream_readable.js:1129:12)
    at processTicksAndRejections (internal/process/next_tick.js:76:17)
[nodemon] app crashed - waiting for file changes before starting...

</code>```

Any solution to this? Thanks.

答:
TL;DR: Only use one session management, for custom session information extend the session object don't overwrite it.

Old question, but I had the same issue, so for anyone else trying to accomplish the same thing :) . I believe that the problem is some sort of conflict from different session objects:

//Use session
app.use(session({ secret: 'secretomitted', cookie: { maxAge: 0 } }))

//Set cookie session
app.use(cookieParser())
app.use(cookieSession({ name: 'session', secret: 'secretomitted', maxAge: 0 }))
```

This is using express-session AND cookie-session. Here is a quote from expressjs.com:

A user session can be stored in two main ways with cookies: on the server or on the client. [cookie-session] stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.

As explained above, express-session only stores an ID in the cookie, while cookie-session stores all session data in the cookie. This very short blog post explains how messing with the session data will cause your error. The two types of session storage will inevitably cause such a conflict, since they are trying to store the data in different places.

Body:
I'm working on a personal project, recently included express-session and cookie-session. Though i'm having a problem when navigating to localhost:3000/, i get an error telling me that req.session.touch is not a function in express-session module. Below you can find a snippet of the code:

const express = require('express');
const bodyParser = require('body-parser');
const _ = require('lodash');
const passport = require('passport')
const LocalStrategy = require('passport-local')
const cookieParser = require('cookie-parser');
const session = require('express-session')
let cookieSession = require('cookie-session')
const pug = require('pug');
require('./db/mongoose');
const mongoose = require('mongoose');
const Todo = mongoose.model('Todo');
const User = mongoose.model('User');
let app = express();
const ObjectID = require('valid-objectid');

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

//Use session
app.use(session({ secret: 'secretomitted', cookie: { maxAge: 0 } }))

//Set cookie session
app.use(cookieParser())
app.use(cookieSession({ name: 'session', secret: 'secretomitted', maxAge: 0 }))

//Set views folder and view engine
app.set('views', './views');
app.set('view engine', 'pug');

passport.use(new LocalStrategy(
  function (email, password, done) {
    User.findOne({ 'email': email }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, console.log('Wrong username'));
      }
      if (!user.validatePassword(password)) {
        return done(null, false, console.log('Wrong Password'));
      }
      return done(null, user);
    });
  }
));

//FE Requests

app.get('/', (req, res) => {
  res.send(pug.renderFile('index.pug'))
  console.log('index rendered')
})

and this is the error i'm getting:

[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server/server.js`
express-session deprecated undefined resave option; provide resave option server/server.js:24:9
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option server/server.js:24:9
Started on port 3000
/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/express-session/index.js:326
        req.session.touch()
                    ^

TypeError: req.session.touch is not a function
    at ServerResponse.end (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/express-session/index.js:326:21)
    at Array.write (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/finalhandler/index.js:297:9)
    at listener (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/on-finished/index.js:169:15)
    at onFinish (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/on-finished/index.js:100:5)
    at callback (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/ee-first/index.js:55:10)
    at IncomingMessage.onevent (/Users/alessandrocamplese/Desktop/Projects/Mongo-tasker/mongo-tasker/node_modules/ee-first/index.js:93:5)
    at IncomingMessage.emit (events.js:197:13)
    at endReadableNT (_stream_readable.js:1129:12)
    at processTicksAndRejections (internal/process/next_tick.js:76:17)
[nodemon] app crashed - waiting for file changes before starting...

Any solution to this? Thanks.

Body:
TL;DR: Only use one session management, for custom session information extend the session object don't overwrite it.

Old question, but I had the same issue, so for anyone else trying to accomplish the same thing :) . I believe that the problem is some sort of conflict from different session objects:

//Use session
app.use(session({ secret: 'secretomitted', cookie: { maxAge: 0 } }))

//Set cookie session
app.use(cookieParser())
app.use(cookieSession({ name: 'session', secret: 'secretomitted', maxAge: 0 }))

This is using express-session AND cookie-session. Here is a quote from expressjs.com:

A user session can be stored in two main ways with cookies: on the server or on the client. [cookie-session] stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.

As explained above, express-session only stores an ID in the cookie, while cookie-session stores all session data in the cookie. This very short blog post explains how messing with the session data will cause your error. The two types of session storage will inevitably cause such a conflict, since they are trying to store the data in different places.


问:
Cannot Access the Qt UI from an external cpp file
Im trying to make a program an in that program I want to press a button that processes some text in another cpp file and appends my QTextEdit. I basically as a test just setup my button to run a function in the other file and also in when the program starts. When it starts it properly prints to the Text Edit as well as my console but when I press my button it only prints to the console and not to my TextEdit. For the function that appends the text in my TextEdit and prints to the console, I made it a public slot so I could access it from my other file.

This is my quiz.cpp

```<code>#include <iostream>
#include "quiz.h"
#include "ui_quiz.h"
#include "test.h"

Quiz::Quiz(QWidget *parent) : QMainWindow(parent), ui(new Ui::Quiz) {
    ui->setupUi(this);
    setText();
}

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

void Quiz::on_actionQuit_triggered() {
    QCoreApplication::quit();
}

void Quiz::on_pushButton_clicked() {
    run();
}

void Quiz::setText() {
    ui->console->append("Hello");
    std::cout << "Hello world!" << std::endl;
}
</code>```

This is its header:

```<code>#ifndef QUIZ_H
#define QUIZ_H

#include <QMainWindow>

namespace Ui {
class Quiz;
}

class Quiz : public QMainWindow
{
    Q_OBJECT

public:
    explicit Quiz(QWidget *parent = 0);
    ~Quiz();
public slots:
    void setText();
private slots:
    void on_actionQuit_triggered();

    void on_pushButton_clicked();
private:
    Ui::Quiz *ui;
};

#endif // QUIZ_H
</code>```

This is my test.cpp:

```<code>#include "quiz.h"
#include "test.h"
#include "ui_quiz.h"

void run() {
    Quiz* quiz = new Quiz();
    quiz->setText();
}
</code>```

and its header:

```<code>#ifndef TEST_H
#define TEST_H

#endif // TEST_H

void run();
</code>```

What am I doing wrong? Why can I not access the ui but the rest of the function runs?

答:
In header file of your cpp where you want to use the UI, add the following lines of ui.

##.h file:

```<code>class A
{
 Public:
    Ui::MainWindow *ui;
}
</code>```

##.cpp file:

```<code>ui->label->setText(ui->button->text());
</code>```

Body:
Im trying to make a program an in that program I want to press a button that processes some text in another cpp file and appends my QTextEdit. I basically as a test just setup my button to run a function in the other file and also in when the program starts. When it starts it properly prints to the Text Edit as well as my console but when I press my button it only prints to the console and not to my TextEdit. For the function that appends the text in my TextEdit and prints to the console, I made it a public slot so I could access it from my other file.

This is my quiz.cpp

#include <iostream>
#include "quiz.h"
#include "ui_quiz.h"
#include "test.h"

Quiz::Quiz(QWidget *parent) : QMainWindow(parent), ui(new Ui::Quiz) {
    ui->setupUi(this);
    setText();
}

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

void Quiz::on_actionQuit_triggered() {
    QCoreApplication::quit();
}

void Quiz::on_pushButton_clicked() {
    run();
}

void Quiz::setText() {
    ui->console->append("Hello");
    std::cout << "Hello world!" << std::endl;
}

This is its header:

#ifndef QUIZ_H
#define QUIZ_H

#include <QMainWindow>

namespace Ui {
class Quiz;
}

class Quiz : public QMainWindow
{
    Q_OBJECT

public:
    explicit Quiz(QWidget *parent = 0);
    ~Quiz();
public slots:
    void setText();
private slots:
    void on_actionQuit_triggered();

    void on_pushButton_clicked();
private:
    Ui::Quiz *ui;
};

#endif // QUIZ_H

This is my test.cpp:

#include "quiz.h"
#include "test.h"
#include "ui_quiz.h"

void run() {
    Quiz* quiz = new Quiz();
    quiz->setText();
}

and its header:

#ifndef TEST_H
#define TEST_H

#endif // TEST_H

void run();

What am I doing wrong? Why can I not access the ui but the rest of the function runs?

Body:
In header file of your cpp where you want to use the UI, add the following lines of ui.

##.h file:

class A
{
 Public:
    Ui::MainWindow *ui;
}

##.cpp file:

ui->label->setText(ui->button->text());


答:
I would do the following:</p>
```<code>while True:
    name = input('Enter employee name: ')
    info = employees.get(name, -1)
    if info == -1:
        print('Employee does not exist')
    else:
        print(f'Employee details are: \n Employee Id: {info[0]} \n Salary: {info[1]} \n Address: {info[2]}')
    #And then the exit thing
</code>```

Title: Print details of an employee by entering the name of employee in Python

Body:
I am getting input of details of the employee from the user and then asking the user to enter the name of the employee, he wants to retrieve information of. I am saving all the entered data in a dictionary with employee name as its key and [employee_id, salary, address] as the values. Now whatever name I enter to retrieve the details, the output is always the details of the last entered employee.

    n = int(input('Enter the number of employee: '))
    employees = {}

    for i in range(n):
        name = input('Enter the name of the employee: ')
        emp_id = input("Enter employee Id: ")
        sal = int(input("Enter the employee salary: "))
        address = input('Enter the employee address: ')
        employees[name] = [emp_id, sal, address]

    while True:
        name = input('Enter employee name: ')
        info = employees.get(name, -1)
        if info == -1:
            print('Employee does not exist')
        else:
            print('Employee details are: \n Employee Id: ', emp_id, '\n Salary: ', sal, '\n Address: ', address)

        exit_choice = input('Do you want to exit [Yes|No]: ')
        if exit_choice == 'No' or exit_choice == 'no':
            break

I want to get the output as the details of the employee whose name is entered. Please can you help me get out of this situation?

Body:
I would do the following:

while True:
    name = input('Enter employee name: ')
    info = employees.get(name, -1)
    if info == -1:
        print('Employee does not exist')
    else:
        print(f'Employee details are: \n Employee Id: {info[0]} \n Salary: {info[1]} \n Address: {info[2]}')
    #And then the exit thing


问:
How to compare a picture in Appium, using Python code?
I need to compare template picture in iOS app. What syntax I need to use for it? I found so many information about it, but only with Java syntax.

I use Appium + Python on Mac.

答:
I couldn't use openCV library.
Because I cannot install opencv4nodejs

You can try to install it like this way, with npm module: npm i -g opencv4nodejs
So, I found solution to compare images. You can use this code:

```<code>/**
 * Finds the a region in one image that best matches another, smaller, image.
 */
public static int[] findSubImage(BufferedImage im1, BufferedImage im2){
    int w1 = im1.getWidth(); int h1 = im1.getHeight();
    int w2 = im2.getWidth(); int h2 = im2.getHeight();
    assert(w2 <= w1 && h2 <= h1);
    // will keep track of best position found
    int bestX = 0; int bestY = 0; double lowestDiff = Double.POSITIVE_INFINITY;
    // brute-force search through whole image (slow...)
    for(int x = 0;x < w1-w2;x++){
        for(int y = 0;y < h1-h2;y++){
            double comp = compareImages(im1.getSubimage(x,y,w2,h2),im2);
            if(comp < lowestDiff){
                bestX = x; bestY = y; lowestDiff = comp;
            }
        }
    }
    // output similarity measure from 0 to 1, with 0 being identical
    System.out.println(lowestDiff + "output similarity measure from 0 to 1, with 0 being identical");
    Assertions.assertTrue(lowestDiff<0.5);
    // return best location
    return new int[]{bestX,bestY};
}

/**
 * Determines how different two identically sized regions are.
 */
public static double compareImages(BufferedImage im1, BufferedImage im2){
    assert(im1.getHeight() == im2.getHeight() && im1.getWidth() == im2.getWidth());
    double variation = 0.0;
    for(int x = 0;x < im1.getWidth();x++){
        for(int y = 0;y < im1.getHeight();y++){
            variation += compareARGB(im1.getRGB(x,y),im2.getRGB(x,y))/Math.sqrt(3);
        }
    }
    return variation/(im1.getWidth()*im1.getHeight());
}

/**
 * Calculates the difference between two ARGB colours (BufferedImage.TYPE_INT_ARGB).
 */
public static double compareARGB(int rgb1, int rgb2){
    double r1 = ((rgb1 >> 16) & 0xFF)/255.0; double r2 = ((rgb2 >> 16) & 0xFF)/255.0;
    double g1 = ((rgb1 >> 8) & 0xFF)/255.0;  double g2 = ((rgb2 >> 8) & 0xFF)/255.0;
    double b1 = (rgb1 & 0xFF)/255.0;         double b2 = (rgb2 & 0xFF)/255.0;
    double a1 = ((rgb1 >> 24) & 0xFF)/255.0; double a2 = ((rgb2 >> 24) & 0xFF)/255.0;
    // if there is transparency, the alpha values will make difference smaller
    return a1*a2*Math.sqrt((r1-r2)*(r1-r2) + (g1-g2)*(g1-g2) + (b1-b2)*(b1-b2));
}
</code>```

I found it here.
It works good, but too slow.
If you also cannot use openCV, you can use this way.
Good luck.

Body:
I couldn't use openCV library.
Because I cannot install opencv4nodejs

You can try to install it like this way, with npm module: npm i -g opencv4nodejs
So, I found solution to compare images. You can use this code:

/**
 * Finds the a region in one image that best matches another, smaller, image.
 */
public static int[] findSubImage(BufferedImage im1, BufferedImage im2){
    int w1 = im1.getWidth(); int h1 = im1.getHeight();
    int w2 = im2.getWidth(); int h2 = im2.getHeight();
    assert(w2 <= w1 && h2 <= h1);
    // will keep track of best position found
    int bestX = 0; int bestY = 0; double lowestDiff = Double.POSITIVE_INFINITY;
    // brute-force search through whole image (slow...)
    for(int x = 0;x < w1-w2;x++){
        for(int y = 0;y < h1-h2;y++){
            double comp = compareImages(im1.getSubimage(x,y,w2,h2),im2);
            if(comp < lowestDiff){
                bestX = x; bestY = y; lowestDiff = comp;
            }
        }
    }
    // output similarity measure from 0 to 1, with 0 being identical
    System.out.println(lowestDiff + "output similarity measure from 0 to 1, with 0 being identical");
    Assertions.assertTrue(lowestDiff<0.5);
    // return best location
    return new int[]{bestX,bestY};
}

/**
 * Determines how different two identically sized regions are.
 */
public static double compareImages(BufferedImage im1, BufferedImage im2){
    assert(im1.getHeight() == im2.getHeight() && im1.getWidth() == im2.getWidth());
    double variation = 0.0;
    for(int x = 0;x < im1.getWidth();x++){
        for(int y = 0;y < im1.getHeight();y++){
            variation += compareARGB(im1.getRGB(x,y),im2.getRGB(x,y))/Math.sqrt(3);
        }
    }
    return variation/(im1.getWidth()*im1.getHeight());
}

/**
 * Calculates the difference between two ARGB colours (BufferedImage.TYPE_INT_ARGB).
 */
public static double compareARGB(int rgb1, int rgb2){
    double r1 = ((rgb1 >> 16) & 0xFF)/255.0; double r2 = ((rgb2 >> 16) & 0xFF)/255.0;
    double g1 = ((rgb1 >> 8) & 0xFF)/255.0;  double g2 = ((rgb2 >> 8) & 0xFF)/255.0;
    double b1 = (rgb1 & 0xFF)/255.0;         double b2 = (rgb2 & 0xFF)/255.0;
    double a1 = ((rgb1 >> 24) & 0xFF)/255.0; double a2 = ((rgb2 >> 24) & 0xFF)/255.0;
    // if there is transparency, the alpha values will make difference smaller
    return a1*a2*Math.sqrt((r1-r2)*(r1-r2) + (g1-g2)*(g1-g2) + (b1-b2)*(b1-b2));
}

I found it here.
It works good, but too slow.
If you also cannot use openCV, you can use this way.
Good luck.


答:
this hard to implement since if a prime number comes in between you can never break it to be square root of 1; for example,

take 11,

3^2--- now 2 remains and it does't have square root and the number less than this is "1", and 1^(n) is always 1.. so always there remains a reminder..

so may be you need to follow some kind of algorithms as other answers suggest...

Title: Is there any way to represent any number as sum of 4 squares?


问:
regex to replace regular quotes with curly quotes
I have a block of text where the opening and closing quotes are same

"Hey", How are you? "Hey there"... “Some more text” and some more "here".

Please note that the quote character is " and not “ ” these characters

```<code>(["'])(?:(?=(\\?))\2.)*?\1
</code>```

I want to replace the opening " character as “

it will now look as
“Hey", How are you? “Hey there"... “Some more text” and some more “here".

and then again running I can simply find and replace the left over " occurance as ”

and that would give the expected output which should look as

“Hey”, How are you? “Hey there”... “Some more text” and some more “here”.

答:
My preference would be for the solution given by @WiktorStribiżew in a comment on the question, but I wish to give an alternative solution that may be of interest to some readers.

The second replacement of the remaining (trailing) double-quotes (i.e., ASCII 32) is straightforward, so I will not discuss that.

You could match leading double-quotes with the following regular expression, and then replace each match with “:

```<code>"(?=(?:(?:[^"]*"){2})*[^"]*"[^"]*$)
</code>```

Demo

This regex is based on the observation that we want to identify all double-quotes that are followed later in the string by an odd number of double-quotes (assuming the string contains an even number of double-quotes.

The regular expression can be broken down as follows.

```<code>"              # match a double-quote (dq)
(?=            # begin a positive lookahead
  (?:          # begin a non-capture group
    (?:        # begin a non-capture group
      [^"]*"   # match 0+ chars other than dq then match dq
    ){2}       # end non-capture group and execute it twice
  )*           # end non-capture group and execute it 0+ times
  [^"]*"[^"]*  # match dq preceded and followed by 0+ non-dq chars
  $            # match end of string
)              # end positive lookahead
</code>```

If the data set is large it may be advisable to perform some benchmarking to see if execution speed is satisfactory.

Body:
I have a block of text where the opening and closing quotes are same

"Hey", How are you? "Hey there"... “Some more text” and some more "here".

Please note that the quote character is " and not “ ” these characters

(["'])(?:(?=(\\?))\2.)*?\1

I want to replace the opening " character as “

it will now look as
“Hey", How are you? “Hey there"... “Some more text” and some more “here".

and then again running I can simply find and replace the left over " occurance as ”

and that would give the expected output which should look as

“Hey”, How are you? “Hey there”... “Some more text” and some more “here”.

Body:
My preference would be for the solution given by @WiktorStribiżew in a comment on the question, but I wish to give an alternative solution that may be of interest to some readers.

The second replacement of the remaining (trailing) double-quotes (i.e., ASCII 32) is straightforward, so I will not discuss that.

You could match leading double-quotes with the following regular expression, and then replace each match with “:

"(?=(?:(?:[^"]*"){2})*[^"]*"[^"]*$)

Demo

This regex is based on the observation that we want to identify all double-quotes that are followed later in the string by an odd number of double-quotes (assuming the string contains an even number of double-quotes.

The regular expression can be broken down as follows.

"              # match a double-quote (dq)
(?=            # begin a positive lookahead
  (?:          # begin a non-capture group
    (?:        # begin a non-capture group
      [^"]*"   # match 0+ chars other than dq then match dq
    ){2}       # end non-capture group and execute it twice
  )*           # end non-capture group and execute it 0+ times
  [^"]*"[^"]*  # match dq preceded and followed by 0+ non-dq chars
  $            # match end of string
)              # end positive lookahead

If the data set is large it may be advisable to perform some benchmarking to see if execution speed is satisfactory.