问:
Cannot reference filled 2D array
I'm trying to finish this magic square project but when filling the square its referring to the empty instance variable rather than the one with a defined size and I can't seem to fix it.

It says null error at line 22.

Can anyone help me with this?

```<code>
public class MagicSquare {
    private int[][] magicSquare;

    public MagicSquare(int size){
        int[][] magicSquare = new int[size][size];
        fillSquare(size);
    }
    private void fillSquare(int size){
        int row = size - 1;
        int col = size / 2;
        magicSquare[row][col] = 1;

        for (int i = 2;i < size * size;++i){
            if (magicSquare[(1 + row) % size][(col + 1) % size] == 0){
                row = (1 + row) % size;
                col = (1 + col) % size;
            }
            else {
                row = ( row - 1 + size) % size;
            }
            magicSquare[row][col] = i;
        }
    }
    public void toString(int size){
        for (int i = 0; i < size;++i){
            for (int j = 0; j < size;++j){
                System.out.println(magicSquare[i][j]);
            }
        }

    }

}

</code>```

答:
don't init magicSquare in int[][] magicSquare = new int[size][size];

that over rides the global magicSquare instance ,

your code should look like this:

```<code> public class MagicSquare {
        private int[][] magicSquare;

        public MagicSquare(int size){
            magicSquare = new int[size][size];
            fillSquare(size);
        }
        private void fillSquare(int size){
            int row = size - 1;
            int col = size / 2;
            magicSquare[row][col] = 1;

            for (int i = 2;i < size * size;++i){
                if (magicSquare[(1 + row) % size][(col + 1) % size] == 0){
                    row = (1 + row) % size;
                    col = (1 + col) % size;
                }
                else {
                    row = ( row - 1 + size) % size;
                }
                magicSquare[row][col] = i;
            }
        }
        public void toString(int size){
            for (int i = 0; i < size;++i){
                for (int j = 0; j < size;++j){
                    System.out.println(magicSquare[i][j]);
                }
            }

        }

    }
</code>```

Title: Cannot reference filled 2D array

Body:
I'm trying to finish this magic square project but when filling the square its referring to the empty instance variable rather than the one with a defined size and I can't seem to fix it.

It says null error at line 22.

Can anyone help me with this?

public class MagicSquare {
    private int[][] magicSquare;

    public MagicSquare(int size){
        int[][] magicSquare = new int[size][size];
        fillSquare(size);
    }
    private void fillSquare(int size){
        int row = size - 1;
        int col = size / 2;
        magicSquare[row][col] = 1;

        for (int i = 2;i < size * size;++i){
            if (magicSquare[(1 + row) % size][(col + 1) % size] == 0){
                row = (1 + row) % size;
                col = (1 + col) % size;
            }
            else {
                row = ( row - 1 + size) % size;
            }
            magicSquare[row][col] = i;
        }
    }
    public void toString(int size){
        for (int i = 0; i < size;++i){
            for (int j = 0; j < size;++j){
                System.out.println(magicSquare[i][j]);
            }
        }

    }

}

Body:
don't init magicSquare in int[][] magicSquare = new int[size][size];

that over rides the global magicSquare instance ,

your code should look like this:

 public class MagicSquare {
        private int[][] magicSquare;

        public MagicSquare(int size){
            magicSquare = new int[size][size];
            fillSquare(size);
        }
        private void fillSquare(int size){
            int row = size - 1;
            int col = size / 2;
            magicSquare[row][col] = 1;

            for (int i = 2;i < size * size;++i){
                if (magicSquare[(1 + row) % size][(col + 1) % size] == 0){
                    row = (1 + row) % size;
                    col = (1 + col) % size;
                }
                else {
                    row = ( row - 1 + size) % size;
                }
                magicSquare[row][col] = i;
            }
        }
        public void toString(int size){
            for (int i = 0; i < size;++i){
                for (int j = 0; j < size;++j){
                    System.out.println(magicSquare[i][j]);
                }
            }

        }

    }


来源: stackexchange

问:
Downsides to Path('foo').exists() != bool(Path('foo'))
Tried to rephrase my question to be less opinion based.

What are the downsides to pathlib.Path object coerce/evaluate to False when the filesystem path does not exist?

For example pathlib.Path could have been written with any __bool__ logic as it is just a Python class

```<code>class Path(object):
    def __init__(self, path):
        self.path_ = path

    def __bool__(self):
        return self.checkIfExistsOnFileSystemOrNot_()

    def path(self):
        return self.path_

    def checkIfExistsOnFileSystemOrNot_(self):
        # any logic here ...

    ...
</code>```

I understand you might want to build up a filepath that is not "there" in a python program but when would you want to do

```<code>if path:
   # do something with the path "assuming" it exits on the filesystem (and not just that it's not falsy)
</code>```

I'll grant that

```<code>if path.exists():
    # ...
</code>```

Isn't that much more effort but given I've been jumping around between languages this has caused me some pain.

答:
Now that the question has been changed, the last point I made in my original answer is probably the most important: clarity.

The Zen of Python says:

Explicit is better than implicit.

and

Readability counts.

Explicitly calling .exists() on a Path object is very clear. A new programmer, unfamiliar with Python, could read

if some_path.exists():
    # ...
```

<p>and probably understand it. But</p>

<pre class="lang-py prettyprint-override"><code>if some_path:
    # ...
</code>```

is much less clear.

I've been jumping around between languages this has caused me some pain.

Idiomatic Python and idiomatic Ruby or C# or Scala are all different. That's okay.

Now, to the rest of old answer:

pathlib isn't just for representing files and folders on the specific visible filesystem. It's for representing and manipulating paths per se (bold added):

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

You can even manipulate Windows-style paths on Linux systems and vice-versa.

Reducing the truthiness of paths to "does this file exist?" would seem like a strange design decision. Especially when there are other Boolean things that can be asked about files and directories: Is it readable? Writable? Executable? A symbolic link? A directory? A regular file? A FIFO?

ContentLicense: CC BY-SA 4.0

Body:
Tried to rephrase my question to be less opinion based.

What are the downsides to pathlib.Path object coerce/evaluate to False when the filesystem path does not exist?

For example pathlib.Path could have been written with any __bool__ logic as it is just a Python class

class Path(object):
    def __init__(self, path):
        self.path_ = path

    def __bool__(self):
        return self.checkIfExistsOnFileSystemOrNot_()

    def path(self):
        return self.path_

    def checkIfExistsOnFileSystemOrNot_(self):
        # any logic here ...

    ...

I understand you might want to build up a filepath that is not "there" in a python program but when would you want to do

if path:
   # do something with the path "assuming" it exits on the filesystem (and not just that it's not falsy)

I'll grant that

if path.exists():
    # ...

Isn't that much more effort but given I've been jumping around between languages this has caused me some pain.

Body:
Now that the question has been changed, the last point I made in my original answer is probably the most important: clarity.

The Zen of Python says:

Explicit is better than implicit.

and

Readability counts.

Explicitly calling .exists() on a Path object is very clear. A new programmer, unfamiliar with Python, could read

if some_path.exists():
    # ...

and probably understand it. But

if some_path:
    # ...

is much less clear.

I've been jumping around between languages this has caused me some pain.

Idiomatic Python and idiomatic Ruby or C# or Scala are all different. That's okay.

Now, to the rest of old answer:

pathlib isn't just for representing files and folders on the specific visible filesystem. It's for representing and manipulating paths per se (bold added):

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

You can even manipulate Windows-style paths on Linux systems and vice-versa.

Reducing the truthiness of paths to "does this file exist?" would seem like a strange design decision. Especially when there are other Boolean things that can be asked about files and directories: Is it readable? Writable? Executable? A symbolic link? A directory? A regular file? A FIFO?


问:
How can I fetch a single file at at a specific commit (by hash) from a remote git repository?
I'd like to fetch a file at a commit from a remote git repository without fetching all objects in the repository. I know git archive doesn't work as it can only fetch the tip of a branch.

With sparse-checkout and using protocol v2 (thanks @bk2204) I can create a work-tree with only the readme at a commit, but git transmits 10s of thousands of objects and 188mb.

```<code>mkdir linux
cd linux
git init
git config core.sparseCheckout true
git config protocol.version 2
git remote add origin git@github.com:torvalds/linux.git
echo "/README" > .git/info/sparse-checkout
git fetch --depth 1 origin ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7
git checkout ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7
</code>```

```<code>remote: Enumerating objects: 71432, done.
remote: Counting objects: 100% (71432/71432), done.
remote: Compressing objects: 100% (66651/66651), done.
remote: Total 71432 (delta 5277), reused 25451 (delta 3920), pack-reused 0
Receiving objects: 100% (71432/71432), 188.85 MiB | 7.71 MiB/s, done.
Resolving deltas: 100% (5277/5277), done.
</code>```

Ideally this operation should fetch 3 objects
 - the commit (the known sha) > the commit's tree > the file in the tree

```<code>$ git cat-file -p ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7 | grep tree
tree f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8
$ git cat-file -p f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8 | grep README
100644 blob 669ac7c32292798644b21dbb5a0dc657125f444d    README
$ git cat-file -p 669ac7c32292798644b21dbb5a0dc657125f444d
</code>```

答:
In general, you cannot fetch individual objects without partial clone support.  The protocol doesn't allow it.  Sparse checkout doesn't prevent you from fetching all of the data, it just prevents you from checking it all out.

I'm not aware of any major Git hosting providers that have generally available partial clone support right now, although I suspect it will be coming soon.  The feature is still relatively experimental.

However, if you're using a remote that supports protocol v2, you can fetch a specific commit, even if you normally wouldn't be able to without protocol v2.  You can run git config protocol.version 2 and then you'll be able to fetch individual commits by hash.  Doing that with a --depth 1 would be the best you could do in this particular case.

Body:
I'd like to fetch a file at a commit from a remote git repository without fetching all objects in the repository. I know git archive doesn't work as it can only fetch the tip of a branch.

With sparse-checkout and using protocol v2 (thanks @bk2204) I can create a work-tree with only the readme at a commit, but git transmits 10s of thousands of objects and 188mb.

mkdir linux
cd linux
git init
git config core.sparseCheckout true
git config protocol.version 2
git remote add origin git@github.com:torvalds/linux.git
echo "/README" > .git/info/sparse-checkout
git fetch --depth 1 origin ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7
git checkout ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7

remote: Enumerating objects: 71432, done.
remote: Counting objects: 100% (71432/71432), done.
remote: Compressing objects: 100% (66651/66651), done.
remote: Total 71432 (delta 5277), reused 25451 (delta 3920), pack-reused 0
Receiving objects: 100% (71432/71432), 188.85 MiB | 7.71 MiB/s, done.
Resolving deltas: 100% (5277/5277), done.

Ideally this operation should fetch 3 objects
 - the commit (the known sha) > the commit's tree > the file in the tree

$ git cat-file -p ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7 | grep tree
tree f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8
$ git cat-file -p f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8 | grep README
100644 blob 669ac7c32292798644b21dbb5a0dc657125f444d    README
$ git cat-file -p 669ac7c32292798644b21dbb5a0dc657125f444d


问:
How to remove element from an array using reduce?
Trying to filter out object based on some logic below code is returning empty array any help will be appreciated trying to achieve following logic

1- If first Obj (firstFillIndicator=Y, acceptDigitalFirstFill=Y) and Second Object(firstFillIndicator = Y, acceptDigitalFirstFill=N). this object should be removed its falsy.

2- if first obj(firstFillIndicator=Y, acceptDigitalFirstFill=Y) and seond object (firstFillIndicator= N, acceptDigitalFirstFill=Y).  this object should be removed its falsy.

3- if both objects have firstFillIndicator and acceptDigitalFirstFill have some values that would be truthy.

main.ts

```<code>function validateSingleOrder(data){
  let isValid = false;
  const filteredDrugs = data.filter((item) => {
      isValid = isValidOrder(item);
      if(isValid){
        return true;
      } else {
        return false;
      }
  })

 return filteredDrugs;
}

function isValidOrder(item){
   item.rxInfos.reduce((a, c) => {
    return (a.acceptDigitalFirstFill === "Y" && c.firstFillIndicator === "Y") || (a.firstFillIndicator === "N" && c.acceptDigitalFirstFill === "N")
  });
}

console.log(validateSingleOrder(rxDetails));
</code>```

data

```<code> const rxDetails = [
      {
            indexID: 1,
            rxInfos: [{
                    firstFillIndicator: "Y",
                    acceptDigitalFirstFill: "Y",
                    rxNumber: "1512"
                },
                {
                    firstFillIndicator: "Y",
                    acceptDigitalFirstFill: "N",
                    rxNumber: "16021"

                }
            ]
      },
      {
          indexID: 2,
          rxInfos: [{
                  firstFillIndicator: "Y",
                  acceptDigitalFirstFill: "Y",
                  rxNumber: "1512"
              },
              {
                  firstFillIndicator: "N",
                  acceptDigitalFirstFill: "Y",
                  rxNumber: "16021"

              }
          ]
      },
      {
          indexID: 3,
          rxInfos: [{
                  firstFillIndicator: "Y",
                  acceptDigitalFirstFill: "Y",
                  rxNumber: "1512"
              },
              {
                  firstFillIndicator: "N",
                  acceptDigitalFirstFill: "N",
                  rxNumber: "16021"

              }
          ]
      }
    ]
</code>```

expected result

```<code>[{
        indexID: 3
        rxInfoss: [{
                firstFillIndicator: "Y",
                acceptDigitalFirstFill: "Y",
                rxNumber: "1512"
            },
            {
                firstFillIndicator: "N",
                acceptDigitalFirstFill: "N",
                rxNumber: "16021"

            }
        ]
    },

];
</code>```

答:
The problem is that the isValidOrder function doesn't return anything, in any case, using something like .every(..) is more appropriate then using .reduce(..) in this case, here is an example:

const rxDetails = [{
    indexID: 1,
    rxInfos: [{
        firstFillIndicator: "Y",
        acceptDigitalFirstFill: "Y",
        rxNumber: "1512"
      },
      {
        firstFillIndicator: "Y",
        acceptDigitalFirstFill: "N",
        rxNumber: "16021"

      }
    ]
  },
  {
    indexID: 2,
    rxInfos: [{
        firstFillIndicator: "Y",
        acceptDigitalFirstFill: "Y",
        rxNumber: "1512"
      },
      {
        firstFillIndicator: "N",
        acceptDigitalFirstFill: "Y",
        rxNumber: "16021"

      }
    ]
  },
  {
    indexID: 3,
    rxInfos: [{
        firstFillIndicator: "Y",
        acceptDigitalFirstFill: "Y",
        rxNumber: "1512"
      },
      {
        firstFillIndicator: "N",
        acceptDigitalFirstFill: "N",
        rxNumber: "16021"

      }
    ]
  }
];

const result = rxDetails.filter(o => {
  return o.rxInfos.every(v => {
    return (v.firstFillIndicator === 'Y' && v.acceptDigitalFirstFill === 'Y') || (v.firstFillIndicator === 'N' && v.acceptDigitalFirstFill === 'N');
  });
});

console.log(result);```

Body:
Trying to filter out object based on some logic below code is returning empty array any help will be appreciated trying to achieve following logic

1- If first Obj (firstFillIndicator=Y, acceptDigitalFirstFill=Y) and Second Object(firstFillIndicator = Y, acceptDigitalFirstFill=N). this object should be removed its falsy.

2- if first obj(firstFillIndicator=Y, acceptDigitalFirstFill=Y) and seond object (firstFillIndicator= N, acceptDigitalFirstFill=Y).  this object should be removed its falsy.

3- if both objects have firstFillIndicator and acceptDigitalFirstFill have some values that would be truthy.

main.ts

function validateSingleOrder(data){
  let isValid = false;
  const filteredDrugs = data.filter((item) => {
      isValid = isValidOrder(item);
      if(isValid){
        return true;
      } else {
        return false;
      }
  })

 return filteredDrugs;
}

function isValidOrder(item){
   item.rxInfos.reduce((a, c) => {
    return (a.acceptDigitalFirstFill === "Y" && c.firstFillIndicator === "Y") || (a.firstFillIndicator === "N" && c.acceptDigitalFirstFill === "N")
  });
}

console.log(validateSingleOrder(rxDetails));

data

 const rxDetails = [
      {
            indexID: 1,
            rxInfos: [{
                    firstFillIndicator: "Y",
                    acceptDigitalFirstFill: "Y",
                    rxNumber: "1512"
                },
                {
                    firstFillIndicator: "Y",
                    acceptDigitalFirstFill: "N",
                    rxNumber: "16021"

                }
            ]
      },
      {
          indexID: 2,
          rxInfos: [{
                  firstFillIndicator: "Y",
                  acceptDigitalFirstFill: "Y",
                  rxNumber: "1512"
              },
              {
                  firstFillIndicator: "N",
                  acceptDigitalFirstFill: "Y",
                  rxNumber: "16021"

              }
          ]
      },
      {
          indexID: 3,
          rxInfos: [{
                  firstFillIndicator: "Y",
                  acceptDigitalFirstFill: "Y",
                  rxNumber: "1512"
              },
              {
                  firstFillIndicator: "N",
                  acceptDigitalFirstFill: "N",
                  rxNumber: "16021"

              }
          ]
      }
    ]

expected result

[{
        indexID: 3
        rxInfoss: [{
                firstFillIndicator: "Y",
                acceptDigitalFirstFill: "Y",
                rxNumber: "1512"
            },
            {
                firstFillIndicator: "N",
                acceptDigitalFirstFill: "N",
                rxNumber: "16021"

            }
        ]
    },

];


问:
How to read txt file into a Dictionary?
How can I read a text file containing

example:

```<code>qtsdatacenter.aws.edu 128.60.3.2 A

www.ibm.com 64.42.3.4 A

www.google.edu 8.7.45.2 A
</code>```

Into a Dictionary like this:

```<code> tsdictionary = {   "qtsdatacenter.aws.com" : "qtsdatacenter.aws.edu 128.60.3.2 A",
                     "www.ibm.com" : "www.ibm.com 64.42.3.4 A",
                     "www.google.edu" : "www.google.edu 8.7.45.2 A"
                }
</code>```

Where the first string read before a space also becomes the key.

答:
```<code>rsdictionary = {}
with open("PROJI-DNSRS.txt") as f:
    for line in f:
        (key, val) = line.strip().split(" ", 1)
        rsdictionary[key] = "{} {}".format(key, val)
</code>```

Title: How to read txt file into a Dictionary?

Body:
How can I read a text file containing

example:

qtsdatacenter.aws.edu 128.60.3.2 A

www.ibm.com 64.42.3.4 A

www.google.edu 8.7.45.2 A

Into a Dictionary like this:

 tsdictionary = {   "qtsdatacenter.aws.com" : "qtsdatacenter.aws.edu 128.60.3.2 A",
                     "www.ibm.com" : "www.ibm.com 64.42.3.4 A",
                     "www.google.edu" : "www.google.edu 8.7.45.2 A"
                }

Where the first string read before a space also becomes the key.


答:
You can achieve something like this with the following:

my_dict = dict()

with open("data.txt") as data:
  for line in data:
    site , *_= line.strip().split(" ", 1)
    if site:
      my_dict[site] = line.strip()

print(my_dict)
```

Title: How to read txt file into a Dictionary?


问:
Spring-Hibernate Template - Is it possible to search a user in the DB by username (one of the properties) instead of by id (primary key)?
I am trying to find a user in the DB by username instead of ID (which works fine). But everything I tried I couldn't get it to work. here is the code

employee.hbm.xml

```<code><?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="co.edureka.Employee" table="emp1">
        <cache usage="read-only" />
        <id name="empno" column="empno">
            <generator class="assigned" />
        </id>
        <property name="ename" />
        <property name="basic" />
        <property name="hra" />
        <property name="da" />
        <property name="deduction" />
    </class>
</hibernate-mapping>
</code>```

ApplicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:annotation-config/>

    <!-- Initiate driver -->
    <bean id="ds"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"
            value="com.mysql.cj.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/edureka" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="mysessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="ds"></property>
    <property name="mappingResources">
    <list>
        <value>employee.hbm.xml</value>
    </list>
    </property>

        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
        </property>
    </bean>

    <bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="mysessionFactory"></property>
    </bean>

    <bean id="empdao" class="co.edureka.EmployeeDAO">
        <property name="template" ref="template" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mysessionFactory"/>
    </bean>

</beans>

</code>```

Employee.java

```<code>package co.edureka;

public class Employee {
    private int empno;
    private String ename;
    private int basic, hra, da, deduction;

    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Employee(int empno, String ename, int basic, int hra, int da, int deduction) {
        super();
        this.empno = empno;
        this.ename = ename;
        this.basic = basic;
        this.hra = hra;
        this.da = da;
        this.deduction = deduction;
    }

    public int getEmpno() {
        return empno;
    }
    public void setEmpno(int empno) {
        this.empno = empno;
    }
    public int getBasic() {
        return basic;
    }
    public void setBasic(int basic) {
        this.basic = basic;
    }
    public int getHra() {
        return hra;
    }
    public void setHra(int hra) {
        this.hra = hra;
    }
    public int getDa() {
        return da;
    }
    public void setDa(int da) {
        this.da = da;
    }
    public int getDeduction() {
        return deduction;
    }
    public void setDeduction(int deduction) {
        this.deduction = deduction;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }

    @Override
    public String toString() {
        return "Employee [empno=" + empno + ", ename=" + ename +", basic=" + basic + ", hra=" + hra + ", da=" + da + ", deduction="
                + deduction + "]";
    }
}
</code>```

Employee.DAO

```<code>package co.edureka;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

public class EmployeeDAO {

    private HibernateTemplate template;

    public HibernateTemplate getTemplate() {
        return template;
    }

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    @Transactional(readOnly = false)
    public void saveEmployee(Employee emp) {
    template.save(emp);
    }

    @Transactional(readOnly = false)
    public void updateEmployee(Employee emp) {
    template.update(emp);
    }

    @Transactional(readOnly = false)
    public void deleteEmployee(Employee emp) {
    template.delete(emp);

    }

    public Employee getByEmpno(int empno) {
        Employee emp = (Employee)template.get(Employee.class, empno);
        return emp;
    }

    public List<Employee> getEmployees(){
        List<Employee> list = new ArrayList<Employee>();
        list = template.loadAll(Employee.class);
        return list;
    }
}
</code>```

Main.java

```<code>package co.edureka;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        EmployeeDAO dao = (EmployeeDAO)context.getBean("empdao");

        //Employee emp2 = new Employee(105, "daddio Papo",75000, 15000, 18000, 5000 );
        //dao.saveEmployee(emp2);

        Employee emp4 =(Employee)dao.getByEmpno(101);
        System.out.println(emp4);

        List<Employee> emps = dao.getEmployees();
        for(Employee semp : emps) {
            System.out.println(semp);
        }
}
}
</code>```

I tried adding this method in the employeeDAO to get the employee by name but it doesnt seem to work

```<code>public Employee getByEname(String ename) {
        Employee emp = (Employee)template.find("FROM emp1 WHERE ename = '"+ename+"'"); // this is not working
        return emp;
    }
</code>```

and this in the main.java

```<code>Employee emp3 =(Employee)dao.getByEname("Adrianne");
        System.out.println(emp3);
</code>```

I get the following stacktrace error

```<code>Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: emp1 is not mapped [FROM emp1 WHERE ename = 'Adrianne']
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:722)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:110)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282)
    at org.springframework.orm.hibernate5.HibernateTemplate.lambda$find$30(HibernateTemplate.java:904)
    at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:385)
    at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:351)
    at org.springframework.orm.hibernate5.HibernateTemplate.find(HibernateTemplate.java:902)
    at co.edureka.EmployeeDAO.getByEname(EmployeeDAO.java:52)
    at co.edureka.EmployeeDAO$$FastClassBySpringCGLIB$$8fa4cd73.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685)
    at co.edureka.EmployeeDAO$$EnhancerBySpringCGLIB$$df7ce4c0.getByEname(<generated>)
    at co.edureka.Main.main(Main.java:26)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: emp1 is not mapped [FROM emp1 WHERE ename = 'Adrianne']
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:155)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:601)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
    ... 16 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: emp1 is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3704)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3593)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:724)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:580)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:317)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:265)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:272)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192)
    ... 22 more
</code>```

I can easily add and search by the empno (primary key). I can also get the list of all the employees from the DB. So the table is definitely mapped. The method I tried to put together to get by ename is most likely wrong but I am not sure what else to try. Is it even possible to search by ename since it's a property as opposed to the primary key?

Also this is my first time posting, hope what I am asking is clear enough. If not please let me know so I can add it.

答:
```<code>Employee emp = (Employee)template.find("FROM emp1 WHERE ename = '"+ename+"'");
</code>```

emp1 is the table name, you need to specify the entity name here Employee

Try:

```<code> Employee emp = (Employee)template.find("FROM Employee WHERE ename = '"+ename+"'");
</code>```

Body:
I am trying to find a user in the DB by username instead of ID (which works fine). But everything I tried I couldn't get it to work. here is the code

employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="co.edureka.Employee" table="emp1">
        <cache usage="read-only" />
        <id name="empno" column="empno">
            <generator class="assigned" />
        </id>
        <property name="ename" />
        <property name="basic" />
        <property name="hra" />
        <property name="da" />
        <property name="deduction" />
    </class>
</hibernate-mapping>

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:annotation-config/>

    <bean id="ds"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"
            value="com.mysql.cj.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/edureka" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

    <bean id="mysessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="ds"></property>
    <property name="mappingResources">
    <list>
        <value>employee.hbm.xml</value>
    </list>
    </property>

        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
        </property>
    </bean>

    <bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="mysessionFactory"></property>
    </bean>

    <bean id="empdao" class="co.edureka.EmployeeDAO">
        <property name="template" ref="template" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mysessionFactory"/>
    </bean>

</beans>

Employee.java

package co.edureka;

public class Employee {
    private int empno;
    private String ename;
    private int basic, hra, da, deduction;

    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Employee(int empno, String ename, int basic, int hra, int da, int deduction) {
        super();
        this.empno = empno;
        this.ename = ename;
        this.basic = basic;
        this.hra = hra;
        this.da = da;
        this.deduction = deduction;
    }

    public int getEmpno() {
        return empno;
    }
    public void setEmpno(int empno) {
        this.empno = empno;
    }
    public int getBasic() {
        return basic;
    }
    public void setBasic(int basic) {
        this.basic = basic;
    }
    public int getHra() {
        return hra;
    }
    public void setHra(int hra) {
        this.hra = hra;
    }
    public int getDa() {
        return da;
    }
    public void setDa(int da) {
        this.da = da;
    }
    public int getDeduction() {
        return deduction;
    }
    public void setDeduction(int deduction) {
        this.deduction = deduction;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }

    @Override
    public String toString() {
        return "Employee [empno=" + empno + ", ename=" + ename +", basic=" + basic + ", hra=" + hra + ", da=" + da + ", deduction="
                + deduction + "]";
    }
}

Employee.DAO

package co.edureka;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

public class EmployeeDAO {

    private HibernateTemplate template;

    public HibernateTemplate getTemplate() {
        return template;
    }

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    @Transactional(readOnly = false)
    public void saveEmployee(Employee emp) {
    template.save(emp);
    }

    @Transactional(readOnly = false)
    public void updateEmployee(Employee emp) {
    template.update(emp);
    }

    @Transactional(readOnly = false)
    public void deleteEmployee(Employee emp) {
    template.delete(emp);

    }

    public Employee getByEmpno(int empno) {
        Employee emp = (Employee)template.get(Employee.class, empno);
        return emp;
    }

    public List<Employee> getEmployees(){
        List<Employee> list = new ArrayList<Employee>();
        list = template.loadAll(Employee.class);
        return list;
    }
}

Main.java

package co.edureka;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        EmployeeDAO dao = (EmployeeDAO)context.getBean("empdao");

        //Employee emp2 = new Employee(105, "daddio Papo",75000, 15000, 18000, 5000 );
        //dao.saveEmployee(emp2);

        Employee emp4 =(Employee)dao.getByEmpno(101);
        System.out.println(emp4);

        List<Employee> emps = dao.getEmployees();
        for(Employee semp : emps) {
            System.out.println(semp);
        }
}
}

I tried adding this method in the employeeDAO to get the employee by name but it doesnt seem to work

public Employee getByEname(String ename) {
        Employee emp = (Employee)template.find("FROM emp1 WHERE ename = '"+ename+"'"); // this is not working
        return emp;
    }

and this in the main.java

Employee emp3 =(Employee)dao.getByEname("Adrianne");
        System.out.println(emp3);

I get the following stacktrace error

Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: emp1 is not mapped [FROM emp1 WHERE ename = 'Adrianne']
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:722)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:110)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282)
    at org.springframework.orm.hibernate5.HibernateTemplate.lambda$find$30(HibernateTemplate.java:904)
    at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:385)
    at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:351)
    at org.springframework.orm.hibernate5.HibernateTemplate.find(HibernateTemplate.java:902)
    at co.edureka.EmployeeDAO.getByEname(EmployeeDAO.java:52)
    at co.edureka.EmployeeDAO$$FastClassBySpringCGLIB$$8fa4cd73.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685)
    at co.edureka.EmployeeDAO$$EnhancerBySpringCGLIB$$df7ce4c0.getByEname(<generated>)
    at co.edureka.Main.main(Main.java:26)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: emp1 is not mapped [FROM emp1 WHERE ename = 'Adrianne']
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:155)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:601)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
    ... 16 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: emp1 is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3704)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3593)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:724)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:580)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:317)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:265)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:272)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192)
    ... 22 more

I can easily add and search by the empno (primary key). I can also get the list of all the employees from the DB. So the table is definitely mapped. The method I tried to put together to get by ename is most likely wrong but I am not sure what else to try. Is it even possible to search by ename since it's a property as opposed to the primary key?

Also this is my first time posting, hope what I am asking is clear enough. If not please let me know so I can add it.

Body:
Employee emp = (Employee)template.find("FROM emp1 WHERE ename = '"+ename+"'");

emp1 is the table name, you need to specify the entity name here Employee

Try:

 Employee emp = (Employee)template.find("FROM Employee WHERE ename = '"+ename+"'");


问:
Help with Exception handlin in finally block
I am trying to catch an exception using a try-catch-finally block. i have caught the exception in the catch block and passed it to the finally block using a global exception variable. Doing so, i have handled the exception scenario in the finally block. I know this sounds wierd, but theres a need to do so. Please let me know if there is any coding standard issue with the same. Also if you can suggest something on the same, i will be really obliged.

Thanks.

答: catch is to catch the exception and do any necessary exception handling.  The finally block is there to clean up any left open resources, like file handles, database connections, etc.  This block will most of the time run and therefore is the correct place to do cleanup, but no the handle the exceptions themselves, those should be dealt with in the catch block.

ContentLicense: CC BY-SA 3.0


答:
There are probably cleaner solutions but this should work and be flexible...

1.Minimal reproducible example:

```<code>df <- data.frame(Date = c(20121029,20121029, 20121029, 20121029, 20121029, 20121029, 20121029),
                 Time = c(400, 500, 600, 700, 800, 900, 1000),
                 stringsAsFactors = FALSE)

'data.frame':   7 obs. of  2 variables:
$ Date         : int  20121029 20121029 20121029 20121029 20121029 20121029 20121029
$ Time         : int  400 500 600 700 800 900 1000
</code>```

2.Solution with helper function and strptime:

```<code>leftPad <- function(x) {
  len <- 4
  s <- sapply(sapply(x, function(y) paste0("0000", y)),
    function(z) substr(z, nchar(z) - len + 1, nchar(z)))

  return(as.character(s))
}
</code>```

leftPad can then be used to format Time for strptime(We can change the timezone with the tz argument

```<code>strptime(paste0(df$Date, " ", leftPad(df$Time)), format = "%Y%m%d %H%M", tz="UTC")
</code>```

This returns:

```<code>[1] "2012-10-29 04:00:00 UTC" "2012-10-29 05:00:00 UTC"
[3] "2012-10-29 06:00:00 UTC" "2012-10-29 07:00:00 UTC"
[5] "2012-10-29 08:00:00 UTC" "2012-10-29 09:00:00 UTC"
[7] "2012-10-29 10:00:00 UTC"
</code>```

Title: combine two column into one - Date and Time Column with changing their format

Body:
Structure of Data

str(noaaData)

'data.frame':   92 obs. of  3 variables:
 $ Date         : int  20121029 20121029 20121029 20121029 20121029 20121029 20121029 20121029 20121029 20121029 ...
 $ Time         : int  100 200 300 400 500 600 700 800 900 1000 ...
 $ AtmosPressure: num  999 999 998 998 997 ...

I need to combine Date & Time in one column with name "DateTime" by changing them into POSIXct format "%Y-%m-%d %H:%M:%OS"

It should look like this

2012-10-29 01:00:00

minimal reproducible

dput(noaaData)

structure(list(Date = c(20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121029L, 20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121029L, 20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121029L, 20121029L, 20121029L, 20121029L, 20121029L,
20121029L, 20121030L, 20121030L, 20121030L, 20121030L, 20121030L,
20121030L, 20121030L, 20121030L, 20121030L, 20121030L, 20121030L,
20121030L, 20121030L, 20121030L, 20121030L, 20121030L, 20121030L,
20121030L, 20121030L, 20121030L, 20121030L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121031L, 20121031L,
20121031L, 20121031L, 20121031L, 20121031L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L, 20121101L, 20121101L,
20121101L, 20121101L, 20121101L, 20121101L), Time = structure(c(8640000,
17280000, 25920000, 34560000, 43200000, 51840000, 60480000, 69120000,
77760000, 86400000, 95040000, 103680000, 112320000, 120960000,
129600000, 138240000, 146880000, 155520000, 164160000, 172800000,
181440000, 190080000, 198720000, 25920000, 34560000, 43200000,
51840000, 60480000, 69120000, 77760000, 86400000, 95040000, 103680000,
112320000, 120960000, 129600000, 138240000, 146880000, 155520000,
164160000, 172800000, 181440000, 190080000, 198720000, 0, 8640000,
17280000, 25920000, 34560000, 43200000, 51840000, 60480000, 69120000,
77760000, 86400000, 95040000, 103680000, 112320000, 120960000,
129600000, 138240000, 146880000, 155520000, 164160000, 172800000,
181440000, 190080000, 198720000, 0, 8640000, 17280000, 25920000,
34560000, 43200000, 51840000, 60480000, 69120000, 77760000, 86400000,
95040000, 103680000, 112320000, 120960000, 129600000, 138240000,
146880000, 155520000, 164160000, 172800000, 181440000, 190080000,
198720000), class = c("POSIXct", "POSIXt")), AtmosPressure = c(999.2,
999.2, 998.3, 997.9, 996.7, 995.4, 994.4, 992, 990.2, 988.4,
987.1, 985.9, 984, 981.5, 978.8, 975.3, 971.4, 966.3, 961.9,
956.1, 951.4, 949.7, 946.3, 968, 972.9, 976.5, 979.4, 981.2,
982.5, 983.7, 985, 986.2, 987.5, 988.9, 990.1, 991, 992, 992.6,
993, 993.4, 994.1, 994.6, 995.4, 996, 996.6, 997, 997.1, 997.3,
997.3, 997.4, 997.2, 997.2, 997.5, 997.8, 998.3, 998.6, 999,
999.8, 1000, 1000.1, 1000.2, 999.7, 999.5, 999.1, 999.5, 1000,
1000.4, 1001.1, 1001.3, 1001.6, 1001.7, 1001.8, 1001.7, 1001.7,
1001.7, 1002, 1001.9, 1001.9, 1002.1, 1002, 1002.5, 1002.9, 1003.1,
1003, 1003.1, 1002.5, 1002.1, 1001.8, 1001.9, 1001.9, 1002.2,
1002.9)), row.names = c(NA, -92L), class = "data.frame")

I request someone to please help me in this.

Body:
There are probably cleaner solutions but this should work and be flexible...

1.Minimal reproducible example:

df <- data.frame(Date = c(20121029,20121029, 20121029, 20121029, 20121029, 20121029, 20121029),
                 Time = c(400, 500, 600, 700, 800, 900, 1000),
                 stringsAsFactors = FALSE)

'data.frame':   7 obs. of  2 variables:
$ Date         : int  20121029 20121029 20121029 20121029 20121029 20121029 20121029
$ Time         : int  400 500 600 700 800 900 1000

2.Solution with helper function and strptime:

leftPad <- function(x) {
  len <- 4
  s <- sapply(sapply(x, function(y) paste0("0000", y)),
    function(z) substr(z, nchar(z) - len + 1, nchar(z)))

  return(as.character(s))
}

leftPad can then be used to format Time for strptime(We can change the timezone with the tz argument

strptime(paste0(df$Date, " ", leftPad(df$Time)), format = "%Y%m%d %H%M", tz="UTC")

This returns:

[1] "2012-10-29 04:00:00 UTC" "2012-10-29 05:00:00 UTC"
[3] "2012-10-29 06:00:00 UTC" "2012-10-29 07:00:00 UTC"
[5] "2012-10-29 08:00:00 UTC" "2012-10-29 09:00:00 UTC"
[7] "2012-10-29 10:00:00 UTC"


问:
WSO2 ESB: Unable to load DB connection properties from registry
I have a car file named basic.car. This has a registry project named basicRegistry. I have created localentry type registry resource in this project, and named it DB_DRIVER and gave its value as "org.postgresql.Driver" in gov(also tried the same for conf)

Now in dblookup mediator properties, I chose "registry based driver config" and entered the value as

But when the car is deployed it shows the below error.

[2020-02-17 16:41:03,277] ERROR {org.apache.synapse.mediators.db.DBLookupMediator} - Error DB Mediator datasource: null.Registry entry defined with key: gov:dbconfig/DB_DRIVER not found.

What am I doing wrong?

答:
To further analyze could you please provide the following information

ESB version

Synapse configurations related to DB lookup mediator

Do you deploy the DBLookup mediator in a separate car file?

The car files are deployed in alphabetical order. If the registry resources and the DBlookup mediator configurations are deployed by two different car files make sure that registry resources are deployed prior to the synapse artifacts


问:
Debian libsll conflict
I would like to install Viber under Debian 10.2

```<code>dpkg: dependency problems prevent configuration of viber:
 viber depends on libssl1.0.0; however:
  Package libssl1.0.0 is not installed.
</code>```

The actual version installed is 1.1.1

```<code># apt-cache policy libssl1.1
libssl1.1:
  Installed: 1.1.1d-0+deb10u2
  Candidate: 1.1.1d-0+deb10u2
  Version table:
 *** 1.1.1d-0+deb10u2 500
</code>```

I tried to fix it by the following command

```<code># apt-get install libssl1.0.0=1.1.1d-0+deb10u2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Version '1.1.1d-0+deb10u2' for 'libssl1.0.0' was not found
</code>```

Thanks for help.

答:
You can get the libssl1.0.0 package from http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u12_amd64.deb.
If you are using Debian 10 64-bit, you will also have to install the multiarch-support package - you can get it from the Debian repo.
Let me know if the following sequence of commands works for you:</p>

```<code>sudo apt -y install multiarch-support wget
wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u12_amd64.deb
sudo dpkg -i libssl1.0.0_1.0.1t-1+deb8u12_amd64.deb
wget https://download.cdn.viber.com/cdn/desktop/Linux/viber.deb
sudo dpkg -i viber.deb
</code>```

Title: Debian libsll conflict

Body:
I would like to install Viber under Debian 10.2

dpkg: dependency problems prevent configuration of viber:
 viber depends on libssl1.0.0; however:
  Package libssl1.0.0 is not installed.

The actual version installed is 1.1.1

# apt-cache policy libssl1.1
libssl1.1:
  Installed: 1.1.1d-0+deb10u2
  Candidate: 1.1.1d-0+deb10u2
  Version table:
 *** 1.1.1d-0+deb10u2 500

I tried to fix it by the following command

# apt-get install libssl1.0.0=1.1.1d-0+deb10u2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Version '1.1.1d-0+deb10u2' for 'libssl1.0.0' was not found

Thanks for help.

Body:
You can get the libssl1.0.0 package from http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u12_amd64.deb.
If you are using Debian 10 64-bit, you will also have to install the multiarch-support package - you can get it from the Debian repo.
Let me know if the following sequence of commands works for you:

sudo apt -y install multiarch-support wget
wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u12_amd64.deb
sudo dpkg -i libssl1.0.0_1.0.1t-1+deb8u12_amd64.deb
wget https://download.cdn.viber.com/cdn/desktop/Linux/viber.deb
sudo dpkg -i viber.deb


问:
construction of a data model on cassandra / CQL
I have a vehicle tracking table that contains the following fields: vehicle_id, id tracking, time_tracking, longitude, latitude. How to build the table so that I can have the latest tracking of all vehicles according to time_tracking. How to build the table also to have the last tracking of a vehicle also according to time_tracking. Thank you in advance.

答:
Based on the columns specified you can try the below schema.

CREATE TABLE IF NOT EXISTS vehicle_details (time_tracking timestamp,
                                      vehicle_id int,
                                      id int,
                                      latitude varchar,
                                      longitude varchar,
                                      PRIMARY KEY ((time_tracking), vehicle_id)
                                      )WITH CLUSTERING ORDER BY (time_tracking DESC);
```

Since you are storing in a CLUSTERING ORDER of DESC, it will always be very easy to get the latest records, you need to add 'LIMIT' to your query,

Ex: select * from vehicle_details where time_tracking=20200101 limit 10;

You can run a select query based on time_tracking and can add vehicle_id to get the details of vehicle for a particular timestamp.

Ex: select * from vehicle_details where time_tracking=20200101 and vehicle_id = 122 limit 10;

Hope this helps.

Body:
Based on the columns specified you can try the below schema.

CREATE TABLE IF NOT EXISTS vehicle_details (time_tracking timestamp,
                                      vehicle_id int,
                                      id int,
                                      latitude varchar,
                                      longitude varchar,
                                      PRIMARY KEY ((time_tracking), vehicle_id)
                                      )WITH CLUSTERING ORDER BY (time_tracking DESC);

Since you are storing in a CLUSTERING ORDER of DESC, it will always be very easy to get the latest records, you need to add 'LIMIT' to your query,

Ex: select * from vehicle_details where time_tracking=20200101 limit 10;

You can run a select query based on time_tracking and can add vehicle_id to get the details of vehicle for a particular timestamp.

Ex: select * from vehicle_details where time_tracking=20200101 and vehicle_id = 122 limit 10;

Hope this helps.


问:
shell script which opens python with arguments to python script
I want to debug some Python code in PyCharm but the repository I got the code from uses a shell script of the form

```<code>python main.py arg1 ... argN
</code>```

which is run from the command line. The main.py module in turn has a if __name__ == '__main__': part which uses argparse to parse the arguments passed via the script.

How can I write a Python script which also calls the main of main.py without touching main.py?

答:
You don't need a script for that. You can Edit Run Configurations in Pycharm to emulate command line arguments passed to the script.

Follow these steps:

Open Edit Configurations...:

Make sure you edit the configuration of your main.py:

Then, simply add the command line arguments, just as you would in the command line, under the parameters field:

Press OK

Run regularly using the green arrow (or right-click and Run)

If you actually have that shell script, you can run it directly by adding a new configuration. On the Configurations window press the + on the top-left corner and choose Shell Script. Indicate the path and any option you want to pass and run.

Body:
I want to debug some Python code in PyCharm but the repository I got the code from uses a shell script of the form

python main.py arg1 ... argN

which is run from the command line. The main.py module in turn has a if __name__ == '__main__': part which uses argparse to parse the arguments passed via the script.

How can I write a Python script which also calls the main of main.py without touching main.py?


问:
How to use Typescript class in Nodejs REPL?
I created a foo.ts like this:

```<code>class Foo{
    public echo(){
    console.log("foo");
    }
}
</code>```

And it outputs javascript code like this:

```<code>var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.echo = function () {
        console.log("foo");
    };
    return Foo;
})();
</code>```

I want to call echo function in nodejs REPL, but it ends up a error like this:

```<code>$ node
> require('./foo.js');
{}
> f = new Foo
ReferenceError: Foo is not defined
    at repl:1:10
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)
</code>```

How can I instantiate the class and call the function echo?

答:
Update for modern times: You can use ES modules easily thanks to esm:

```<code>export class Foo{
    public echo(){
        console.log("foo");
    }
}
</code>```

In the REPL:

```<code>$ node -r esm
> import { Foo } from './foo.js';
{}
> f = new Foo();
</code>```

Body:
I created a foo.ts like this:

class Foo{
    public echo(){
    console.log("foo");
    }
}

And it outputs javascript code like this:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.echo = function () {
        console.log("foo");
    };
    return Foo;
})();

I want to call echo function in nodejs REPL, but it ends up a error like this:

$ node
> require('./foo.js');
{}
> f = new Foo
ReferenceError: Foo is not defined
    at repl:1:10
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)

How can I instantiate the class and call the function echo?

Body:
Update for modern times: You can use ES modules easily thanks to esm:

export class Foo{
    public echo(){
        console.log("foo");
    }
}

In the REPL:

$ node -r esm
> import { Foo } from './foo.js';
{}
> f = new Foo();


问:
Ho to get key.pem from a couple of .cert files
I have two files bx.crt and CA.crt. How do I get a key.pem from them? Both files are binary.

答: If those are certificate files, then you can't.  Certificate files don't contain a private key, only the public key.  You will need to "find" the private key file that generated the certificate request.</p>


问:
Pass JS foreach to JS post without form
totalforms[i] is reading all inputs from page (dynamically generated) (eg: <input name="test" type="text">)
I want to send all inputs (get from foreach in JS array) to https://example.com/client_area?add_to_cart<?php echo $product_id; ?>.

Function to post data (JS):

```<code>function post(path, params, method='post') {

              const form = document.createElement('form');
              form.method = method;
              form.action = path;

              for (const key in params) {
                if (params.hasOwnProperty(key)) {
                  const hiddenField = document.createElement('input');
                  hiddenField.type = 'hidden';
                  hiddenField.name = key;
                  hiddenField.value = params[key];

                  form.appendChild(hiddenField);
                }
              }

              document.body.appendChild(form);
              form.submit();
            }
</code>```

Function to run getting of all inputs in page:

```<code>function runToCart() {
      var forms = document.getElementsByTagName("input");
      document.getElementById("addToCart").innerHTML = `Add To Cart   <i class="fas fa-spinner fa-spin"></i>`;
      var totalforms = new Array();
      var totalforms_values = new Array();
      var i;
      for (i = 0; i < forms.length; i++) {
        totalforms.push(forms[i].name);
        totalforms_values.push(forms[i].value);
      }
      post('/client_area?add_to_cart=<?php echo $product; ?>', {names: totalforms, values: totalforms_values});
    }
</code>```

so?
I tried to search, but nothing like that specific found.

P.S: i want to make an array for array like totalforms[number_if_input_name]['value_of_name_of_input']

SOLVED BY ADDING form= attribute in my inputs, no need js anymore here.

答:
Just fill an object with data</p>

```<code>let totalforms = {};
for (i = 0; i < forms.length; i++) {
  totalforms[i] = totalforms[i] || {};
  totalforms[i][forms[i].name] = forms[i].value;
}
</code>```

Title: Pass JS foreach to JS post without form

Body:
totalforms[i] is reading all inputs from page (dynamically generated) (eg: <input name="test" type="text">)
I want to send all inputs (get from foreach in JS array) to https://example.com/client_area?add_to_cart<?php echo $product_id; ?>.

Function to post data (JS):

function post(path, params, method='post') {

              const form = document.createElement('form');
              form.method = method;
              form.action = path;

              for (const key in params) {
                if (params.hasOwnProperty(key)) {
                  const hiddenField = document.createElement('input');
                  hiddenField.type = 'hidden';
                  hiddenField.name = key;
                  hiddenField.value = params[key];

                  form.appendChild(hiddenField);
                }
              }

              document.body.appendChild(form);
              form.submit();
            }

Function to run getting of all inputs in page:

function runToCart() {
      var forms = document.getElementsByTagName("input");
      document.getElementById("addToCart").innerHTML = `Add To Cart   <i class="fas fa-spinner fa-spin"></i>`;
      var totalforms = new Array();
      var totalforms_values = new Array();
      var i;
      for (i = 0; i < forms.length; i++) {
        totalforms.push(forms[i].name);
        totalforms_values.push(forms[i].value);
      }
      post('/client_area?add_to_cart=<?php echo $product; ?>', {names: totalforms, values: totalforms_values});
    }

so?
I tried to search, but nothing like that specific found.

P.S: i want to make an array for array like totalforms[number_if_input_name]['value_of_name_of_input']

SOLVED BY ADDING form= attribute in my inputs, no need js anymore here.

Body:
Just fill an object with data

let totalforms = {};
for (i = 0; i < forms.length; i++) {
  totalforms[i] = totalforms[i] || {};
  totalforms[i][forms[i].name] = forms[i].value;
}


问:
where and how to put a picture closing button in my html page
I am stuck. I have a site where people can check my lists, and can click on a code and see a larger picture in a window that opens after. I'd like this larger picture to have a closing option (an "X") somewhere up right. And can not find the place in my HTML page to do it.

Is there anyone who can help me?

Thanks! Tomas http://www.patentesantiguas.com.ar/galeria/repetidas.html

答:
Your site is really interesting. Is it vintage license plates? What I can recommend is to link to another html page instead of a jpeg image and open in new tab (target="_blank"). Also append the image name to url so that you can get image file name into javascript variable.

```<code><a target="_blank" href="yourimageviewer.html?currentimage=yourlicenseplateimagenamehere.jpg">
</code>```

After the html link to the new page use a question mark to pass in the variable of the image you want to display.

On the target page ("yourimageviewer.html") you can use javascript to get the image name variable and display on the page with the x to close it. Since the filename is a variable you only have to put in the links for all of the different files instead of creating a viewer for each page.

```<code><!DOCTYPE html>
    <html>
    <head>

    </head>
    <body>
        <button onclick="closeWindow()">X</button>
        <img id="currImage" src="defaultImage.jpg"  height="100%" width="100%">

       <script>
        <!--BELOW GETS VARIABLE FROM URL-->

 function getPictureName() {
            var pictures = {};
            var urlVariables = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                pictures[key] = value;
            });
            return pictures;
        }

        var image = getPictureName()["currentimage"];
        var path = "yourimagepath/"
        document.getElementById('currImage').src = path + image;

        function closeWindow() {
          window.close();
        }

        </script>

    </body>
    </html>
</code>```

Body:
Your site is really interesting. Is it vintage license plates? What I can recommend is to link to another html page instead of a jpeg image and open in new tab (target="_blank"). Also append the image name to url so that you can get image file name into javascript variable.

<a target="_blank" href="yourimageviewer.html?currentimage=yourlicenseplateimagenamehere.jpg">

After the html link to the new page use a question mark to pass in the variable of the image you want to display.

On the target page ("yourimageviewer.html") you can use javascript to get the image name variable and display on the page with the x to close it. Since the filename is a variable you only have to put in the links for all of the different files instead of creating a viewer for each page.

<!DOCTYPE html>
    <html>
    <head>

    </head>
    <body>
        <button onclick="closeWindow()">X</button>
        <img id="currImage" src="defaultImage.jpg"  height="100%" width="100%">

       <script>
        <!--BELOW GETS VARIABLE FROM URL-->

 function getPictureName() {
            var pictures = {};
            var urlVariables = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                pictures[key] = value;
            });
            return pictures;
        }

        var image = getPictureName()["currentimage"];
        var path = "yourimagepath/"
        document.getElementById('currImage').src = path + image;

        function closeWindow() {
          window.close();
        }

        </script>

    </body>
    </html>


问:
how to use SymPy or other library to have a numerical solution
I was trying to solve two equations for two unknown symbols 'Diff' and 'OHs'. the equations are shown below

```<code>x = (8.67839580228369e-26*Diff + 7.245e-10*OHs**3 +
1.24402291559836e-10*OHs**2 + OHs*(-2.38073807380738e-19*Diff -
2.8607855978291e-18) - 1.01141409254177e-29)

J= (-0.00435840284294195*Diff**0.666666666666667*(1 +
3.64525434266056e-7/OHs) - 1)

solution = sym.nsolve ((x, J), (OHs, Diff), (0.000001, 0.000001))
print (solution)
</code>```

is this the correct way to solve for the two unknowns?

Thanks for your help :)

答:
Note: I edited your equation per Vialfont's comments.

I would say it is a possible way but you could do better by noticing that the J equation can be solved easily for OHs and substituted into the x equation. This will then be much easier for nsolve to solve:

```<code>>>> osol = solve(J, OHs)[0]  # there is only one solution
>>> eq = x.subs(OHs,osol)
>>> dsol = nsolve(eq, 1e-5)
>>> eq.subs(Diff,dsol) # verify
4.20389539297445e-45
>>> osol.subs(Diff,dsol), dsol
(-2.08893263437131e-12, 4.76768525775849e-5)
</code>```

But this is still pretty ill behaved in terms of scaling...proceed with caution. And I would suggest writing Diff**Rational(2,3) instead of Diff**0.666666666666667. Or better, then let Diff be y**3 so you are working with a polynomial in y.

```<code>>>> y = var('y', postive=True)
>>> yx=x.subs(Diff,y**3)
>>> yJ=J.subs(Diff,y**3)
>>> yosol=solve(yJ,OHs)[0]
>>> yeq = yx.subs(OHs, yosol)
</code>```

Now, the solutions of eq will be where its numerator is zero so find the real roots of that:

```<code>>>> ysol = real_roots(yeq.as_numer_denom()[0])
>>> len(ysol)
1
>>> ysol[0].n()
0.0362606728976173
>>> yosol.subs(y,_)
-2.08893263437131e-12
</code>```

That is consistent with our previous solution, and this time the solutions in ysol were exact (given the limitations of the coefficients). So if your OHs solution should be positive, check your numbers and equations.

Body:
I was trying to solve two equations for two unknown symbols 'Diff' and 'OHs'. the equations are shown below

x = (8.67839580228369e-26*Diff + 7.245e-10*OHs**3 +
1.24402291559836e-10*OHs**2 + OHs*(-2.38073807380738e-19*Diff -
2.8607855978291e-18) - 1.01141409254177e-29)

J= (-0.00435840284294195*Diff**0.666666666666667*(1 +
3.64525434266056e-7/OHs) - 1)

solution = sym.nsolve ((x, J), (OHs, Diff), (0.000001, 0.000001))
print (solution)

is this the correct way to solve for the two unknowns?

Thanks for your help :)

Body:
Note: I edited your equation per Vialfont's comments.

I would say it is a possible way but you could do better by noticing that the J equation can be solved easily for OHs and substituted into the x equation. This will then be much easier for nsolve to solve:

>>> osol = solve(J, OHs)[0]  # there is only one solution
>>> eq = x.subs(OHs,osol)
>>> dsol = nsolve(eq, 1e-5)
>>> eq.subs(Diff,dsol) # verify
4.20389539297445e-45
>>> osol.subs(Diff,dsol), dsol
(-2.08893263437131e-12, 4.76768525775849e-5)

But this is still pretty ill behaved in terms of scaling...proceed with caution. And I would suggest writing Diff**Rational(2,3) instead of Diff**0.666666666666667. Or better, then let Diff be y**3 so you are working with a polynomial in y.

>>> y = var('y', postive=True)
>>> yx=x.subs(Diff,y**3)
>>> yJ=J.subs(Diff,y**3)
>>> yosol=solve(yJ,OHs)[0]
>>> yeq = yx.subs(OHs, yosol)

Now, the solutions of eq will be where its numerator is zero so find the real roots of that:

>>> ysol = real_roots(yeq.as_numer_denom()[0])
>>> len(ysol)
1
>>> ysol[0].n()
0.0362606728976173
>>> yosol.subs(y,_)
-2.08893263437131e-12

That is consistent with our previous solution, and this time the solutions in ysol were exact (given the limitations of the coefficients). So if your OHs solution should be positive, check your numbers and equations.


问:
using h3 properly since it's a sensitive tag
So imagine i have the following scenario:

```<code><h3 className="service-card__body__title">
    <Icon name={service.icon} size="xl" />
    <span>{service.title}</span>
</h3>
</code>```

Shouldn't this be better?

```<code><span className="service-card__body__title">
  <Icon name={service.icon} size="lg" />
  <span>{service.title}</span>
</span>
</code>```

or

```<code><div className="service-card__body__title">
      <Icon name={service.icon} size="lg" />
      <span>{service.title}</span>
</div>
</code>```

So the h tag is a sensitive tag. Right now the design may no be affected, but if we add other elements to the design it could be affected, since you can not place everything inside of a h tag.

https://dotnetdaily.net/web-development/tutorials/html-tags-place-a-h1-tag

答:
Is it a sub-sub-heading? then use an h3. If you feel the need to add an element that isn't allowed in an h3 then it probably isn't part of the heading (so either you don't have a heading, or the additional element should appear after it).

(You can't play everything inside a span either).

Don't forget the warning from the CSS specification:

Note. CSS gives so much power to the "class" attribute, that authors could conceivably design their own "document language" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.

Body:
So imagine i have the following scenario:

    <Icon name={service.icon} size="xl" />
    {service.title}

Shouldn't this be better?

  <Icon name={service.icon} size="lg" />
  {service.title}

or

      <Icon name={service.icon} size="lg" />
      {service.title}

So the h tag is a sensitive tag. Right now the design may no be affected, but if we add other elements to the design it could be affected, since you can not place everything inside of a h tag.

https://dotnetdaily.net/web-development/tutorials/html-tags-place-a-h1-tag


问:
Is there an R function for evaluating the pdf for an ARIMA model given data and a parameter set?
I'm unfamiliar with R, but I've been able to write code that estimates parameters for an ARIMA model of whatever order to some data I have in a file. It looks like this:

```<code>data <- read.table("ARMA22-series.csv", sep=" ", header=FALSE, dec=".")
data <- as.ts(data)
arima_results <- arima0(data, order=c(2, 0, 2), include.mean=FALSE)
</code>```

However, I'm interested in evaluating the likelihood function for a certain set of parameter values, rather than just finding the parameters that maximise the likelihood for a given dataset. Is there a function that allows you to just evaluate the probability density of data, given values for the ARIMA parameters?

Thanks in advance!

答:
I don't know why you're using arima0, which is labelled as a preliminary version, and was replaced by arima.

arima fits a specific (S)ARIMA model to your data, with parameters specified through the function arguments order and seasonal. forecast::auto.arima tries to determine the optimal (S)ARIMA model conditional on the data.

The arima output object includes the log-likelihood; for example, consider the USAccDeaths sample data, we can fit the two SARIMA models: SARIMA(0,1,1)(0,1,1) and SARIMA(0,1,0)(0,1,0).

```<code>fit1 <- arima(USAccDeaths, order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1)))
fit2 <- arima(USAccDeaths, order = c(0, 1, 0), seasonal = list(order = c(0, 1, 0)))
</code>```

The arima output object is a list, and the log-likelihood is stored in element loglik:

```<code>fit1$loglik
#[1] -425.44
fit2$loglik
#[1] -435.8443
</code>```

Body:
I'm unfamiliar with R, but I've been able to write code that estimates parameters for an ARIMA model of whatever order to some data I have in a file. It looks like this:

data <- read.table("ARMA22-series.csv", sep=" ", header=FALSE, dec=".")
data <- as.ts(data)
arima_results <- arima0(data, order=c(2, 0, 2), include.mean=FALSE)

However, I'm interested in evaluating the likelihood function for a certain set of parameter values, rather than just finding the parameters that maximise the likelihood for a given dataset. Is there a function that allows you to just evaluate the probability density of data, given values for the ARIMA parameters?

Thanks in advance!

Body:
I don't know why you're using arima0, which is labelled as a preliminary version, and was replaced by arima.

arima fits a specific (S)ARIMA model to your data, with parameters specified through the function arguments order and seasonal. forecast::auto.arima tries to determine the optimal (S)ARIMA model conditional on the data.

The arima output object includes the log-likelihood; for example, consider the USAccDeaths sample data, we can fit the two SARIMA models: SARIMA(0,1,1)(0,1,1) and SARIMA(0,1,0)(0,1,0).

fit1 <- arima(USAccDeaths, order = c(0, 1, 1), seasonal = list(order = c(0, 1, 1)))
fit2 <- arima(USAccDeaths, order = c(0, 1, 0), seasonal = list(order = c(0, 1, 0)))

The arima output object is a list, and the log-likelihood is stored in element loglik:

fit1$loglik
#[1] -425.44
fit2$loglik
#[1] -435.8443


问:
Merge only part of a Word document from Excel source
As the header suggests, I am trying use the MS Office merge functions to apply to a part of a Word document and not the entire document.

Context: I have a database in Excel with names and email addresses of recipients and use this as a source in MS Word. However, I have several languages in one single Word document. The recipient should only receive her own language and not all others. I had set up the Word document that way to avoid having several word documents named Email_booking_FR.docx, Email_booking_EN.docx, Email_booking_NL.docx, etc.
I have to say that the merge functions properly at the moment, with the limitation that the email sent contains all languages.

My Word document looks like this (Minimum Working Example):

```<code>EN

Dear Recipient,

Thank you for your email. We will get back to you as soon as possible.

Best,

FR

Cher Recipient,

Merci pour votre e-mail. Nous le traiterons dans les plus brefs délais.

Cordialement,
</code>```

where Recipient is the field in the Excel worksheet.

Objective:
I wuold like the merge function in MS Word to apply to the whole document (in other words, to complete all Recipient fields, but to send only part of the Word document as an email). Is this possible? Is Word capable of doing such things if the EN and FR parts are sections (Title1 tags)

From the following possibilities, which one(s) are (1) possible and (2) adequate?:

If...then...else statement within Word based on the language of the recipient in the Excel sheet

Separate the languages by a page break (the problem of the Header EN or FR remains, however)

Recover the line number of the specific sections and use it in a Macro (but I have no idea how)

Do you have more thoughts on the matter?

答:
Provided you have a field in the mailmerge data source that identifies the language to be used, you could use a series of fields, coded along the lines of:

```<code>{IF{MERGEFIELD Language}= "EN" "Dear «Recipient»,

Thank you for your email. We will get back to you as soon as possible.

Best,"}{IF{MERGEFIELD Language}= "NL" "Beste «Recipient»,

Bedankt voor je email. We nemen zo snel mogelijk contact met u op.

Het beste,"}{IF{MERGEFIELD Language}= "FR" "Cher «Recipient»,

Merci pour votre e-mail. Nous le traiterons dans les plus brefs délais.

Cordialement,"}
</code>```

Note: The field brace pairs (i.e. '{ }') for the above example are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required.

Note also that the output text cannot contain any double quotes; otherwise the output will be truncated at that point. Moreover, you are liable to have the remainder appearing in the other outputs! You can work around that by using paired single quotes.

You may also find my Mailmerge Tips and Tricks thread at http://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html helpful.

Body:
As the header suggests, I am trying use the MS Office merge functions to apply to a part of a Word document and not the entire document.

Context: I have a database in Excel with names and email addresses of recipients and use this as a source in MS Word. However, I have several languages in one single Word document. The recipient should only receive her own language and not all others. I had set up the Word document that way to avoid having several word documents named Email_booking_FR.docx, Email_booking_EN.docx, Email_booking_NL.docx, etc.
I have to say that the merge functions properly at the moment, with the limitation that the email sent contains all languages.

My Word document looks like this (Minimum Working Example):

EN

Dear Recipient,

Thank you for your email. We will get back to you as soon as possible.

Best,

FR

Cher Recipient,

Merci pour votre e-mail. Nous le traiterons dans les plus brefs délais.

Cordialement,

where Recipient is the field in the Excel worksheet.

Objective:
I wuold like the merge function in MS Word to apply to the whole document (in other words, to complete all Recipient fields, but to send only part of the Word document as an email). Is this possible? Is Word capable of doing such things if the EN and FR parts are sections (Title1 tags)

From the following possibilities, which one(s) are (1) possible and (2) adequate?:

If...then...else statement within Word based on the language of the recipient in the Excel sheet

Separate the languages by a page break (the problem of the Header EN or FR remains, however)

Recover the line number of the specific sections and use it in a Macro (but I have no idea how)

Do you have more thoughts on the matter?

Body:
Provided you have a field in the mailmerge data source that identifies the language to be used, you could use a series of fields, coded along the lines of:

{IF{MERGEFIELD Language}= "EN" "Dear «Recipient»,

Thank you for your email. We will get back to you as soon as possible.

Best,"}{IF{MERGEFIELD Language}= "NL" "Beste «Recipient»,

Bedankt voor je email. We nemen zo snel mogelijk contact met u op.

Het beste,"}{IF{MERGEFIELD Language}= "FR" "Cher «Recipient»,

Merci pour votre e-mail. Nous le traiterons dans les plus brefs délais.

Cordialement,"}

Note: The field brace pairs (i.e. '{ }') for the above example are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required.

Note also that the output text cannot contain any double quotes; otherwise the output will be truncated at that point. Moreover, you are liable to have the remainder appearing in the other outputs! You can work around that by using paired single quotes.

You may also find my Mailmerge Tips and Tricks thread at http://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html helpful.


问:
Finding ResizeObserver with Typescript in Angular 9
I am trying to implement a ResizeObserver in an Angular app:

```<code>const obs = new ResizeObserver(e => {
      // ...
});
</code>```

... and am met with the TS error:

```<code>TS2304: Cannot find name 'ResizeObserver'.
</code>```

I've tried to update my type definition with:

```<code>@types/resize-observer-browser
</code>```

... however my issue persists.  Is there an advisable solution or common workaround, or would it be better to use an NPM package like 'resize-observer' to keep moving forward?

Happy to include more info if needed.

Tks!

答:
I've never used ResizeObserver, however I do use fromEvent from RxJS with the resize event and it's working fine. Here is the code for it.</p>

```<code>import { fromEvent, Observable, Subscription } from "rxjs";

resizeObservable$: Observable<Event>;
resizeSubscription$: Subscription;

ngOnInit() {
  this.resizeObservable$ = fromEvent(element, 'resize')
  this.resizeSubscription$ = this.resizeObservable$.subscribe(evt => {
     // do whatever you waant
  })
}

ngOnDestroy() {
  this.resizeSubscription$.unsubscribe();
}
</code>```

Body:
I am trying to implement a ResizeObserver in an Angular app:

const obs = new ResizeObserver(e => {
      // ...
});

... and am met with the TS error:

TS2304: Cannot find name 'ResizeObserver'.

I've tried to update my type definition with:

@types/resize-observer-browser

... however my issue persists.  Is there an advisable solution or common workaround, or would it be better to use an NPM package like 'resize-observer' to keep moving forward?

Happy to include more info if needed.

Tks!

Body:
I've never used ResizeObserver, however I do use fromEvent from RxJS with the resize event and it's working fine. Here is the code for it.

import { fromEvent, Observable, Subscription } from "rxjs";

resizeObservable$: Observable<Event>;
resizeSubscription$: Subscription;

ngOnInit() {
  this.resizeObservable$ = fromEvent(element, 'resize')
  this.resizeSubscription$ = this.resizeObservable$.subscribe(evt => {
     // do whatever you waant
  })
}

ngOnDestroy() {
  this.resizeSubscription$.unsubscribe();
}


问:
How to add AutoComplete/AutoSuggestion in Microsoft botframework webchat using React.js
I'm trying to add autosuggestion/autocomplete function in my bot-framework web chat(v-4) using react js. In which i want to fetch input data from azure table. Heard that its not recommended to use j-query inside React js. Looking for a solution to add this.

I'm looking for a solution like in the below image, PFA.
And the code which i used for React is attached below,

```<code>React.js file

import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            token: '',
            conversationId:'',
            directLine: {},
            view: false,
            feedBack: null,
            value: '',
            popupContent: '',
            storeValue:''
        };
        this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
        this.handleChange = this.handleChange.bind(this);

    }

    handleTokenGeneration = async () => {
        console.log("handleTokenGeneration");
        const response = await fetch(`api/TokenGenerationService/GetToken`);
        const data = await response.json();
        this.setState({ token: data.categoryObject.token, conversationId: data.categoryObject.conversationId });
        console.log("conversationId");
    };

    async componentDidMount() {
        try {
            await this.handleTokenGeneration();

        } catch (error) {
            console.log("error in fetchung token");
            console.log(error);
        }

        this.state.directLine = new DirectLine({ token: this.state.token });
        this.setState({ view: true });

    }

    handleChange = (event) => {
        this.setState({ value: event.target.value });
    }

    render() {

        if (!this.state.view) {
            return <div />
        } else {
            return (

                <div className="react-container webchat" >
                    <ReactWebChat directLine={this.state.directLine} webSocket={true}  userID='2656' username='res' store={this.state.storeValue} />

                    <footer className="chat-footer" >

                        <div className="foot-footer">
                            Was I helpful ?
                            <span className="feedback"  >Yes</span><span>|</span><span className="feedback" >No</span>
                        </div>
                    </footer>
                </div>
            );
        }
    }

}
</code>```

答:
Web Chat uses Redux which has a Redux store that can use Redux middleware. Web chat has an action called WEB_CHAT/SET_SEND_BOX that can be used to respond to what the user types in the text input box like this:

```<code>const store = window.WebChat.createStore(
    {},
    store => next => action => {
        if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
            const user_entered_text = action.payload.text;

            // Use the text to query the Azure database and display suggestions
        }
        return next(action);
    }
);
</code>```

When the user clicks on a suggestion or presses the right key, you can use that same action to change what's in the text input box like this:

```<code>store.dispatch({
    type: 'WEB_CHAT/SET_SEND_BOX',
    payload: {
        text: user_selected_suggestion,
    }
});
</code>```

There are samples in the Web Chat repo that may help with using Redux actions in Web Chat

Body:
I'm trying to add autosuggestion/autocomplete function in my bot-framework web chat(v-4) using react js. In which i want to fetch input data from azure table. Heard that its not recommended to use j-query inside React js. Looking for a solution to add this.

I'm looking for a solution like in the below image, PFA.
And the code which i used for React is attached below,

React.js file

import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            token: '',
            conversationId:'',
            directLine: {},
            view: false,
            feedBack: null,
            value: '',
            popupContent: '',
            storeValue:''
        };
        this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
        this.handleChange = this.handleChange.bind(this);

    }

    handleTokenGeneration = async () => {
        console.log("handleTokenGeneration");
        const response = await fetch(`api/TokenGenerationService/GetToken`);
        const data = await response.json();
        this.setState({ token: data.categoryObject.token, conversationId: data.categoryObject.conversationId });
        console.log("conversationId");
    };

    async componentDidMount() {
        try {
            await this.handleTokenGeneration();

        } catch (error) {
            console.log("error in fetchung token");
            console.log(error);
        }

        this.state.directLine = new DirectLine({ token: this.state.token });
        this.setState({ view: true });

    }

    handleChange = (event) => {
        this.setState({ value: event.target.value });
    }

    render() {

        if (!this.state.view) {
            return

        } else {
            return (

                    <ReactWebChat directLine={this.state.directLine} webSocket={true}  userID='2656' username='res' store={this.state.storeValue} />

                            Was I helpful ?
                            Yes|No

            );
        }
    }

}

Body:
Web Chat uses Redux which has a Redux store that can use Redux middleware. Web chat has an action called WEB_CHAT/SET_SEND_BOX that can be used to respond to what the user types in the text input box like this:

const store = window.WebChat.createStore(
    {},
    store => next => action => {
        if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
            const user_entered_text = action.payload.text;

            // Use the text to query the Azure database and display suggestions
        }
        return next(action);
    }
);

When the user clicks on a suggestion or presses the right key, you can use that same action to change what's in the text input box like this:

store.dispatch({
    type: 'WEB_CHAT/SET_SEND_BOX',
    payload: {
        text: user_selected_suggestion,
    }
});

There are samples in the Web Chat repo that may help with using Redux actions in Web Chat


问:
jdk source code lookup in cider not working
I am using Emacs 26.3, CIDER 0.23.0 (Lima), Open JDK 11.0.5 (OpenJDK Runtime Environment Corretto-11.0.5.10.2 (build 11.0.5+10-LTS) on macOS Mojave (10.14.6). My CIDER installation works for everything that I need, but not for referencing JDK source code and javadoc. It shows me Clojure source for Clojure methods but not JDK source for any Java methods for some reason. I figured out that my cider-classpath is missing the jdk source.zip location and other jars from JRE as seen below.

```<code>/Users/user/Projects/clojure/test/test
/Users/user/Projects/clojure/test/src
/Users/user/Projects/clojure/test/dev-resources
/Users/user/Projects/clojure/test/resources
/Users/user/Projects/clojure/test/target/classes
/Users/user/.m2/repository/cider/cider-nrepl/0.22.4/cider-nrepl-0.22.4.jar
/Users/user/.m2/repository/nrepl/nrepl/0.6.0/nrepl-0.6.0.jar
/Users/user/.m2/repository/org/clojure/clojure/1.10.0/clojure-1.10.0.jar
/Users/user/.m2/repository/org/clojure/spec.alpha/0.2.176/spec.alpha-0.2.176.jar
/Users/user/.m2/repository/org/clojure/core.specs.alpha/0.2.44/core.specs.alpha-0.2.44.jar
/Users/user/.m2/repository/clojure-complete/clojure-complete/0.2.5/clojure-complete-0.2.5.jar
</code>```

How can I make JDK source code lookup work in CIDER?

答:
Try to add a directory containing a zip with Java sources as a resource to Leiningen profile (~/.lein/profiles.clj) e.g. a default one:

```<code>{:user {:resource-paths ["/usr/lib/jvm/openjdk-8"]}}
</code>```

This now must be included in every project which activates the profile.

I'm using Ubuntu 18.04 with Emacs 26.3 CIDER 0.24.0 nREPL 0.6.0 Java 1.8.0_242.

Body:
I am using Emacs 26.3, CIDER 0.23.0 (Lima), Open JDK 11.0.5 (OpenJDK Runtime Environment Corretto-11.0.5.10.2 (build 11.0.5+10-LTS) on macOS Mojave (10.14.6). My CIDER installation works for everything that I need, but not for referencing JDK source code and javadoc. It shows me Clojure source for Clojure methods but not JDK source for any Java methods for some reason. I figured out that my cider-classpath is missing the jdk source.zip location and other jars from JRE as seen below.

/Users/user/Projects/clojure/test/test
/Users/user/Projects/clojure/test/src
/Users/user/Projects/clojure/test/dev-resources
/Users/user/Projects/clojure/test/resources
/Users/user/Projects/clojure/test/target/classes
/Users/user/.m2/repository/cider/cider-nrepl/0.22.4/cider-nrepl-0.22.4.jar
/Users/user/.m2/repository/nrepl/nrepl/0.6.0/nrepl-0.6.0.jar
/Users/user/.m2/repository/org/clojure/clojure/1.10.0/clojure-1.10.0.jar
/Users/user/.m2/repository/org/clojure/spec.alpha/0.2.176/spec.alpha-0.2.176.jar
/Users/user/.m2/repository/org/clojure/core.specs.alpha/0.2.44/core.specs.alpha-0.2.44.jar
/Users/user/.m2/repository/clojure-complete/clojure-complete/0.2.5/clojure-complete-0.2.5.jar

How can I make JDK source code lookup work in CIDER?

Body:
Try to add a directory containing a zip with Java sources as a resource to Leiningen profile (~/.lein/profiles.clj) e.g. a default one:

{:user {:resource-paths ["/usr/lib/jvm/openjdk-8"]}}

This now must be included in every project which activates the profile.

I'm using Ubuntu 18.04 with Emacs 26.3 CIDER 0.24.0 nREPL 0.6.0 Java 1.8.0_242.