问:
Parse data from XML
I am struggling to read out the "ProtectedElements" node of the xml file below.
I can read out the information above that node without an issue, but I cant seem to find a way to read out the checksum from that particular node.
When i try to read it, the code returns "null".

I have tried to look up the documentation from Microsoft but the examples dont seem to help. I guess it is something to do with the nesting but I cant figure out a solution.
I only want to read out the value of the attribute.

Any help appreciated.

```<code>        var doc = XDocument.Load(TempFile);

        // get LockInfo element
        var lockInfoElement = doc.Root.Element(ns + "LockInfo");

        // get lockDate
        var lockDateAttr = lockInfoElement.Attribute("lockDate");
        var lockDateText = lockDateAttr.Value;
        var lockDate = DateTime.Parse(lockDateText);

        // get locked by
        var lockedByAttr = lockInfoElement.Attribute("lockedBy");
        var lockedByText = lockedByAttr.Value;
        var lockedBy = lockedByText.ToString();

        // get ValidationInfo element
        var validationInfoElement = doc.Root.Element(ns + "ValidationInfo");

        var validationDateAttr = validationInfoElement.Attribute("validationDate");
        var validationDateText = validationDateAttr.Value;
        var validationDate = DateTime.Parse(validationDateText);

        // get ValidationInfo element
        var validationByAttr = validationInfoElement.Attribute("validatedBy");
        var validationByText = validationByAttr.Value;
        var validationBy = validationByText.ToString();

        // get ConfigSeal checksum element
        var configInfoElement = doc.Root.Element(ns + "ConfigurationSeal");
        var configurationSealAttr = configInfoElement.Attribute("checksum");
        var configurationSealChkSum = configurationSealAttr.Value;
        var configurationSealText = configurationSealChkSum.ToString();

        //--------------------------------------------------------------------

        // get Protected elements checksum
        var protectedElements = doc.Root.Element(ns + "ProtectedElements");
        var protectedElementsAttr = protectedElements.Attribute("checksum");
        var protectedElementsChkSum = protectedElementsAttr.Value;
        var protectedElementsText = protectedElementsChkSum.ToString();
</code>```

XML DATA:

```<code><SafetyConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:abb-robotics-safety-controller-configuration sc_cfg.1.00.01.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" version="1.00.01" xmlns="urn:abb-robotics-safety-controller-configuration">
  <ValidationInfo validationDate="2019-08-29T13:45:16" validatedBy="W01 Admin"/>
  <LockInfo lockDate="2020-02-11T13:54:07" lockedBy="W01 Admin" controllerId="6700-110323"/>
  <ConfigurationSeal checksum="776890E3E367E5171CC3FD52700BE8FA5373422BCC6C4214C0321E6BEC02EA52" creationDate="2019-08-29T13:39:23.2736126+02:00" createdBy="W01 Admin" systemName="00RZ21_ST010_IR001" swVersion="1.02.04">
    <ProtectedElements checksum="20E318119904F2A8506AD3A00035BE2FE562FA772D371DCC43B04A2E4622550F" />
    <SiosCfg version="1.0">
      <Net name="PNFDevice">
        <Device name="PNFDeviceDev" inSizeBits="64" outSizeBits="64" address="">
          <Module name="InputOutputModule" inputSize="8" outputSize="8" sourceAddress="100" destAddress="144" wdTimeout="500" crcLength="3" fParVersion="2" slot="3" silLevel="2" visible="true" readonly="false" />
</code>```

答:
var protectedElements = configInfoElement.Element(ns + "ProtectedElements");
var protectedElementsAttr = protectedElements.Attribute("checksum");
```

On the first line we're looking under configInfoElement rather than doc.Root, and in the second line we're looking under protectedElements rather than configInfoElement

Title: Parse data from XML

Body:
I am struggling to read out the "ProtectedElements" node of the xml file below.
I can read out the information above that node without an issue, but I cant seem to find a way to read out the checksum from that particular node.
When i try to read it, the code returns "null".

I have tried to look up the documentation from Microsoft but the examples dont seem to help. I guess it is something to do with the nesting but I cant figure out a solution.
I only want to read out the value of the attribute.

Any help appreciated.

        var doc = XDocument.Load(TempFile);

        // get LockInfo element
        var lockInfoElement = doc.Root.Element(ns + "LockInfo");

        // get lockDate
        var lockDateAttr = lockInfoElement.Attribute("lockDate");
        var lockDateText = lockDateAttr.Value;
        var lockDate = DateTime.Parse(lockDateText);

        // get locked by
        var lockedByAttr = lockInfoElement.Attribute("lockedBy");
        var lockedByText = lockedByAttr.Value;
        var lockedBy = lockedByText.ToString();

        // get ValidationInfo element
        var validationInfoElement = doc.Root.Element(ns + "ValidationInfo");

        var validationDateAttr = validationInfoElement.Attribute("validationDate");
        var validationDateText = validationDateAttr.Value;
        var validationDate = DateTime.Parse(validationDateText);

        // get ValidationInfo element
        var validationByAttr = validationInfoElement.Attribute("validatedBy");
        var validationByText = validationByAttr.Value;
        var validationBy = validationByText.ToString();

        // get ConfigSeal checksum element
        var configInfoElement = doc.Root.Element(ns + "ConfigurationSeal");
        var configurationSealAttr = configInfoElement.Attribute("checksum");
        var configurationSealChkSum = configurationSealAttr.Value;
        var configurationSealText = configurationSealChkSum.ToString();

        //--------------------------------------------------------------------

        // get Protected elements checksum
        var protectedElements = doc.Root.Element(ns + "ProtectedElements");
        var protectedElementsAttr = protectedElements.Attribute("checksum");
        var protectedElementsChkSum = protectedElementsAttr.Value;
        var protectedElementsText = protectedElementsChkSum.ToString();

XML DATA:

<SafetyConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:abb-robotics-safety-controller-configuration sc_cfg.1.00.01.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" version="1.00.01" xmlns="urn:abb-robotics-safety-controller-configuration">
  <ValidationInfo validationDate="2019-08-29T13:45:16" validatedBy="W01 Admin"/>
  <LockInfo lockDate="2020-02-11T13:54:07" lockedBy="W01 Admin" controllerId="6700-110323"/>
  <ConfigurationSeal checksum="776890E3E367E5171CC3FD52700BE8FA5373422BCC6C4214C0321E6BEC02EA52" creationDate="2019-08-29T13:39:23.2736126+02:00" createdBy="W01 Admin" systemName="00RZ21_ST010_IR001" swVersion="1.02.04">
    <ProtectedElements checksum="20E318119904F2A8506AD3A00035BE2FE562FA772D371DCC43B04A2E4622550F" />
    <SiosCfg version="1.0">
      <Net name="PNFDevice">
        <Device name="PNFDeviceDev" inSizeBits="64" outSizeBits="64" address="">
          <Module name="InputOutputModule" inputSize="8" outputSize="8" sourceAddress="100" destAddress="144" wdTimeout="500" crcLength="3" fParVersion="2" slot="3" silLevel="2" visible="true" readonly="false" />

Body:
var protectedElements = configInfoElement.Element(ns + "ProtectedElements");
var protectedElementsAttr = protectedElements.Attribute("checksum");

On the first line we're looking under configInfoElement rather than doc.Root, and in the second line we're looking under protectedElements rather than configInfoElement


来源: stackexchange

问:
How to use WinForms progress bar?
I want to show progress of calculations, which are performing in external library.

For example if I have some calculate method, and I want to use it for 100000 values in my Form class I can write:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Caluculate(int i)
    {
        double pow = Math.Pow(i, i);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        progressBar1.Maximum = 100000;
        progressBar1.Step = 1;

        for(int j = 0; j < 100000; j++)
        {
            Caluculate(j);
            progressBar1.PerformStep();
        }
    }
}
</code>```

I should perform step after each calculation. But what if I perform all 100000 calculations in external method. When should I "perform step" if I don't want to make this method dependant on progress bar? I can, for example, write

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void CaluculateAll(System.Windows.Forms.ProgressBar progressBar)
    {
        progressBar.Maximum = 100000;
        progressBar.Step = 1;

        for(int j = 0; j < 100000; j++)
        {
            double pow = Math.Pow(j, j); //Calculation
            progressBar.PerformStep();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        CaluculateAll(progressBar1);
    }
}
</code>```

but I don't want to do like that.

答:
There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

```<code>   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }
</code>```

Done! Then you can reuse ProgressDialog anywhere:

```<code>var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use WinForms progress bar?

Body:
I want to show progress of calculations, which are performing in external library.

For example if I have some calculate method, and I want to use it for 100000 values in my Form class I can write:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Caluculate(int i)
    {
        double pow = Math.Pow(i, i);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        progressBar1.Maximum = 100000;
        progressBar1.Step = 1;

        for(int j = 0; j < 100000; j++)
        {
            Caluculate(j);
            progressBar1.PerformStep();
        }
    }
}

I should perform step after each calculation. But what if I perform all 100000 calculations in external method. When should I "perform step" if I don't want to make this method dependant on progress bar? I can, for example, write

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void CaluculateAll(System.Windows.Forms.ProgressBar progressBar)
    {
        progressBar.Maximum = 100000;
        progressBar.Step = 1;

        for(int j = 0; j < 100000; j++)
        {
            double pow = Math.Pow(j, j); //Calculation
            progressBar.PerformStep();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        CaluculateAll(progressBar1);
    }
}

but I don't want to do like that.

Body:
There is Task exists, It is unnesscery using BackgroundWorker, Task is more simple. for example:

ProgressDialog.cs:

   public partial class ProgressDialog : Form
    {
        public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }

        public ProgressDialog()
        {
            InitializeComponent();
        }

        public void RunAsync(Action action)
        {
            Task.Run(action);
        }
    }

Done! Then you can reuse ProgressDialog anywhere:

var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;

progressDialog.RunAsync(() =>
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000)
        this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
            this.progressDialog.Progressbar.Value += 1;
        }));
    }
});

progressDialog.ShowDialog();

ContentLicense: CC BY-SA 4.0


问:
I have a method withdraw(); that doesnt work, any idea why?
My withdraw method doesnt work, maybe someone see things I dont see?

This is part of my abstract class Account and abstract method withdraw

```<code>import java.util.ArrayList;

public abstract class Account {
private String accountType;
private static double balance = 0;
protected int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;

public Account(String acType, int acNumber){
    accountType = acType;
    accountNumberCounter ++;
    accountId = accountNumberCounter;
}

public Account() {
    accountNumberCounter++;
    accountId = accountNumberCounter;
}

public abstract boolean withdraw(double value);
</code>```

This is SavingsAccount class and its method withdraw()

```<code>public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static  String accountType = "Savings Account";
private int accountId;

public SavingsAccount(){
    super();
}

public double getBalance(){
    return balance;
}

public void deposit(double amount){
    balance = balance + amount;
}

public boolean withdraw(double amount){
    if (balance<= amount){
        System.out.println("You have only" + amount + "left on your account.");
    return false;
    }
    else{
        balance -= amount;
        System.out.println("You took:" + amount);
        return true;
    }
}
</code>```

Method from BankLogic as well, I think this part should be correct:

```<code>  public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false;
}
</code>```

答:
The problem is:

```<code>private boolean testingWithdraw(String pNr, int accountId, double amount) {
    System.out.println("withdraw(" + pNr + "," + accountId + "," + amount + ")");
    return bank.withdraw(pNr, accountId, amount);
}
</code>```

That's because inside bank withdraw method, you return false, even if it is success.

```<code> public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false; //this should be true. this denotes  the whole process
}
</code>```

If you want to maintain the status of updation of each accouunt, then you may use a map of (String,boolean) to maintaion id->updation status

Body:
My withdraw method doesnt work, maybe someone see things I dont see?

This is part of my abstract class Account and abstract method withdraw

import java.util.ArrayList;

public abstract class Account {
private String accountType;
private static double balance = 0;
protected int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;

public Account(String acType, int acNumber){
    accountType = acType;
    accountNumberCounter ++;
    accountId = accountNumberCounter;
}

public Account() {
    accountNumberCounter++;
    accountId = accountNumberCounter;
}

public abstract boolean withdraw(double value);

This is SavingsAccount class and its method withdraw()

public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static  String accountType = "Savings Account";
private int accountId;

public SavingsAccount(){
    super();
}

public double getBalance(){
    return balance;
}

public void deposit(double amount){
    balance = balance + amount;
}

public boolean withdraw(double amount){
    if (balance<= amount){
        System.out.println("You have only" + amount + "left on your account.");
    return false;
    }
    else{
        balance -= amount;
        System.out.println("You took:" + amount);
        return true;
    }
}

Method from BankLogic as well, I think this part should be correct:

  public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false;
}

Body:
The problem is:

private boolean testingWithdraw(String pNr, int accountId, double amount) {
    System.out.println("withdraw(" + pNr + "," + accountId + "," + amount + ")");
    return bank.withdraw(pNr, accountId, amount);
}

That's because inside bank withdraw method, you return false, even if it is success.

 public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false; //this should be true. this denotes  the whole process
}

If you want to maintain the status of updation of each accouunt, then you may use a map of (String,boolean) to maintaion id->updation status


问:
Selective Automatic Schema Generation settings per entity in Hibernate
Is it possible to selectively choose to which entities or datasources the schema generation settings of Hibernate apply?

hibernate.hbm2ddl.auto=none

I´d like to use existing tables of a database that I don´t want to modify, but also create some new ones automatically.

答: You will have to use ->hibernate.hbm2ddl.auto=update instead of none.</p>


问:
Trying To Get a Custom Array With Looping PHP
Good day, i am trying to generate a csv with array below

```<code>array[0] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 1, --> the value is only 1 and 2
  ["d"] => user2,
),
array[1] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 2,
  ["d"] => user3,
),
array[2] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 1,
  ["d"] => user4,
),
array[3] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 2,
  ["d"] => user5,
)
</code>```

edit: i want to get the 2 array with same number on "a" and "b" value, but different in "c" value
i tried my code below

```<code>$results = array();

for($i = 1 ; $i <= 10 ; $i++){
    $j = $i+1;

    $response = array(
        array(
            $i, $i, 1, "user".$i
        ),
        array(
            $i, $i, 2, "user".$j
        )
    );
    array_push($results, $response);
}
</code>```

but the array result is not as i wanted like above result. is there any solutions?, sorry for the confusion of this question, i am trying my best to ask. thank you for the help!.

Body:
Good day, i am trying to generate a csv with array below

array[0] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 1, --> the value is only 1 and 2
  ["d"] => user2,
),
array[1] => array(
  ["a"] => 1,
  ["b"] => 1,
  ["c"] => 2,
  ["d"] => user3,
),
array[2] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 1,
  ["d"] => user4,
),
array[3] => array(
  ["a"] => 2,
  ["b"] => 2,
  ["c"] => 2,
  ["d"] => user5,
)

edit: i want to get the 2 array with same number on "a" and "b" value, but different in "c" value
i tried my code below

$results = array();

for($i = 1 ; $i <= 10 ; $i++){
    $j = $i+1;

    $response = array(
        array(
            $i, $i, 1, "user".$i
        ),
        array(
            $i, $i, 2, "user".$j
        )
    );
    array_push($results, $response);
}

but the array result is not as i wanted like above result. is there any solutions?, sorry for the confusion of this question, i am trying my best to ask. thank you for the help!.

Body:
I think you will have to work with a for loop and a manually increments value for your userx value like this.

$results = [];
$user = 1;

for($i = 1 ; $i <= 10 ; $i++){
    $x = 1;
    $user++;
    $results[] = [$i, $i, $x, "user$user"];
    $x = 2;
    $user++;
    $results[] = [$i, $i, $x, "user$user"];
}
print_r($results);

RESULT:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1
            [3] => user2
        )

    [1] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 2
            [3] => user3
        )

    [2] => Array
        (
            [0] => 2
            [1] => 2
            [2] => 1
            [3] => user4
        )

    [3] => Array
        (
            [0] => 2
            [1] => 2
            [2] => 2
            [3] => user5
        )

    [4] => Array
        (
            [0] => 3
            [1] => 3
            [2] => 1
            [3] => user6
        )

    [5] => Array
        (
            [0] => 3
            [1] => 3
            [2] => 2
            [3] => user7
        )

    [6] => Array
        (
            [0] => 4
            [1] => 4
            [2] => 1
            [3] => user8
        )

    [7] => Array
        (
            [0] => 4
            [1] => 4
            [2] => 2
            [3] => user9
        )

    [8] => Array
        (
            [0] => 5
            [1] => 5
            [2] => 1
            [3] => user10
        )

    [9] => Array
        (
            [0] => 5
            [1] => 5
            [2] => 2
            [3] => user11
        )

    [10] => Array
        (
            [0] => 6
            [1] => 6
            [2] => 1
            [3] => user12
        )

    [11] => Array
        (
            [0] => 6
            [1] => 6
            [2] => 2
            [3] => user13
        )

    [12] => Array
        (
            [0] => 7
            [1] => 7
            [2] => 1
            [3] => user14
        )

    [13] => Array
        (
            [0] => 7
            [1] => 7
            [2] => 2
            [3] => user15
        )

    [14] => Array
        (
            [0] => 8
            [1] => 8
            [2] => 1
            [3] => user16
        )

    [15] => Array
        (
            [0] => 8
            [1] => 8
            [2] => 2
            [3] => user17
        )

    [16] => Array
        (
            [0] => 9
            [1] => 9
            [2] => 1
            [3] => user18
        )

    [17] => Array
        (
            [0] => 9
            [1] => 9
            [2] => 2
            [3] => user19
        )

    [18] => Array
        (
            [0] => 10
            [1] => 10
            [2] => 1
            [3] => user20
        )

    [19] => Array
        (
            [0] => 10
            [1] => 10
            [2] => 2
            [3] => user21
        )

)

I removed the array_push() as it is quicker (no function call) to do a simple $arr[] = $something;


问:
Is this possible to setInterval with custom ID so I can clear it later on from another services?
I want to register a new interval using setInterval method that will be running until I stop it. I want to stop it from another service (api route).
But the problem is that I don't have the ID of the interval. All I have is this when log the interval object:

```<code>let interval = setInterval(() => console.log(`Hello World`), 3000);
console.log(`interval:`, interval);

// we got this in the log:

interval: Timeout {
  _called: false,
  _idleTimeout: 3000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 2765,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: 3000,
  _destroyed: false,
  [Symbol(unrefed)]: false,
  [Symbol(asyncId)]: 29,
  [Symbol(triggerId)]: 1 }
</code>```

答:
That is the "id" of the interval, in Node.js. (It would be a number on browsers, but on Node.js it's a Timeout object.) It's what you pass to clearInterval. So pass that object to the other service that you want to stop the interval from.

In a comment you've said:

But I cannot send it to another service directly, the service should pull it from DB or something. And I tried to store it in MongoDB and got an error because mongo wont store such an object.

Assuming the other service is in the same process (otherwise, it can't cancel the timer), you could write a module to assign timers numeric IDs:

```<code>let lastId = 0;
const timers = new Map();

export function mySetInterval(callback, ms) {
    const id = ++lastId;
    timers.set(id, setInterval(callback, ms));
    return id;
}

export function myClearInterval(id) {
    const timer = timers.get(id);
    if (timer) {
        timers.delete(id);
        clearInterval(timer);
    }
}
</code>```

Setting an interval timer:

```<code>import { mySetInterval } from "./my-module";

saveTimerIdInDB(mySetInterval(() => console.log(`Hello World`), 3000));
</code>```

Clearing it:

```<code>import { myClearInterval } from "./my-module";

myClearInterval(getTimerIdFromDB());
</code>```

Note: I'm using JavaScript standard module syntax there ("ESM"). But you can do the same thing with Node.js's older module syntax ("CJS"), switch to exports.mySetInterval = ... and const mySetInterval = require(...) accordingly.

Body:
I want to register a new interval using setInterval method that will be running until I stop it. I want to stop it from another service (api route).
But the problem is that I don't have the ID of the interval. All I have is this when log the interval object:

let interval = setInterval(() => console.log(`Hello World`), 3000);
console.log(`interval:`, interval);

// we got this in the log:

interval: Timeout {
  _called: false,
  _idleTimeout: 3000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 2765,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: 3000,
  _destroyed: false,
  [Symbol(unrefed)]: false,
  [Symbol(asyncId)]: 29,
  [Symbol(triggerId)]: 1 }

Body:
That is the "id" of the interval, in Node.js. (It would be a number on browsers, but on Node.js it's a Timeout object.) It's what you pass to clearInterval. So pass that object to the other service that you want to stop the interval from.

In a comment you've said:

But I cannot send it to another service directly, the service should pull it from DB or something. And I tried to store it in MongoDB and got an error because mongo wont store such an object.

Assuming the other service is in the same process (otherwise, it can't cancel the timer), you could write a module to assign timers numeric IDs:

let lastId = 0;
const timers = new Map();

export function mySetInterval(callback, ms) {
    const id = ++lastId;
    timers.set(id, setInterval(callback, ms));
    return id;
}

export function myClearInterval(id) {
    const timer = timers.get(id);
    if (timer) {
        timers.delete(id);
        clearInterval(timer);
    }
}

Setting an interval timer:

import { mySetInterval } from "./my-module";

saveTimerIdInDB(mySetInterval(() => console.log(`Hello World`), 3000));

Clearing it:

import { myClearInterval } from "./my-module";

myClearInterval(getTimerIdFromDB());

Note: I'm using JavaScript standard module syntax there ("ESM"). But you can do the same thing with Node.js's older module syntax ("CJS"), switch to exports.mySetInterval = ... and const mySetInterval = require(...) accordingly.


问:
Where can I get a PEM (private) key?
I am working on IdP-initiated SAML response for Salesforce and need your help.

I was working with the code and found that I need a .pem (private) key.

```<code>KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)   ks.getEntry("alias", new KeyStore.PasswordProtection(password));
PrivateKey pk = pkEntry.getPrivateKey();
</code>```

The PEM key will be used to sign my response signature. Where can I get a .pem key?

答:
```<code>openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj ‘/C=US/ST=CA/L=San Mateo/CN=www.appirio.com’ -keyout key-mycompanyrsa.pem -out cert-mycompanyrsa.pem
</code>```

More info:
http://blog.jeffdouglas.com/2010/07/06/using-rsa-sha1-with-salesforce-crypto-class/

Title: Where can I get a PEM (private) key?

Body:
I am working on IdP-initiated SAML response for Salesforce and need your help.

I was working with the code and found that I need a .pem (private) key.

KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)   ks.getEntry("alias", new KeyStore.PasswordProtection(password));
PrivateKey pk = pkEntry.getPrivateKey();

The PEM key will be used to sign my response signature. Where can I get a .pem key?

Body:
openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj ‘/C=US/ST=CA/L=San Mateo/CN=www.appirio.com’ -keyout key-mycompanyrsa.pem -out cert-mycompanyrsa.pem

More info:
http://blog.jeffdouglas.com/2010/07/06/using-rsa-sha1-with-salesforce-crypto-class/


问:
Host name does not match the certificate subject provided by the peer after library change
After updating our project dependencies from apache HttpClient 4.5.10 to 4.5.11 we keep getting this error in our local environment.

We use hystrix, so the connection itself uses HttpAsyncClient (4.1.2).

Production environments work fine after the update, so I guess there is a problem with our certificate that somehow does not pop up when using 4.5.10 for the ssl context configuration.

Does anyone have any idea what might be missing in the cert?

```<code>
   Caused by: javax.net.ssl.SSLPeerUnverifiedException: Host name 'domain' does not match the certificate subject provided by the peer (CN=domain, O=Something, ST=Some-State, C=NL)
        at org.apache.http.nio.conn.ssl.SSLIOSessionStrategy.verifySession(SSLIOSessionStrategy.java:209)
        at org.apache.http.nio.conn.ssl.SSLIOSessionStrategy$1.verify(SSLIOSessionStrategy.java:188)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:354)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:503)
        at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:120)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:588)
</code>```

(I already checked this, and does not seem to match the problem)

Host name does not match the certificate subject provided by the peer, but it's a perfect match

答:
The actual problem was not the domain itself, but that it was a private domain and DefaultHostnameVerifier assumes it is an ICANN domain. Modifying the hostname verifier fixes it.

It was triggered by the change from 4.5.10 to 4.5.11 because of this commit: https://github.com/apache/httpcomponents-client/commit/858946348f5d34f9a8b4caf3c5f054721e647983#diff-842a4260950ada415839175b42257751

It actually corrects a verification problem, but the error is not exactly clear, so I hope this helps someone down the road.

Body:
After updating our project dependencies from apache HttpClient 4.5.10 to 4.5.11 we keep getting this error in our local environment.

We use hystrix, so the connection itself uses HttpAsyncClient (4.1.2).

Production environments work fine after the update, so I guess there is a problem with our certificate that somehow does not pop up when using 4.5.10 for the ssl context configuration.

Does anyone have any idea what might be missing in the cert?

   Caused by: javax.net.ssl.SSLPeerUnverifiedException: Host name 'domain' does not match the certificate subject provided by the peer (CN=domain, O=Something, ST=Some-State, C=NL)
        at org.apache.http.nio.conn.ssl.SSLIOSessionStrategy.verifySession(SSLIOSessionStrategy.java:209)
        at org.apache.http.nio.conn.ssl.SSLIOSessionStrategy$1.verify(SSLIOSessionStrategy.java:188)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:354)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:503)
        at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:120)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:588)

(I already checked this, and does not seem to match the problem)

Host name does not match the certificate subject provided by the peer, but it's a perfect match


问:
Prevent View Controller from extending under status bar
I have a view controller which is the rootVc for Navigation Controller.

I needed the navigation bar to be hiddden for the rootview controller hence I used the following method to hide it and make it reappear.

```<code>override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: false)
}

 override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated: false)
}
</code>```

I'm basically hiding the navigation bar in the rootVc and showing it for all other view controllers.

But when I remove the NavBar I see that my content is extending under the status bar

Is there a way to fix this?

答:
Instead of setting the top constraint to superView use safe area.
Something like this

Body:
I have a view controller which is the rootVc for Navigation Controller.

I needed the navigation bar to be hiddden for the rootview controller hence I used the following method to hide it and make it reappear.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(true, animated: false)
}

 override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.setNavigationBarHidden(false, animated: false)
}

I'm basically hiding the navigation bar in the rootVc and showing it for all other view controllers.

But when I remove the NavBar I see that my content is extending under the status bar

Is there a way to fix this?


问:
Opening Tag URI with Chrome Custom Tabs "ActivityNotFoundException: No Activity found to handle Intent"
I am currently developing a simple RSS app for Android and one of the app's features is opening url with chrome custom tabs; I have implemented Chrome Custom Tabs based on the samples available on the docs.

While most of the urls were successfully shown by parsing it as Uri, one of the url I passed caused crashes when the custom tab tried to open, which looked something like this format:

tag:github.com,2008:PullRequestReviewCommentEvent/4172209621

I am guessing I should not just parse this String url with Uri.parse() method, but I am kind of stuck, seeking to know what to do here.

I am also guessing this is a similar question with this one:
Chrome custom tabs not opening other apps

The crash seems like there is no available activity that can handle this intent:

```<code>FATAL EXCEPTION: main
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=tag:github.com,2008:PullRequestReviewCommentEvent/4172209621 (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1798)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
    at android.app.Activity.startActivityForResult(Activity.java:3930)
    at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
    at android.app.Activity.startActivityForResult(Activity.java:3890)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
    at android.app.Activity.startActivity(Activity.java:4213)
    at android.support.v4.app.ActivityCompatJB.startActivity(ActivityCompatJB.java:27)
    at android.support.v4.app.ActivityCompat.startActivity(ActivityCompat.java:134)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:244)
    at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
    at android.view.View.performClick(View.java:5204)
    at android.view.View$PerformClick.run(View.java:21155)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5422)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

Below is the source code that I have written so far regarding opening an URL with Chrome Custom Tabs:

```<code>public class ArticleFragment extends Fragment {

  @OnClick(R.id.button_see_more) public void onClickSeeMore() {
    launchCustomTabs(article.url());
  }

  private CustomTabsServiceConnection customTabsConnection;
  private CustomTabsClient customTabsClient;
  private CustomTabsSession customTabsSession;

  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ...

    bindCustomTabsService();
  }

  @Override public void onDestroy() {
    unbindCustomTabsService();
    super.onDestroy();
  }

  private void bindCustomTabsService() {
    if (customTabsClient != null) {
      return;
    }

    customTabsConnection = new CustomTabsServiceConnection() {
      @Override public void onCustomTabsServiceConnected(ComponentName componentName,
          CustomTabsClient customTabsClient) {
        ArticleSummaryDetailFragment.this.customTabsClient = customTabsClient;
        customTabsSession = customTabsClient.newSession(new CustomTabsCallback() {
          @Override public void onNavigationEvent(int navigationEvent, Bundle extras) {
            Timber.wtf("onNavigationEvent: Code = " + navigationEvent);
          }
        });

        customTabsSession.mayLaunchUrl(Uri.parse(article.originId()), null, null);
        customTabsClient.warmup(0L);
      }

      @Override public void onServiceDisconnected(ComponentName componentName) {
        customTabsClient = null;
      }
    };

    CustomTabsClient.bindCustomTabsService(getActivity(), getActivity().getPackageName(),
        customTabsConnection);
  }

  private void unbindCustomTabsService() {
    if (customTabsConnection == null) {
      return;
    }

    getActivity().unbindService(customTabsConnection);
    customTabsClient = null;
    customTabsSession = null;
  }

  private void launchCustomTabs(String url) {
    CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(customTabsSession).build();
    customTabsIntent.launchUrl(getActivity(), Uri.parse(url));
  }
}
</code>```

答: In my case Google Chrome Application was disabled. After enabling, it starts working.

Body:
I am currently developing a simple RSS app for Android and one of the app's features is opening url with chrome custom tabs; I have implemented Chrome Custom Tabs based on the samples available on the docs.

While most of the urls were successfully shown by parsing it as Uri, one of the url I passed caused crashes when the custom tab tried to open, which looked something like this format:

tag:github.com,2008:PullRequestReviewCommentEvent/4172209621

I am guessing I should not just parse this String url with Uri.parse() method, but I am kind of stuck, seeking to know what to do here.

I am also guessing this is a similar question with this one:
Chrome custom tabs not opening other apps

The crash seems like there is no available activity that can handle this intent:

FATAL EXCEPTION: main
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=tag:github.com,2008:PullRequestReviewCommentEvent/4172209621 (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1798)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
    at android.app.Activity.startActivityForResult(Activity.java:3930)
    at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
    at android.app.Activity.startActivityForResult(Activity.java:3890)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
    at android.app.Activity.startActivity(Activity.java:4213)
    at android.support.v4.app.ActivityCompatJB.startActivity(ActivityCompatJB.java:27)
    at android.support.v4.app.ActivityCompat.startActivity(ActivityCompat.java:134)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:244)
    at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
    at android.view.View.performClick(View.java:5204)
    at android.view.View$PerformClick.run(View.java:21155)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5422)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Below is the source code that I have written so far regarding opening an URL with Chrome Custom Tabs:

public class ArticleFragment extends Fragment {

  @OnClick(R.id.button_see_more) public void onClickSeeMore() {
    launchCustomTabs(article.url());
  }

  private CustomTabsServiceConnection customTabsConnection;
  private CustomTabsClient customTabsClient;
  private CustomTabsSession customTabsSession;

  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ...

    bindCustomTabsService();
  }

  @Override public void onDestroy() {
    unbindCustomTabsService();
    super.onDestroy();
  }

  private void bindCustomTabsService() {
    if (customTabsClient != null) {
      return;
    }

    customTabsConnection = new CustomTabsServiceConnection() {
      @Override public void onCustomTabsServiceConnected(ComponentName componentName,
          CustomTabsClient customTabsClient) {
        ArticleSummaryDetailFragment.this.customTabsClient = customTabsClient;
        customTabsSession = customTabsClient.newSession(new CustomTabsCallback() {
          @Override public void onNavigationEvent(int navigationEvent, Bundle extras) {
            Timber.wtf("onNavigationEvent: Code = " + navigationEvent);
          }
        });

        customTabsSession.mayLaunchUrl(Uri.parse(article.originId()), null, null);
        customTabsClient.warmup(0L);
      }

      @Override public void onServiceDisconnected(ComponentName componentName) {
        customTabsClient = null;
      }
    };

    CustomTabsClient.bindCustomTabsService(getActivity(), getActivity().getPackageName(),
        customTabsConnection);
  }

  private void unbindCustomTabsService() {
    if (customTabsConnection == null) {
      return;
    }

    getActivity().unbindService(customTabsConnection);
    customTabsClient = null;
    customTabsSession = null;
  }

  private void launchCustomTabs(String url) {
    CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(customTabsSession).build();
    customTabsIntent.launchUrl(getActivity(), Uri.parse(url));
  }
}


问:
Problem with replicating experiment results
I ran some experiments using CreateDataPartition in R to split the train and test data. I looped the results over about 500 times and did it on one laptop. When I tried to replicate the experiments on another laptop with the same code and data, it gave me very different results and not close to what I had before. I assume that this could be due to the seed issue and I am trying to figure out how to manage this so that I can replicate at least almost the same results as before. Any suggestions?

Below is a snapshot of how I am splitting the train and test data:

```<code>for (i in 1:500){
  set.seed(i)
  index = createDataPartition(data$S, p=.75,list=FALSE,times=1)
  train = data[index,]
  test= data[-index,]
</code>```

答:
Based on what i have understand you can try these things :

I had a similar issue of model results are different in two machines. Have you checked the parameters (if you are building the default model you might get different parameters in each machine)and version of which model you are building.

If you think there is a mistake in Train and Test split(which didn't happen to me create a dummy column with 1-n rows in two machines split them with same code and do the intersection of dummy column you will be sure train and test split working properly)

Body:
I ran some experiments using CreateDataPartition in R to split the train and test data. I looped the results over about 500 times and did it on one laptop. When I tried to replicate the experiments on another laptop with the same code and data, it gave me very different results and not close to what I had before. I assume that this could be due to the seed issue and I am trying to figure out how to manage this so that I can replicate at least almost the same results as before. Any suggestions?

Below is a snapshot of how I am splitting the train and test data:

for (i in 1:500){
  set.seed(i)
  index = createDataPartition(data$S, p=.75,list=FALSE,times=1)
  train = data[index,]
  test= data[-index,]


问:
Equality of F# record Types when consumed from C#
I have the following record type in an F# lib:

```<code>type Rating = {
        Id : string
        AverageRating : decimal
        ValueRange : int
        Label : string }
</code>```

And as expected, the following test passes in an F# test lib:

```<code>[Fact]
let ``ShouldConsiderTwoInstancesOfAClassToBeTheSame`` () =

    let a = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    let b = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    a = b |> should equal true
    a.Equals b |> should equal true
    a <> b |> should equal false
    System.Object.ReferenceEquals(a, b) |> should equal false
</code>```

However, the following test in C# fails...both of the first 2 assertions fail, though the third assertion passes fine:

```<code>    [Test]
    public void ShouldConsiderTwoInstancesOfAClassToBeTheSame()
    {
        var a = new Rating("id", 4.3m, 10, "label");
        var b = new Rating("id", 4.3m, 10, "label");

        Assert.True(a == b);
        Assert.False(a != b);
        Assert.True(a.Equals(b));
        Assert.False(ReferenceEquals(a, b));
    }
</code>```

Is there a way to get the structural equality that record types provide out of the box when consuming from C# using just the operators, or do you need to call Equals() ?

答:
In order for == to work in C#, the class in question needs to implement the == operator

```<code>bool operator ==(Rating a, Rating b) => ...
</code>```

If you look at the generated IL-Code for Rating, you will see that it implement IEquatable<T>, IComparable<T>, GetHashCode(), etc. but I have seen no operator implementation.

Body:
I have the following record type in an F# lib:

type Rating = {
        Id : string
        AverageRating : decimal
        ValueRange : int
        Label : string }

And as expected, the following test passes in an F# test lib:

[Fact]
let ``ShouldConsiderTwoInstancesOfAClassToBeTheSame`` () =

    let a = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    let b = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    a = b |> should equal true
    a.Equals b |> should equal true
    a <> b |> should equal false
    System.Object.ReferenceEquals(a, b) |> should equal false

However, the following test in C# fails...both of the first 2 assertions fail, though the third assertion passes fine:

    [Test]
    public void ShouldConsiderTwoInstancesOfAClassToBeTheSame()
    {
        var a = new Rating("id", 4.3m, 10, "label");
        var b = new Rating("id", 4.3m, 10, "label");

        Assert.True(a == b);
        Assert.False(a != b);
        Assert.True(a.Equals(b));
        Assert.False(ReferenceEquals(a, b));
    }

Is there a way to get the structural equality that record types provide out of the box when consuming from C# using just the operators, or do you need to call Equals() ?

Body:
In order for == to work in C#, the class in question needs to implement the == operator

bool operator ==(Rating a, Rating b) => ...

If you look at the generated IL-Code for Rating, you will see that it implement IEquatable<T>, IComparable<T>, GetHashCode(), etc. but I have seen no operator implementation.


问:
How to enable app on apple app store to view-able on browser?
This is the first time I upload an app to apple app store. After weeks for reviewing, finally, I get my app listed on apple app store. But the problem is, now seems like my app app-store page is only viewable from iTunes. When I try to open it in a browser, it will shows "Connecting to the iTunes Store...". Why is it my app can't be the view from the browser? Why did another app can? How to fix it?</p>

答:
If your app is intended for a specific region, AppStore connect will still give you a  URL with .../us/... in it. Changing it to the respective local region seems to fix the problem for me.

For an example,
given URL: https://apps.apple.com/us/app/yourcompany/id123456

If the app is for Norway region, change the URL to: https://apps.apple.com/no/app/yourcompany/id123456


问:
How to calculate the time spent when using got?
Example code:

```<code>const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}
</code>```

I wonder if there is a better way?

答:
You can go through this way.

console.time('test1');
console.time('test2');

setTimeout( (elem) => {
   console.log('You want to write something here!!');
   console.timeEnd('test2');
}, 2000);

console.timeEnd('test1');```

Body:
Example code:

const got = require('got');
async function timeSpent (){
   const time = new Date().getTime()
   await got('***')
   return new Date().getTime() - time
}

I wonder if there is a better way?


问:
sqlalchemy @hybrid_property expressions for folder and filename from filepath. Very easy to write in pure python
I have a database I'm using sqlalchemy with, which involves storing the locations of files.

I have something like:

```<code>class FileLocation(ORMBase):
    id = Column('id', Integer, primary_key=True)
    filepath = Column('filepath', String)
</code>```

and I want to add hybrid expressions of the folder and filename corresponding to each filepath. This is pretty easy to do with regular python strings, of course, but I can't find a way to do this sort of string manipulation in sqlalchemy expressions.

```<code>from sqlalchemy import func

class FileLocation(ORMBase):

    id = Column('id', Integer, primary_key=True)
    filepath = Column('filepath', String)

    @hybrid_property
    def folder(self):
        return os.path.dirname(self.filepath)

    @folder.expression
    def folder(cls):
        # How to  get folder for sql queries???
        last_pathsep_index = # ???
        return func.substr(cls.filepath, 0, last_pathsep_index)

    @hybrid_property
    def filename(self):
        return os.path.basename(self.filepath)

    @filename.expression
    def filename(cls):
        # How to  get filename for sql queries???
        last_pathsep_index = # ???
        return func.substr(cls.filepath, last_pathsep_index+1, func.len(cls.filepath))
</code>```

How would I go about writing the @filename.expression and @folder.expression attributes, which currently are shown with incomplete implementations?

答:
Here is the solution I ended up with, which I found through @AnthonyCarapetis' suggested link.

This ended up being more just a straight SQL (SQLite) question than about sqlalchemy, but I'll leave the sqlalchemy code here in case it helps anyone else.

```<code>import os

import sqlalchemy as sa
from sqlalchemy import case, func

def getpathsep(osname=os.name):
    """use os.name to determine osname"""
    return case([(osname == 'nt', '\\')], else_='/')

def dirname(filepath, osname=os.name):
    """use os.name to determine osname"""
    pathsep = getpathsep(osname)
    replaced = func.replace(filepath, pathsep, '')
    filename = func.rtrim(filepath, replaced)
    return func.substr(filepath, 0, func.length(filename))

def pathsplit(filepath, osname=os.name):
    """use os.name to determine osname"""
    folder = dirname(filepath, osname)
    l = func.length(folder) + 1  # add 1 for (back) slash char
    basename = func.substr(filepath, l + 1)  # First index is 1
    return folder, basename

def basename(filepath, osname=os.name):
    """use os.name to determine osname"""
    return pathsplit(filepath, osname)[1]

class FileLocation(ORMBase):

    id = Column('id', Integer, primary_key=True)
    osname = Column('osname', String)
    filepath = Column('filepath', String)

    @hybrid_property
    def folder(self):
        return os.path.dirname(self.filepath)

    @folder.expression
    def folder(cls):
        return dirname(cls.filepath, cls.osname)

    @hybrid_property
    def filename(self):
        return os.path.basename(self.filepath)

    @filename.expression
    def filename(cls):
        return basename(cls.filepath, cls.osname)
</code>```

Body:
I have a database I'm using sqlalchemy with, which involves storing the locations of files.

I have something like:

class FileLocation(ORMBase):
    id = Column('id', Integer, primary_key=True)
    filepath = Column('filepath', String)

and I want to add hybrid expressions of the folder and filename corresponding to each filepath. This is pretty easy to do with regular python strings, of course, but I can't find a way to do this sort of string manipulation in sqlalchemy expressions.

from sqlalchemy import func

class FileLocation(ORMBase):

    id = Column('id', Integer, primary_key=True)
    filepath = Column('filepath', String)

    @hybrid_property
    def folder(self):
        return os.path.dirname(self.filepath)

    @folder.expression
    def folder(cls):
        # How to  get folder for sql queries???
        last_pathsep_index = # ???
        return func.substr(cls.filepath, 0, last_pathsep_index)

    @hybrid_property
    def filename(self):
        return os.path.basename(self.filepath)

    @filename.expression
    def filename(cls):
        # How to  get filename for sql queries???
        last_pathsep_index = # ???
        return func.substr(cls.filepath, last_pathsep_index+1, func.len(cls.filepath))

How would I go about writing the @filename.expression and @folder.expression attributes, which currently are shown with incomplete implementations?

Body:
Here is the solution I ended up with, which I found through @AnthonyCarapetis' suggested link.

This ended up being more just a straight SQL (SQLite) question than about sqlalchemy, but I'll leave the sqlalchemy code here in case it helps anyone else.

import os

import sqlalchemy as sa
from sqlalchemy import case, func

def getpathsep(osname=os.name):
    """use os.name to determine osname"""
    return case([(osname == 'nt', '\\')], else_='/')

def dirname(filepath, osname=os.name):
    """use os.name to determine osname"""
    pathsep = getpathsep(osname)
    replaced = func.replace(filepath, pathsep, '')
    filename = func.rtrim(filepath, replaced)
    return func.substr(filepath, 0, func.length(filename))

def pathsplit(filepath, osname=os.name):
    """use os.name to determine osname"""
    folder = dirname(filepath, osname)
    l = func.length(folder) + 1  # add 1 for (back) slash char
    basename = func.substr(filepath, l + 1)  # First index is 1
    return folder, basename

def basename(filepath, osname=os.name):
    """use os.name to determine osname"""
    return pathsplit(filepath, osname)[1]

class FileLocation(ORMBase):

    id = Column('id', Integer, primary_key=True)
    osname = Column('osname', String)
    filepath = Column('filepath', String)

    @hybrid_property
    def folder(self):
        return os.path.dirname(self.filepath)

    @folder.expression
    def folder(cls):
        return dirname(cls.filepath, cls.osname)

    @hybrid_property
    def filename(self):
        return os.path.basename(self.filepath)

    @filename.expression
    def filename(cls):
        return basename(cls.filepath, cls.osname)


问:
How do I make a gif to animate in IE after it was hidden?
I want to show a gif in IE and is not animating. First I added to it the hide class(display: none)
and then I am showing it with .show() method from jquery.
The problem is that the gif is not animating, but if is visible when I first open the page then it works.
I couldn't find I way to make it work for my case.

Code:

```<code><img src="~/Content/images/circular-loading.gif" id="loginLoadingGif" class="hide" />

$('#loginLoadingGif').show();
</code>```

答:
Please refer to the following code, it uses the .loader div to display the loading image, and use the CSS visibility property to show and hide the loading image (you could change it to CSS display property, and use "none" and "block" value to hide/show the image):

```<code><style type="text/css">
    .contents{
      visibility:hidden;
    }
    .loader {
      border: 16px solid #f3f3f3;
      border-radius: 50%;
      border-top: 16px solid blue;
      border-right: 16px solid green;
      border-bottom: 16px solid red;
      border-left: 16px solid pink;
      width: 120px;
      height: 120px;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }

    @-webkit-keyframes spin {
      0% { -webkit-transform: rotate(0deg); }
      100% { -webkit-transform: rotate(360deg); }
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
</style>

<script type="text/javascript">
    document.onreadystatechange = function () {
        var state = document.readyState
        if (state == 'interactive') {
            document.getElementById('contents').style.visibility = "hidden";
        } else if (state == 'complete') {
            setTimeout(function () {
                document.getElementById('interactive');
                document.getElementById('load').style.visibility = "hidden";
                document.getElementById('contents').style.visibility = "visible";
            }, 2000);
        }
    }

    function LoadImage(){
         document.getElementById('load').style.visibility = "visible";
         setTimeout(function () {
                document.getElementById('interactive');
                document.getElementById('load').style.visibility = "hidden";
                document.getElementById('contents').style.visibility = "visible";
            }, 3000);
    }
</script>

<form id="form1" runat="server">
    <div id="load" class="loader"></div>
    <div id="contents" class="contents">
        This is testing
    </div>
    <input type="button" id="btnShow" value="Show Loader" onClick="LoadImage();">
</form>
</code>```

The output as below (when page loads, it will display the loading image, after page load, if we click the Show Loader button, it will show the loading image and after 3 second, it will hide the image):

Reference:

How TO - CSS Loader

Display (Show) Loading Progress GIF Image when Page Loads in ASP.Net MVC

Body:
I want to show a gif in IE and is not animating. First I added to it the hide class(display: none)
and then I am showing it with .show() method from jquery.
The problem is that the gif is not animating, but if is visible when I first open the page then it works.
I couldn't find I way to make it work for my case.

Code:

$('#loginLoadingGif').show();

Body:
Please refer to the following code, it uses the .loader div to display the loading image, and use the CSS visibility property to show and hide the loading image (you could change it to CSS display property, and use "none" and "block" value to hide/show the image):

<style type="text/css">
    .contents{
      visibility:hidden;
    }
    .loader {
      border: 16px solid #f3f3f3;
      border-radius: 50%;
      border-top: 16px solid blue;
      border-right: 16px solid green;
      border-bottom: 16px solid red;
      border-left: 16px solid pink;
      width: 120px;
      height: 120px;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }

    @-webkit-keyframes spin {
      0% { -webkit-transform: rotate(0deg); }
      100% { -webkit-transform: rotate(360deg); }
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
</style>

<script type="text/javascript">
    document.onreadystatechange = function () {
        var state = document.readyState
        if (state == 'interactive') {
            document.getElementById('contents').style.visibility = "hidden";
        } else if (state == 'complete') {
            setTimeout(function () {
                document.getElementById('interactive');
                document.getElementById('load').style.visibility = "hidden";
                document.getElementById('contents').style.visibility = "visible";
            }, 2000);
        }
    }

    function LoadImage(){
         document.getElementById('load').style.visibility = "visible";
         setTimeout(function () {
                document.getElementById('interactive');
                document.getElementById('load').style.visibility = "hidden";
                document.getElementById('contents').style.visibility = "visible";
            }, 3000);
    }
</script>

<form id="form1" runat="server">
    <div id="load" class="loader"></div>
    <div id="contents" class="contents">
        This is testing
    </div>
    <input type="button" id="btnShow" value="Show Loader" onClick="LoadImage();">
</form>

The output as below (when page loads, it will display the loading image, after page load, if we click the Show Loader button, it will show the loading image and after 3 second, it will hide the image):

Reference:

How TO - CSS Loader

Display (Show) Loading Progress GIF Image when Page Loads in ASP.Net MVC


问:
How to enable .htaccess in AWS Lightsail LAMP module
I am new to AWS Lightsail.

I have successfully migrated my web application to a LAMP server (bitnami) and I generated SSL certificate. now I want to redirect to HTTP to HTTPS. Hence I created .htaccess and copied the below the code and restarted my server. but the page is not migrating from http to https. can you please help me to enable .htaccess?

Since I am planning to host 3 websites, I am looking for .htaccess so that I can configure locally based on the condition.

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.in [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.test.in/$1 [R,L]
</code>```

Thank you.

答:
Bitnami Engineer here:

By default, we disable .htaccess files due to security and performance reasons. We also move .htaccess files content to a file called htaccess.conf in the folder /opt/bitnami/apps/APPNAME/conf. You can check more about it at https://docs.bitnami.com/aws/infrastructure/lamp/administration/use-htaccess/.

If you want to enable .htaccess usage, you would need to set it to AllowOverride All in /opt/bitnami/apache2/conf/bitnami/bitnami.conf file:

```<code><VirtualHost _default_:80>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  <Directory "/opt/bitnami/apache2/htdocs">
    Options Indexes FollowSymLinks
    AllowOverride All <---- HERE
    <IfVersion < 2.3 >
      Order allow,deny
      Allow from all
    </IfVersion>
    <IfVersion >= 2.3 >
      Require all granted
    </IfVersion>
  </Directory>
</code>```

Restart Apache after applying your changes.

Regards

Body:
I am new to AWS Lightsail.

I have successfully migrated my web application to a LAMP server (bitnami) and I generated SSL certificate. now I want to redirect to HTTP to HTTPS. Hence I created .htaccess and copied the below the code and restarted my server. but the page is not migrating from http to https. can you please help me to enable .htaccess?

Since I am planning to host 3 websites, I am looking for .htaccess so that I can configure locally based on the condition.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.in [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.test.in/$1 [R,L]

Thank you.

Body:
Bitnami Engineer here:

By default, we disable .htaccess files due to security and performance reasons. We also move .htaccess files content to a file called htaccess.conf in the folder /opt/bitnami/apps/APPNAME/conf. You can check more about it at https://docs.bitnami.com/aws/infrastructure/lamp/administration/use-htaccess/.

If you want to enable .htaccess usage, you would need to set it to AllowOverride All in /opt/bitnami/apache2/conf/bitnami/bitnami.conf file:

<VirtualHost _default_:80>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  <Directory "/opt/bitnami/apache2/htdocs">
    Options Indexes FollowSymLinks
    AllowOverride All <---- HERE
    <IfVersion < 2.3 >
      Order allow,deny
      Allow from all
    </IfVersion>
    <IfVersion >= 2.3 >
      Require all granted
    </IfVersion>
  </Directory>

Restart Apache after applying your changes.

Regards


问:
passing list of strings in efficient way
```<code>#include <iostream>
#include <vector>
#include <string>

void function1(const char** keywords) {  // C like
    for (const char** keyword = keywords; *keyword; ++keyword) {
        std::cout << *keyword << std::endl;
    }
}

void function2(const std::vector<std::string>& keywords) {  // C++11 like
    for(const std::string& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}

int main() {
    static const char* keywords[] = { "hello", "world", "!", 0 };
    function1(keywords);
    function2({ "hello", "world", "!" });
    return 0;
}
</code>```

Both functions do the same result. I like the new c++11 format of initialization where values are inline and I can skip empty value (zero). The issue is a performance. I expect that function2 will dynamically alocate memory on each invoke. I suppose it wan't be efficient. Is there a better way to implement such function with c++ manner keeping old C efficency?

Update:

There is a little misunderstanding. My concern is usage of std::vector which provokes dynamic memory allocation. In fact I would use std::string in the body of function1 so std::string allocation is not a case. The same std::cout was added by me as an example of usage (not a real case). std::array cannot be used here becouse length of list is not fixed.

I extend my question:
Goal is use only one argument with default empty value to pass list of strings. How to achieve this in most effient and pretty-look way?

So above functions' declarations may look as follows:

```<code>void function1(const char** keywords = nullptr)

void function2(const std::vector<std::string>& keywords = {})
</code>```

Here I see the next problem. Invoking function1 without parameter cost nothing but I expect empty vector initialization in function2. Am I right?

答:
If there is choice for C++17
there is new class std::string_view  that is exactly what you want.</p>

```<code>void function2(const std::vector<std::string_view>& keywords) {  // C++17
    for(auto const& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}
</code>```

Body:
#include <iostream>
#include <vector>
#include <string>

void function1(const char** keywords) {  // C like
    for (const char** keyword = keywords; *keyword; ++keyword) {
        std::cout << *keyword << std::endl;
    }
}

void function2(const std::vector<std::string>& keywords) {  // C++11 like
    for(const std::string& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}

int main() {
    static const char* keywords[] = { "hello", "world", "!", 0 };
    function1(keywords);
    function2({ "hello", "world", "!" });
    return 0;
}

Both functions do the same result. I like the new c++11 format of initialization where values are inline and I can skip empty value (zero). The issue is a performance. I expect that function2 will dynamically alocate memory on each invoke. I suppose it wan't be efficient. Is there a better way to implement such function with c++ manner keeping old C efficency?

Update:

There is a little misunderstanding. My concern is usage of std::vector which provokes dynamic memory allocation. In fact I would use std::string in the body of function1 so std::string allocation is not a case. The same std::cout was added by me as an example of usage (not a real case). std::array cannot be used here becouse length of list is not fixed.

I extend my question:
Goal is use only one argument with default empty value to pass list of strings. How to achieve this in most effient and pretty-look way?

So above functions' declarations may look as follows:

void function1(const char** keywords = nullptr)

void function2(const std::vector<std::string>& keywords = {})

Here I see the next problem. Invoking function1 without parameter cost nothing but I expect empty vector initialization in function2. Am I right?

Body:
If there is choice for C++17
there is new class std::string_view  that is exactly what you want.

void function2(const std::vector<std::string_view>& keywords) {  // C++17
    for(auto const& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}


问:
Error trying to import CSV in Leads Module in Vtiger CRM 7.0
We have in trouble trying to import CSV to leads module in CRM 7.0 where there is the message error saying " Unable to import more data in this batch. Please start a new import. "

Any assistance and reply is greatly appreciated.

答:
You have already one import job in queue which is not finished yet.

This import will be done via cron, so make sure you have configured vtiger cron.

There will be only one import job is allowed for a user. So you can import from another user if you want.


问:
Syntax for Wget to execute same call 10 times
Is there a way to call the same url 10 times in sequence via wget rather than sending the same call again manually? Thanks!!
for example, instead of sending this call manually can i have the call execute 10 times?
time wget -O test.txt --no-check-certificate https:google.com

I am basically trying to get the average response time for a url using this.

答:
Solution 1 :

Create a text file "input.txt" with the same URL copied 10 times, 1 per line.

Then, add "-i input.txt" to your wget command instead of "https:google.com" (which >is incorrect anyway).

This will make wget call the same URL 10 times.

Solution 2 :

Assuming your shell is bash, you can call wget in a loop like so -

for x in {1..10}; do time wget -O test.txt --no-check-certificate https://google.com ; done ;

This will also call wget 10 times for the same URL.

What is the difference between the two approaches ?

Solution1 will call the URL 10 times from a single wget instance and Solution2 will spawn a new wget instance for each of the 10 attempts.


问:
if statement in gridview template filed
I have a gridview. its data source is a datatable that is loaded from the database.
In this gridview, i have a template column. The content of this column is not directly pulled from the database but instead, i use the id of the current item to make a name and look for that name in a directory of images. The template field is:

```<code><asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>' />
    </itemtemplate>
</asp:TemplateField>
</code>```

Not all the items have images so I would like to check if this file exists. If it does, I'd like to use the above code to place it, if it doesn't i'd like to leave the field empty.
In the .cs file this is a matter of an if statement with the condition set to File.Exist(). But I could not find the syntax to do it in the .aspx file.
Is this possible and if so how?
Thanks.

答:
img tag has an event called onerror. So, if your requirement is to do something if the image is not found, do something like this.

onerror="this.src='Images/default.png'"

Title: if statement in gridview template filed

Body:
I have a gridview. its data source is a datatable that is loaded from the database.
In this gridview, i have a template column. The content of this column is not directly pulled from the database but instead, i use the id of the current item to make a name and look for that name in a directory of images. The template field is:

<asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>' />
    </itemtemplate>
</asp:TemplateField>

Not all the items have images so I would like to check if this file exists. If it does, I'd like to use the above code to place it, if it doesn't i'd like to leave the field empty.
In the .cs file this is a matter of an if statement with the condition set to File.Exist(). But I could not find the syntax to do it in the .aspx file.
Is this possible and if so how?
Thanks.


问:
How do i display pagination data to table in Laravel
I try to display specify paginate data to table...My paginate data contain json that already been decode in controller...I want display NICK_NAME in table

```<code>public function index()
{

 $response =  $this->client->get('getUserIndex')->getBody();
     $content = json_decode($response->getContents());
     $total = count($content) ;
     $collection = new \Illuminate\Support\Collection($content);
     $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');
     return view('configuration.comuserprofiles.ComUserProfilesList', compact('paginationRecord'));
}
</code>```

This is my dd of paginationrecord

```<code>LengthAwarePaginator {#4177 ▼
  #total: 1
  #lastPage: 1
  #items: Collection {#4169 ▼
    #items: array:1 [▼
      "data" => array:852 [▼
        0 => {#624 ▶}
        1 => {#623 ▶}
        2 => {#628 ▼
          +"ID": "cust1"
          +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
          +"NICK_NAME": "CUST1"  //i want display this
          +"PWD_INVALID_HIT": "0"
          +"PWD_CREATE_DT": "2019/07/22 15:57:15"
          +"INSTITUTION_ID": "C01"
          +"ACL_ID": "L04"
          +"LOGIN_DT": "2019/07/22 15:57:15"
          +"LOGIN_STS_ID": "N"
          +"STS_ID": "C08"
          +"TYPE_ID": "U00"
          +"UPD_ID": "sufyzasukor"
          +"UPD_DT": "2019/07/22 15:57:15"
          +"EMAIL_ID": "cust1@gmail.com"
          +"PHONE_NO_ID": "0"
          +"HP_ID": "0                        "
          +"CRT_DATE_DELETED": null
          +"irel__com_access_level": {#621 …9}
          +"irel__com_user_types": {#630 …5}
          +"irel__com_status": {#631 …5}
        }
 ]
  }
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}
</code>```

How do i write from here

```<code><tbody>
          @foreach($paginationRecord as $i=>$user)
                   <td>$user ??<td>
          @endforeach
</tbody>
</code>```

How do i access and display data from LengthAwarePaginator ?? Sorry if my explaination no clear because this is something new for me

答:
When calling the paginate method, you will receive an instance of Illuminate\Pagination\LengthAwarePaginator

So, once you have retrieved the results, you may display the results and render the page links using Blade:

```<code><div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $users->links() }}
</code>```

The links method will render the links to the rest of the pages in the result set. Each of these links will already contain the proper page query string variable.

Source: https://laravel.com/docs/5.8/pagination

Body:
I try to display specify paginate data to table...My paginate data contain json that already been decode in controller...I want display NICK_NAME in table

public function index()
{

 $response =  $this->client->get('getUserIndex')->getBody();
     $content = json_decode($response->getContents());
     $total = count($content) ;
     $collection = new \Illuminate\Support\Collection($content);
     $paginationRecord = CollectionPaginate::paginate($collection, $total, '15');
     return view('configuration.comuserprofiles.ComUserProfilesList', compact('paginationRecord'));
}

This is my dd of paginationrecord

LengthAwarePaginator {#4177 ▼
  #total: 1
  #lastPage: 1
  #items: Collection {#4169 ▼
    #items: array:1 [▼
      "data" => array:852 [▼
        0 => {#624 ▶}
        1 => {#623 ▶}
        2 => {#628 ▼
          +"ID": "cust1"
          +"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
          +"NICK_NAME": "CUST1"  //i want display this
          +"PWD_INVALID_HIT": "0"
          +"PWD_CREATE_DT": "2019/07/22 15:57:15"
          +"INSTITUTION_ID": "C01"
          +"ACL_ID": "L04"
          +"LOGIN_DT": "2019/07/22 15:57:15"
          +"LOGIN_STS_ID": "N"
          +"STS_ID": "C08"
          +"TYPE_ID": "U00"
          +"UPD_ID": "sufyzasukor"
          +"UPD_DT": "2019/07/22 15:57:15"
          +"EMAIL_ID": "cust1@gmail.com"
          +"PHONE_NO_ID": "0"
          +"HP_ID": "0                        "
          +"CRT_DATE_DELETED": null
          +"irel__com_access_level": {#621 …9}
          +"irel__com_user_types": {#630 …5}
          +"irel__com_status": {#631 …5}
        }
 ]
  }
  #perPage: "15"
  #currentPage: 1
  #path: "http://localhost/IFICSV3/public/configuration/comuserprofiles"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

How do i write from here

          @foreach($paginationRecord as $i=>$user)
                   $user ??
          @endforeach

How do i access and display data from LengthAwarePaginator ?? Sorry if my explaination no clear because this is something new for me

Body:
When calling the paginate method, you will receive an instance of Illuminate\Pagination\LengthAwarePaginator

So, once you have retrieved the results, you may display the results and render the page links using Blade:

<div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $users->links() }}

The links method will render the links to the rest of the pages in the result set. Each of these links will already contain the proper page query string variable.

Source: https://laravel.com/docs/5.8/pagination


问:
Is this boolean conversion correct?
I have a boolean expression that looks like this

```<code>(!B and !C) or (B and !D) or (A and !C)
</code>```

And I need to convert it so that it only has and operations. So I came up with this result

```<code>(B and C) and (!B and D) and (!A and C)
</code>```

Is this correct or am I doing something wrong? I just want to make it sure.

I also know that

```<code>A or B
</code>```

Is equilevant to

```<code>!(!A and !B)
</code>```

答:
If you apply your last expression to replace OR by AND, you can rewrite your Boolean expression to

```<code>!(!(!B and !C) and !(B and !D) and !(A and !C))
</code>```

But the Boolean expression can be simplified to

```<code>!C or (B and !D)
</code>```

Karnaugh map:

```<code>         cd
       00  01  11  10
      +---+---+---+---+
   00 | 1 | 1 | 0 | 0 |
      +---+---+---+---+
   01 | 1 | 1 | 0 | 1 |
ab    +---+---+---+---+
   11 | 1 | 1 | 0 | 1 |
      +---+---+---+---+
   10 | 1 | 1 | 0 | 0 |
      +---+---+---+---+
</code>```

This can be expressed as

```<code>!(C and !(B and !D))
</code>```

Title: Is this boolean conversion correct?

Body:
I have a boolean expression that looks like this

(!B and !C) or (B and !D) or (A and !C)

And I need to convert it so that it only has and operations. So I came up with this result

(B and C) and (!B and D) and (!A and C)

Is this correct or am I doing something wrong? I just want to make it sure.

I also know that

A or B

Is equilevant to

!(!A and !B)

Body:
If you apply your last expression to replace OR by AND, you can rewrite your Boolean expression to

!(!(!B and !C) and !(B and !D) and !(A and !C))

But the Boolean expression can be simplified to

!C or (B and !D)

Karnaugh map:

         cd
       00  01  11  10
      +---+---+---+---+
   00 | 1 | 1 | 0 | 0 |
      +---+---+---+---+
   01 | 1 | 1 | 0 | 1 |
ab    +---+---+---+---+
   11 | 1 | 1 | 0 | 1 |
      +---+---+---+---+
   10 | 1 | 1 | 0 | 0 |
      +---+---+---+---+

This can be expressed as

!(C and !(B and !D))


问:
Understaning stdin, stderr, stdout
I want to write a script that will:

read a text stream on stdin

print every 10th line on stderr

print a random* line on stdout

I tried

```<code>#!/bin/bash

count=0
while IFS= read -r line; do

        awk '{if(NR%3==0) print $line}' >&2
        awk '{if(( RANDOM % 2 )) print $line}' >&1
done
</code>```

However, RANDOM is not working.
What is wrong here? How to fix this?

答:
You must assing the RANDOM bash variable value as awk variables before using it. The random line must be something like:</p>

```<code>awk -v random="$RANDOM" -v aline="$line" 'BEGIN {if(random % 2) print aline}' >&1
</code>```

Title: Understaning stdin, stderr, stdout

Body:
I want to write a script that will:

read a text stream on stdin

print every 10th line on stderr

print a random* line on stdout

I tried

#!/bin/bash

count=0
while IFS= read -r line; do

        awk '{if(NR%3==0) print $line}' >&2
        awk '{if(( RANDOM % 2 )) print $line}' >&1
done

However, RANDOM is not working.
What is wrong here? How to fix this?

Body:
You must assing the RANDOM bash variable value as awk variables before using it. The random line must be something like:

awk -v random="$RANDOM" -v aline="$line" 'BEGIN {if(random % 2) print aline}' >&1


问:
How do I make my tkinter image pop not show the tkinter option window
I have a simple code that opens an exe. This exe makes a pop-up image using Tkinter but there is an option to delete or minimise the photo. How do I get rid of this option?

here is my code
and here is the TK option I was talking about

[![enter image description here]

and here is the TK option I was talking about

答:
You can try:

CODE_1: where it will show minize, maximize and exit but it will not work

```<code>from tkinter import *

window = Tk()
window.title("Grand Canyon")
canvas = Canvas(window, width=500, height=500)
canvas.pack()
#window.overrideredirect(1)
window.attributes('-disabled', True)
window.resizable(0,0)
window.mainloop()
</code>```

CODE_2: where it will NOT show minize, maximize and exit because it will pack into the top of your window

```<code>from tkinter import *

window = Tk()
window.title("Grand Canyon")
canvas = Canvas(window, width=500, height=500)
canvas.pack()
window.overrideredirect(1)
#window.attributes('-disabled', True)
window.resizable(0,0)
window.mainloop()
</code>```

Body:
You can try:

CODE_1: where it will show minize, maximize and exit but it will not work

from tkinter import *

window = Tk()
window.title("Grand Canyon")
canvas = Canvas(window, width=500, height=500)
canvas.pack()
#window.overrideredirect(1)
window.attributes('-disabled', True)
window.resizable(0,0)
window.mainloop()

CODE_2: where it will NOT show minize, maximize and exit because it will pack into the top of your window

from tkinter import *

window = Tk()
window.title("Grand Canyon")
canvas = Canvas(window, width=500, height=500)
canvas.pack()
window.overrideredirect(1)
#window.attributes('-disabled', True)
window.resizable(0,0)
window.mainloop()


问:
Slope/Intercept ratio with Purrr in R
I'm looking to print a one way view for the ratio between the slope and the intercept.

so far I've got:

```<code>mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")
</code>```

This works and prints the intercept and slope as required but i cant seem to do any calculations on either.

I've tried the following to get the ratio between the two.

```<code>mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")/map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt"/"(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl(map_dbl("wt")/map_dbl("(Intercept)"))
</code>```

Any help appreciated, thanks.

答:
subset the current element ./.x using names then create a division formula using ~

```<code>mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map_dbl(~.[["coefficients"]][["wt"]]/.[["coefficients"]][["(Intercept)"]]) #%>%
  #enframe(name = "cyl", value = "ratio") #produces output as a data.frame

          4           6           8
-0.14270545 -0.09786058 -0.09185668
</code>```

to make your approach works we can use {}

```<code>mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% {map_dbl(.,"wt")/map_dbl(.,"(Intercept)")}
</code>```

Title: Slope/Intercept ratio with Purrr in R

Body:
I'm looking to print a one way view for the ratio between the slope and the intercept.

so far I've got:

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")

This works and prints the intercept and slope as required but i cant seem to do any calculations on either.

I've tried the following to get the ratio between the two.

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")/map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt"/"(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl(map_dbl("wt")/map_dbl("(Intercept)"))

Any help appreciated, thanks.

Body:
subset the current element ./.x using names then create a division formula using ~

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map_dbl(~.[["coefficients"]][["wt"]]/.[["coefficients"]][["(Intercept)"]]) #%>%
  #enframe(name = "cyl", value = "ratio") #produces output as a data.frame

          4           6           8
-0.14270545 -0.09786058 -0.09185668

to make your approach works we can use {}

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% {map_dbl(.,"wt")/map_dbl(.,"(Intercept)")}


问:
AngularJS filter where checking if array parameter contains value
I have simple function to set active state for nav based on url:

```<code>angular.forEach(this.$filter('filter')(this.fullNav, {
    'link': this.$location.$$path
}, true), (item) => {
    item.active = true;
});
</code>```

Now I want to add legacy URLs to be also highlighted. Instead of link I have links (if there are more then one, but I can make all links parameters to be arrays.

To have it work with links and link paramaters I made change to this:

```<code>angular.forEach(this.fullNav, (item) => {
    if(item.links) {
        if(item.links.includes(this.$location.$$path)) {
            item.active = true;
        }
    } else {
        if(item.link === this.$location.$$path) {
            item.active = true;
        }
    }
});
</code>```

How can I write the second function in $filter form? Or at least without if else statement (by removing link property and having only links property).

答:
you can try following code which is similar to the code you have added.</p>

```<code>angular.forEach(this.$filter('filter')(this.fullNav, (item) => {
    return Array.isArray(item.links) && item.links.includes(this.$location.$$path);
}, true), (item) => {
    item.active = true;
});
</code>```

Body:
I have simple function to set active state for nav based on url:

angular.forEach(this.$filter('filter')(this.fullNav, {
    'link': this.$location.$$path
}, true), (item) => {
    item.active = true;
});

Now I want to add legacy URLs to be also highlighted. Instead of link I have links (if there are more then one, but I can make all links parameters to be arrays.

To have it work with links and link paramaters I made change to this:

angular.forEach(this.fullNav, (item) => {
    if(item.links) {
        if(item.links.includes(this.$location.$$path)) {
            item.active = true;
        }
    } else {
        if(item.link === this.$location.$$path) {
            item.active = true;
        }
    }
});

How can I write the second function in $filter form? Or at least without if else statement (by removing link property and having only links property).

Body:
you can try following code which is similar to the code you have added.

angular.forEach(this.$filter('filter')(this.fullNav, (item) => {
    return Array.isArray(item.links) && item.links.includes(this.$location.$$path);
}, true), (item) => {
    item.active = true;
});


问:
Can we run our webpack (UI) build just like that in an browser without any server?
I have a reactjs setup with webpack dev server, and a webpack build. Can I run the build file which is bundle.js in browser directly? When we make a build and deploy it on cloud, what happens and how our application runs?

答: Sorry you can't run webpack on a browser without any server.....</p>


问:
How to replace NAs with values from another column in data.table (Example given)?
DT is data.table and I want to replace NAs with values from visits column and Expected_DT is desired DT.

```<code>DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

This is what I want

```<code>Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

答:
A few options:

1) using fcoalesce

```<code>DT[, count := fcoalesce(visits, count)]
</code>```

2) using is.na:

```<code>DT[is.na(count), count := visits]
</code>```

3) using fifelse:

```<code>DT[, count := fifelse(is.na(count), visits, count)]
</code>```

4) using set and using sindri_baldur's comment on [[ for faster indexing:

```<code>ix <- DT[is.na(count), which=TRUE]
set(DT, ix, "count", DT[["visits"]][ix])
</code>```

Body:
DT is data.table and I want to replace NAs with values from visits column and Expected_DT is desired DT.

DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

This is what I want

Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

Body:
A few options:

1) using fcoalesce

DT[, count := fcoalesce(visits, count)]

2) using is.na:

DT[is.na(count), count := visits]

3) using fifelse:

DT[, count := fifelse(is.na(count), visits, count)]

4) using set and using sindri_baldur's comment on [[ for faster indexing:

ix <- DT[is.na(count), which=TRUE]
set(DT, ix, "count", DT[["visits"]][ix])


问:
How to check user agent inside Django template?
I want to check the useragent using Django inside my template. I know this is possible using JavaScript, but I wanted a server side solution.

I know I can use HttpRequest.META in some middleware class, which I am not currently looking for. I want to determine this using some code in the template itself, without any dependency on other files / classes.

Can anybody help?

答:
You need to use context processors, more specifically django.core.context_processors.request.

This SO answer covers it quiet well:
How can I pass data to any template from any view in Django?

Especially this blog post, that is referenced in the SO answer:

http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/


答:
Solution using data.table:

```<code>DT[is.na(count),  count:=visits]

DT
</code>```

Returns:

```<code>   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78
</code>```

Title: How to replace NAs with values from another column in data.table (Example given)?

Body:
Solution using data.table:

DT[is.na(count),  count:=visits]

DT

Returns:

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78