问:
Hibernate statement hangs
From my junit test I'm calling a simple method to clear my table:

```<code>    @AfterClass
public static void runAfterClass() {
    //Clear db contents after tests
    // NOTE this clears ALL data from the table
    try {
        System.out.println("deleting db contents");
        HibFunction.clearTable();
    } catch (Exception e) {
        System.out.println("Couldnt delete db contents");
        e.printStackTrace();
    }
</code>```

The clearTable looks like:

```<code>    public static void clearTable()
{
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try{
    transaction = session.beginTransaction();
    session.createQuery("delete from metadataPoC.hib.TestHib").executeUpdate();
    transaction.commit();
    }catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

}
</code>```

All fairly simple stuff however my console output goes no further than:

```<code>deleting db contents
</code>```

I am unsure why exactly a simple delete from classname

can cause such issues. The programme has just been hanging for 10mins with no failure or result from the junit test.

Edit

However I've isolated the problem to the clearTable() method moved it around in the code and as soon as it entered, hangs!
I'm not exactly sure why exactly, from the info I've found online my method seems correct from what I can see. But it has to be this method. I placed it in my @BeforeClass and the test just frozen when it got to it.

Bottom line there is a problem with the clearTable() method. Thou I've no idea what :(

EDIT 2

tracked down the problem to the executeupdate portion of the command for whatever reason it just stalls once it gets to the:

ParseUtil.encodePath(String, boolean) line: 100

答:
It's probably a deadlock between transaction of clearTable() method and transaction of the test method.

Make sure that you complete (commit or rollback) all transactions when leaving the test method.

Title: Hibernate statement hangs

Body:
From my junit test I'm calling a simple method to clear my table:

    @AfterClass
public static void runAfterClass() {
    //Clear db contents after tests
    // NOTE this clears ALL data from the table
    try {
        System.out.println("deleting db contents");
        HibFunction.clearTable();
    } catch (Exception e) {
        System.out.println("Couldnt delete db contents");
        e.printStackTrace();
    }

The clearTable looks like:

    public static void clearTable()
{
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try{
    transaction = session.beginTransaction();
    session.createQuery("delete from metadataPoC.hib.TestHib").executeUpdate();
    transaction.commit();
    }catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

}

All fairly simple stuff however my console output goes no further than:

deleting db contents

I am unsure why exactly a simple delete from classname

can cause such issues. The programme has just been hanging for 10mins with no failure or result from the junit test.

Edit

However I've isolated the problem to the clearTable() method moved it around in the code and as soon as it entered, hangs!
I'm not exactly sure why exactly, from the info I've found online my method seems correct from what I can see. But it has to be this method. I placed it in my @BeforeClass and the test just frozen when it got to it.

Bottom line there is a problem with the clearTable() method. Thou I've no idea what :(

EDIT 2

tracked down the problem to the executeupdate portion of the command for whatever reason it just stalls once it gets to the:

ParseUtil.encodePath(String, boolean) line: 100


来源: stackexchange

问:
Trying to display JSON Data, but receiving JSON Parse Error
I am trying to display JSON data on my screen, the integer 4 to be exact.

But, I am receiving a JSON Parse Error.

I've posted and that works fine as in Webhooksite says it successfully posted. Also, it "gets" fine, but the data doesn't display. Please help!

```<code>// JSON Data

{
    "cheetosamount": 4,
    "cookiesvalue": 2
}
</code>```

```<code>export default class ChooseDeliveries extends Component {

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    }
  }
  componentDidMount(){
    this.handleGetRequest();
  }

  handleGetRequest() {
    fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
      method: 'GET',
    })
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: JSON.parse(responseJson),
        isLoading: false,
      })
    })
    .catch(error => {
      console.error(error);
    });
  };

  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    } else {
      return(
        <View style={{flex: 1, paddingTop:20}}>
          <Text>
            {this.state.dataSource.cheetosamount}
          </Text>
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

答:
I believe its because that 'JSON' that you are getting is already an object and there's no need for you to parse it.

More indepth explaination provided here SyntaxError: Unexpected token o in JSON at position 1

Try the following in your chrome console

```<code>let c ={
    "cheetosamount": 4,
    "cookiesvalue": 2
}

c.cheetosAmount
</code>```

So essentially all you have to do is

```<code> this.setState({
        dataSource: responseJson,
        isLoading: false,
      })

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to display JSON data on my screen, the integer 4 to be exact.

But, I am receiving a JSON Parse Error.

I've posted and that works fine as in Webhooksite says it successfully posted. Also, it "gets" fine, but the data doesn't display. Please help!

// JSON Data

{
    "cheetosamount": 4,
    "cookiesvalue": 2
}

export default class ChooseDeliveries extends Component {

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    }
  }
  componentDidMount(){
    this.handleGetRequest();
  }

  handleGetRequest() {
    fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
      method: 'GET',
    })
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: JSON.parse(responseJson),
        isLoading: false,
      })
    })
    .catch(error => {
      console.error(error);
    });
  };

  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    } else {
      return(
        <View style={{flex: 1, paddingTop:20}}>
          <Text>
            {this.state.dataSource.cheetosamount}
          </Text>
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Body:
I believe its because that 'JSON' that you are getting is already an object and there's no need for you to parse it.

More indepth explaination provided here SyntaxError: Unexpected token o in JSON at position 1

Try the following in your chrome console

let c ={
    "cheetosamount": 4,
    "cookiesvalue": 2
}

c.cheetosAmount

So essentially all you have to do is

 this.setState({
        dataSource: responseJson,
        isLoading: false,
      })


问:
Python 3.7 MultiThreading strategy
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

```<code>for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]
</code>```

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4

答:
It's hard to say if and how much this will actually help (as I have nothing to test...), but you might try a multiprocessing.Pool. It handles all the dirty work for you and you can customize number of processes, chunk size etc.

from multiprocessing import Pool

def worker(x):
    myData = DownloadData(x)
    return ParseData(myData)

if __name__ == "__main__":
    processes = None  # defaults to os.cpu_count()
    chunksize = 1

    with Pool(processes) as pool:
        parsedData = pool.map(worker, lastTenYears, chunksize)
```

Here for the example I use the map method, but according to your needs you might want to use imap or map_async.

Title: Python 3.7 MultiThreading strategy

Body:
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4

Body:
It's hard to say if and how much this will actually help (as I have nothing to test...), but you might try a multiprocessing.Pool. It handles all the dirty work for you and you can customize number of processes, chunk size etc.

from multiprocessing import Pool

def worker(x):
    myData = DownloadData(x)
    return ParseData(myData)

if __name__ == "__main__":
    processes = None  # defaults to os.cpu_count()
    chunksize = 1

    with Pool(processes) as pool:
        parsedData = pool.map(worker, lastTenYears, chunksize)

Here for the example I use the map method, but according to your needs you might want to use imap or map_async.


问:
Oracle SQL procedure with table name as input using dynamic SQL
I see a lot of similar questions already answered including here, here and here.  The list goes on.

What makes mine different?  These other questions seem to be very simple, one line sql statements.  I have a more complex merge statement that spans multiple lines and no matter how I have tried to put the statement together it gives me a compilation error.  Below is one such attempt.

It is a long statement, the only dynamic parts are 2 nonconsecutive lines at the very beginning as shown below.  I have tried to make the whole statement a string and execute it, but I get an error that the string is too long, plus this makes it very hard to read so it is undesirable.  I have also tried breaking up the 2 parts that require dynamic sql into 2 execute immediate blocks, but that throws a compilation error as well.

My code

```<code>create or replace procedure table_sync(
table_name in varchar2,
source_node in varchar2
)

is

begin
    execute immediate
        'merge into ' || table_name || ' dest' /* ---- first line ---- */

        using (select date_time, version_date, data_entry_date, value
                'from username.' || table_name || '@' || source_node /* ---- second line ---- */
                where data_entry_date < (sysdate - 10)) src
        on    ( dest.date_time       = src.date_time  and
                dest.version_date    = src.version_date
                )
        when  matched then
            update
                set
                    dest.data_entry_date = src.data_entry_date,
                    dest.value           = src.value
                    where
                        (case
                          .
                          .
                          .
</code>```

Is there a way to put combine this dynamic statement?

Thank you

答:
Using merge to achieve this is a good approach, but your statement is missing some quotes. Here is a fiddle with an example, similar to what you are trying to do.

From that fiddle, create test data:

```<code>create table table1(id varchar2(30), username varchar2(30), fullname varchar2(30));
create table table2(id varchar2(30), username varchar2(30), fullname varchar2(30));

insert into table1 values('a1', 'b1', 'c1');
insert into table1 values('a2', 'b2', 'c2');
insert into table1 values('a3', 'b3', 'c3');
insert into table1 values('a4', 'b4', 'c4');

insert into table2 values('a1', 'b1', 'c1');
insert into table2 values('a2', 'b2', 'c2');
insert into table2 values('a3', 'b3', 'c3');
</code>```

Your function:

```<code>CREATE OR replace PROCEDURE Table_sync(table_name IN VARCHAR2)
IS
  stmnt CLOB;
BEGIN
    stmnt := 'merge into ' || table_name || ' dest '
             || 'using (select id, username from table1) src '
             || 'on (dest.id = src.id) '
             ||
    ' when matched then update set dest.fullname = src.username || src.id '
             || ' where dest.username like ''%2'' '
             || ' when not matched then insert (id, username, fullname) values(src.id, src.id||src.username, src.username||src.username) '
;

EXECUTE IMMEDIATE stmnt;
END table_sync;
</code>```

If the record in table1 exists with the same value in col1 as the column in table2, then it will update it based on a condition, if the record does not exist, it will insert it.

You can write all your conditions inside that where statement and pay attention to the 2xsingle quotes used for quoting values in the dynamic query.

Body:
I see a lot of similar questions already answered including here, here and here.  The list goes on.

What makes mine different?  These other questions seem to be very simple, one line sql statements.  I have a more complex merge statement that spans multiple lines and no matter how I have tried to put the statement together it gives me a compilation error.  Below is one such attempt.

It is a long statement, the only dynamic parts are 2 nonconsecutive lines at the very beginning as shown below.  I have tried to make the whole statement a string and execute it, but I get an error that the string is too long, plus this makes it very hard to read so it is undesirable.  I have also tried breaking up the 2 parts that require dynamic sql into 2 execute immediate blocks, but that throws a compilation error as well.

My code

create or replace procedure table_sync(
table_name in varchar2,
source_node in varchar2
)

is

begin
    execute immediate
        'merge into ' || table_name || ' dest' /* ---- first line ---- */

        using (select date_time, version_date, data_entry_date, value
                'from username.' || table_name || '@' || source_node /* ---- second line ---- */
                where data_entry_date < (sysdate - 10)) src
        on    ( dest.date_time       = src.date_time  and
                dest.version_date    = src.version_date
                )
        when  matched then
            update
                set
                    dest.data_entry_date = src.data_entry_date,
                    dest.value           = src.value
                    where
                        (case
                          .
                          .
                          .

Is there a way to put combine this dynamic statement?

Thank you

Body:
Using merge to achieve this is a good approach, but your statement is missing some quotes. Here is a fiddle with an example, similar to what you are trying to do.

From that fiddle, create test data:

create table table1(id varchar2(30), username varchar2(30), fullname varchar2(30));
create table table2(id varchar2(30), username varchar2(30), fullname varchar2(30));

insert into table1 values('a1', 'b1', 'c1');
insert into table1 values('a2', 'b2', 'c2');
insert into table1 values('a3', 'b3', 'c3');
insert into table1 values('a4', 'b4', 'c4');

insert into table2 values('a1', 'b1', 'c1');
insert into table2 values('a2', 'b2', 'c2');
insert into table2 values('a3', 'b3', 'c3');

Your function:

CREATE OR replace PROCEDURE Table_sync(table_name IN VARCHAR2)
IS
  stmnt CLOB;
BEGIN
    stmnt := 'merge into ' || table_name || ' dest '
             || 'using (select id, username from table1) src '
             || 'on (dest.id = src.id) '
             ||
    ' when matched then update set dest.fullname = src.username || src.id '
             || ' where dest.username like ''%2'' '
             || ' when not matched then insert (id, username, fullname) values(src.id, src.id||src.username, src.username||src.username) '
;

EXECUTE IMMEDIATE stmnt;
END table_sync;

If the record in table1 exists with the same value in col1 as the column in table2, then it will update it based on a condition, if the record does not exist, it will insert it.

You can write all your conditions inside that where statement and pay attention to the 2xsingle quotes used for quoting values in the dynamic query.


问:
perl validate data structure syntax
i have configuration files for my scripts containing huge data structures, e.g:

```<code>foo  =>  'bar',
one  =>  'two',
bla  =>  [
           'something',
           'else',
         ],
bli  =>  {
           here  =>  {
                       'and'  => 'there',
                       'also' => 'here',
                     },
         },
etc.
</code>```

i'm loading these configuration files using a simple e.g. :

```<code>%hash = do 'config.file';
</code>```

my problem is : when users modify this configuration file, they can mess it up, forgetting a comma, bracket or anything else, it can have terrible impacts as the variables will appear empty afterwards in the script (i don't want to check for the presence of every variable..)

is there any way to "validate" the syntax of such a file/structure at loading time or right after loading it ? any module doing this ?

i suppose i could add a value at the bottom and check for the presence of this value but it's a bit dirty.

thank you !

答: Rx is intended to validate the schema of JSON/YAML documents but because it runs on the in-memory data structure rather than the file it's usable with arbitrary config file formats. (It also means that it can't make certain distinctions like the use of true vs. 1 in YAML/JSON.)

Title: perl validate data structure syntax

Body:
i have configuration files for my scripts containing huge data structures, e.g:

foo  =>  'bar',
one  =>  'two',
bla  =>  [
           'something',
           'else',
         ],
bli  =>  {
           here  =>  {
                       'and'  => 'there',
                       'also' => 'here',
                     },
         },
etc.

i'm loading these configuration files using a simple e.g. :

%hash = do 'config.file';

my problem is : when users modify this configuration file, they can mess it up, forgetting a comma, bracket or anything else, it can have terrible impacts as the variables will appear empty afterwards in the script (i don't want to check for the presence of every variable..)

is there any way to "validate" the syntax of such a file/structure at loading time or right after loading it ? any module doing this ?

i suppose i could add a value at the bottom and check for the presence of this value but it's a bit dirty.

thank you !


问:
Create an int[] from Dictionary<int, List<int>>, from each dictionary element's Value List<int> I need an array which contains all dictionary elements
The solution I have for now is as...

```<code>Dictionary<int, List<int>> oDict = <Some code to fill in the dictionary>;

var oList = new List<int>();
oDict.Values.ForEach(oList.AddRange);
oList.ToArray();
</code>```

Is there a way to do this without using the additional List<int>?

答:
Yup, that looks like:

```<code>var array = oDict.Values.SelectMany(list => list).ToArray();
</code>```

(If you only want distinct elements, just call Distinct before ToArray.)

ContentLicense: CC BY-SA 3.0

Body:
The solution I have for now is as...

Dictionary<int, List<int>> oDict = <Some code to fill in the dictionary>;

var oList = new List<int>();
oDict.Values.ForEach(oList.AddRange);
oList.ToArray();

Is there a way to do this without using the additional List<int>?

Body:
Yup, that looks like:

var array = oDict.Values.SelectMany(list => list).ToArray();

(If you only want distinct elements, just call Distinct before ToArray.)


问:
How to create dynamic self-sizing height UITableViewCell in swift?
Hey I have a tableview controller and I want to create dynamic cell height with label and ImageViews. I tried something like below but it doesn't work for me. Where is the mistake about code. Any idea ?</p>

```<code>class NotificationsPageController: UITableViewController{

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    view.backgroundColor = .black
    tableView.estimatedRowHeight = 60
}

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      return 60
  }

 class NotificationCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier)
   backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

    setNotificationAnchors()

}

fileprivate func setNotificationAnchors() {

    addSubview(notiType)
    notiType.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 6, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)
    //notiType.centerYAnchor.constraint(equalTo: notiImage.centerYAnchor).isActive = true

    addSubview(notiImage)
    notiImage.anchor(top: nil, left: nil, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)
    notiImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

答:
First, I strongly recommend you learn how constraints and auto-layout work. The fact that the code you posted shows you are using a .anchor(top:left:bottom:right:...) type of "constraint helper" indicates that you don't understand it yet.

So, here is a simple example. Note that this is not a complete implementation, but it should get you headed in the right direction:

```<code>class NotificationCell: UITableViewCell {

    let notiType: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.numberOfLines = 0
        return v
    }()

    let notiImage: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

        setNotificationAnchors()

    }

    fileprivate func setNotificationAnchors() {

        contentView.addSubview(notiType)
        contentView.addSubview(notiImage)

        let g = contentView.layoutMarginsGuide

        NSLayoutConstraint.activate([

            // constrain label Top, Leading, Bottom to contentView margins
            notiType.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            notiType.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
            notiType.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),

            // constrain image view Right and centerY to contentView margins
            notiImage.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
            notiImage.centerYAnchor.constraint(equalTo: g.centerYAnchor, constant: 0.0),

            // guessing square (1:1 ratio) image view, 24 x 24
            notiImage.widthAnchor.constraint(equalToConstant: 24.0),
            notiImage.heightAnchor.constraint(equalTo: notiImage.widthAnchor),

            // leave 8-pts space between label and image view
            notiType.trailingAnchor.constraint(equalTo: notiImage.leadingAnchor, constant: -8.0),

        ])

        // during development, so we can easily see the element frames
        notiType.backgroundColor = .cyan
        notiImage.backgroundColor = .red

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ExampleTableViewController: UITableViewController {

    let notCell = "notCell"

    let theData: [String] = [
        "Single line label.",
        "This lable will have enough text that it will need to wrap onto multiple lines.",
        "Another single line cell.",
        "Here is a description of a table view cell: Defines the attributes and behavior of cells in a table view. You can set a table cell's selected-state appearance, support editing functionality, display accessory views (such as a switch control), and specify background appearance and content indentation.",
        "This is the fifth row.",
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return theData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: notCell, for: indexPath) as! NotificationCell

        cell.notiType.text = theData[indexPath.row]

        // set image here...
        //cell.notiImage.image = ...

        return cell
    }

}
</code>```

Result - Multi-line label (cyan background) and 24x24 image (red background):

By the way... Step-by-step tutorials on this can be found in many, many places - a little tough to think you searched and couldn't find anything like this.

Body:
Hey I have a tableview controller and I want to create dynamic cell height with label and ImageViews. I tried something like below but it doesn't work for me. Where is the mistake about code. Any idea ?

class NotificationsPageController: UITableViewController{

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    view.backgroundColor = .black
    tableView.estimatedRowHeight = 60
}

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
      return 60
  }

 class NotificationCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier)
   backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

    setNotificationAnchors()

}

fileprivate func setNotificationAnchors() {

    addSubview(notiType)
    notiType.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 6, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)
    //notiType.centerYAnchor.constraint(equalTo: notiImage.centerYAnchor).isActive = true

    addSubview(notiImage)
    notiImage.anchor(top: nil, left: nil, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)
    notiImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

Body:
First, I strongly recommend you learn how constraints and auto-layout work. The fact that the code you posted shows you are using a .anchor(top:left:bottom:right:...) type of "constraint helper" indicates that you don't understand it yet.

So, here is a simple example. Note that this is not a complete implementation, but it should get you headed in the right direction:

class NotificationCell: UITableViewCell {

    let notiType: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.numberOfLines = 0
        return v
    }()

    let notiImage: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1)

        setNotificationAnchors()

    }

    fileprivate func setNotificationAnchors() {

        contentView.addSubview(notiType)
        contentView.addSubview(notiImage)

        let g = contentView.layoutMarginsGuide

        NSLayoutConstraint.activate([

            // constrain label Top, Leading, Bottom to contentView margins
            notiType.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            notiType.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
            notiType.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),

            // constrain image view Right and centerY to contentView margins
            notiImage.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
            notiImage.centerYAnchor.constraint(equalTo: g.centerYAnchor, constant: 0.0),

            // guessing square (1:1 ratio) image view, 24 x 24
            notiImage.widthAnchor.constraint(equalToConstant: 24.0),
            notiImage.heightAnchor.constraint(equalTo: notiImage.widthAnchor),

            // leave 8-pts space between label and image view
            notiType.trailingAnchor.constraint(equalTo: notiImage.leadingAnchor, constant: -8.0),

        ])

        // during development, so we can easily see the element frames
        notiType.backgroundColor = .cyan
        notiImage.backgroundColor = .red

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ExampleTableViewController: UITableViewController {

    let notCell = "notCell"

    let theData: [String] = [
        "Single line label.",
        "This lable will have enough text that it will need to wrap onto multiple lines.",
        "Another single line cell.",
        "Here is a description of a table view cell: Defines the attributes and behavior of cells in a table view. You can set a table cell's selected-state appearance, support editing functionality, display accessory views (such as a switch control), and specify background appearance and content indentation.",
        "This is the fifth row.",
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(NotificationCell.self, forCellReuseIdentifier: notCell)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return theData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: notCell, for: indexPath) as! NotificationCell

        cell.notiType.text = theData[indexPath.row]

        // set image here...
        //cell.notiImage.image = ...

        return cell
    }

}

Result - Multi-line label (cyan background) and 24x24 image (red background):

By the way... Step-by-step tutorials on this can be found in many, many places - a little tough to think you searched and couldn't find anything like this.


问:
Redis command to get all available keys?
Is there a Redis command for fetching all keys in the database? I have seen some python-redis libraries fetching them. But was wondering if it is possible from redis-client.</p>

答:
If you are using Laravel Framework then you can simply use this:

```<code>$allKeyList = Redis::KEYS("*");

print_r($allKeyList);
</code>```

In Core PHP:

```<code>$redis = new Redis();

$redis->connect('hostname', 6379);

$allKeyList = $redis->keys('*');

print_r($allKeyList);
</code>```

Body:
If you are using Laravel Framework then you can simply use this:

$allKeyList = Redis::KEYS("*");

print_r($allKeyList);

In Core PHP:

$redis = new Redis();

$redis->connect('hostname', 6379);

$allKeyList = $redis->keys('*');

print_r($allKeyList);


问:
cudnn error :: CUDNN_STATUS_SUCCESS (1 vs. 0) CUDNN_STATUS_NOT_INITIALIZED
I am trying to install a open-source software "openpose" for which I needed to install cuda, cudnn and nvidia drivers. Output of nvidia-smi is :

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.59       Driver Version: 440.59       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce 940MX       Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   47C    P8    N/A /  N/A |    107MiB /  2004MiB |      7%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1513      G   /usr/lib/xorg/Xorg                            63MiB |
|    0      1698      G   /usr/bin/gnome-shell                          41MiB |
+-----------------------------------------------------------------------------+

</code>```

And output of cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2 gives:

```<code>#define CUDNN_MAJOR 7
#define CUDNN_MINOR 6
#define CUDNN_PATCHLEVEL 5
</code>```

After successfull installations of all the above softwares and libraries, I finally ran openpose
with:

```<code>./build/examples/openpose/openpose.bin --video examples/media/video.avi
</code>```

But the output was:

```<code>Starting OpenPose demo...
Configuring OpenPose...
Starting thread(s)...
Auto-detecting all available GPUs... Detected 1 GPU(s), using 1 of them starting at GPU 0.
F0214 01:02:35.327615  3433 cudnn_conv_layer.cpp:53] Check failed: status == CUDNN_STATUS_SUCCESS (1 vs. 0)  CUDNN_STATUS_NOT_INITIALIZED
*** Check failure stack trace: ***
    @     0x7fabb8f390cd  google::LogMessage::Fail()
    @     0x7fabb8f3af33  google::LogMessage::SendToLog()
    @     0x7fabb8f38c28  google::LogMessage::Flush()
    @     0x7fabb8f3b999  google::LogMessageFatal::~LogMessageFatal()
    @     0x7fabb89459d3  caffe::CuDNNConvolutionLayer<>::LayerSetUp()
    @     0x7fabb8a42308  caffe::Net<>::Init()
    @     0x7fabb8a441e0  caffe::Net<>::Net()
    @     0x7fabbaa2ccaa  op::NetCaffe::initializationOnThread()
    @     0x7fabbaa500a1  op::addCaffeNetOnThread()
    @     0x7fabbaa51518  op::PoseExtractorCaffe::netInitializationOnThread()
    @     0x7fabbaa57163  op::PoseExtractorNet::initializationOnThread()
    @     0x7fabbaa4be61  op::PoseExtractor::initializationOnThread()
    @     0x7fabbaa46a51  op::WPoseExtractor<>::initializationOnThread()
    @     0x7fabbaa8aff1  op::Worker<>::initializationOnThreadNoException()
    @     0x7fabbaa8b120  op::SubThread<>::initializationOnThread()
    @     0x7fabbaa8d2d8  op::Thread<>::initializationOnThread()
    @     0x7fabbaa8d4a7  op::Thread<>::threadFunction()
    @     0x7fabba32566f  (unknown)
    @     0x7fabb9a476db  start_thread
    @     0x7fabb9d8088f  clone
Aborted

</code>```

I have gone through a lot of online discussions but could not figure out how to resolve this.

答:
I have been having the same problem with CUDNN.

Although not ideal, I have been running without CUDNN. In cmake-gui uncheck USE_CUDNN and then compile. When running openpose I have also had to reduce -net_resolution.

For example:  ./build/examples/openpose/openpose.bin -net_resolution 256x192
The greater the resolution the slower the FPS though.

Body:
I am trying to install a open-source software "openpose" for which I needed to install cuda, cudnn and nvidia drivers. Output of nvidia-smi is :

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.59       Driver Version: 440.59       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce 940MX       Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   47C    P8    N/A /  N/A |    107MiB /  2004MiB |      7%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1513      G   /usr/lib/xorg/Xorg                            63MiB |
|    0      1698      G   /usr/bin/gnome-shell                          41MiB |
+-----------------------------------------------------------------------------+

And output of cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2 gives:

#define CUDNN_MAJOR 7
#define CUDNN_MINOR 6
#define CUDNN_PATCHLEVEL 5

After successfull installations of all the above softwares and libraries, I finally ran openpose
with:

./build/examples/openpose/openpose.bin --video examples/media/video.avi

But the output was:

Starting OpenPose demo...
Configuring OpenPose...
Starting thread(s)...
Auto-detecting all available GPUs... Detected 1 GPU(s), using 1 of them starting at GPU 0.
F0214 01:02:35.327615  3433 cudnn_conv_layer.cpp:53] Check failed: status == CUDNN_STATUS_SUCCESS (1 vs. 0)  CUDNN_STATUS_NOT_INITIALIZED
*** Check failure stack trace: ***
    @     0x7fabb8f390cd  google::LogMessage::Fail()
    @     0x7fabb8f3af33  google::LogMessage::SendToLog()
    @     0x7fabb8f38c28  google::LogMessage::Flush()
    @     0x7fabb8f3b999  google::LogMessageFatal::~LogMessageFatal()
    @     0x7fabb89459d3  caffe::CuDNNConvolutionLayer<>::LayerSetUp()
    @     0x7fabb8a42308  caffe::Net<>::Init()
    @     0x7fabb8a441e0  caffe::Net<>::Net()
    @     0x7fabbaa2ccaa  op::NetCaffe::initializationOnThread()
    @     0x7fabbaa500a1  op::addCaffeNetOnThread()
    @     0x7fabbaa51518  op::PoseExtractorCaffe::netInitializationOnThread()
    @     0x7fabbaa57163  op::PoseExtractorNet::initializationOnThread()
    @     0x7fabbaa4be61  op::PoseExtractor::initializationOnThread()
    @     0x7fabbaa46a51  op::WPoseExtractor<>::initializationOnThread()
    @     0x7fabbaa8aff1  op::Worker<>::initializationOnThreadNoException()
    @     0x7fabbaa8b120  op::SubThread<>::initializationOnThread()
    @     0x7fabbaa8d2d8  op::Thread<>::initializationOnThread()
    @     0x7fabbaa8d4a7  op::Thread<>::threadFunction()
    @     0x7fabba32566f  (unknown)
    @     0x7fabb9a476db  start_thread
    @     0x7fabb9d8088f  clone
Aborted

I have gone through a lot of online discussions but could not figure out how to resolve this.


问:
Installing NumPy via Anaconda in Windows
I am trying to use Numpy in a Python 2.7.8 script in Windows. So, I download and installed the latest version of Anaconda (I also want to use some of the other tools in Anaconda) to the directory "C:/Anaconda". As default, I checked the boxing asking me if I wanted to add the path to the binary files to the Windows PATH.

After checking PATH, it contains the following: "C:\Anaconda;C:\Anaconda\Scripts".

Then, after installation I open a new Command Prompt, and in the Python envirnoment, I enter "import numpy", but this gives the error: "ImportError: No module named numpy".

What stage have I missed out in the installation process?

***** EDIT *****

I have just noticed that there is no file called "numpy" in either "C:\Anaconda" or "C:\Anaconda\Scripts". But according to the Anaconda website (http://docs.continuum.io/anaconda/pkg-docs.html), the installation should come with Numpy...

***** EDIT *****

It seems that Windows was running Python from an existing version of Python I had installed, which was not associated with NumPy. After deleting this, and running Python from the Anaconda installation, NumPy is now being recognised.

答:
The above answers seem to resolve the issue.
If it doesn't, then you may also try to update conda using the following command.

```<code>conda update conda
</code>```

And then try to install numpy using

```<code>conda install numpy
</code>```

Body:
The above answers seem to resolve the issue.
If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy


问:
DataSource DisplayMember with custom string composed of DataSource properties
Is it possible to bind a ListBox to a DataSource of List, while setting the DisplayMember to a custom string composed of A's properties, such as the following $"{A.b} {A.c}"?

var list1 = new List();
// populate list
MyListBox.DisplayMember = $"{A.b} {A.c}"; // not going to work
MyListBox.DataSource = list1;
```

<p>I know I can use an anonymous type, but I want the ListBox.Items to remain of type A. I don't want to do the following,</p>

<pre class="lang-cs prettyprint-override"><code>var list2 = (from a in list1
             select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.DataSource = list2;
</code>```

because now MyListBox.Items is anonymous and A can't be retrieved like var list = MyListBox.Items.OfType().

So, is there any way to do that?

答:
I was thinking about it wrong. Solved it now. Maybe it was obvious to some, but I'm going to post my answer for posterity.

Use the anonymous type in the second example, and just set the ValueMember to A

var list2 = (from a in list1
             select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.ValueMember = "A";
MyListBox.DataSource = list2;

var list3 = MyListBox.Items.OfType().ToList(); // works!
```

Body:
Is it possible to bind a ListBox to a DataSource of List, while setting the DisplayMember to a custom string composed of A's properties, such as the following $"{A.b} {A.c}"?

var list1 = new List();
// populate list
MyListBox.DisplayMember = $"{A.b} {A.c}"; // not going to work
MyListBox.DataSource = list1;

I know I can use an anonymous type, but I want the ListBox.Items to remain of type A. I don't want to do the following,

var list2 = (from a in list1
             select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.DataSource = list2;

because now MyListBox.Items is anonymous and A can't be retrieved like var list = MyListBox.Items.OfType().

So, is there any way to do that?

Body:
I was thinking about it wrong. Solved it now. Maybe it was obvious to some, but I'm going to post my answer for posterity.

Use the anonymous type in the second example, and just set the ValueMember to A

var list2 = (from a in list1
             select new {A = a, DisplayMember = $"{a.b} {a.c}"}).ToList();
MyListBox.DisplayMember = "DisplayMember";
MyListBox.ValueMember = "A";
MyListBox.DataSource = list2;

var list3 = MyListBox.Items.OfType<A>().ToList(); // works!


问:
How to insert
 in markaby (rails)
I have to do something like this

 Freeze

 2010-6-1

How can i write it in markaby?
Now I have:
td "#{user.username} #{user.created_at}"

答:
Im not sure, but try this:</p>

```<code>td do
    user.username user.created_at :br
end
</code>```

Title: How to insert <br> in markaby (rails)

Body:
Im not sure, but try this:

td do
    user.username user.created_at :br
end


问:
What's the alternative of layout_above in ConstraintLayout?
I've tried app:layout_constraintBottom_toTopOf="@id/the_view_which_will_remain_below" but it's not the desired output.
I want the same behavior from RelativeLayout's layout_above.

With this code my Textview starts appearing from the bottom and as the character increases texts goes above. But I want the texts to start from starting of parent.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context="com.fatimamostafa.restfulwebservices.asynctask.AsyncTaskRequest">
    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Run" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Clear" />

    </LinearLayout>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/ll"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:textSize="160sp"
        android:text="Text"
      />

</android.support.constraint.ConstraintLayout>
</code>```

答:
You can use height 0dp and organize views vertically.

in relative layout we can use layout below and above like

```<code><FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav"
        android:layout_below="@+id/toolbar"
        />
</code>```

In constraint layout giving height is compulsory so you can give 0 height. and then you can set your view below other views like this

```<code><android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tablayout" />
</code>```

you can use constraintTop_toBottomOf and constraintBottom_toTopOf properties to adjust your view to above or below of other.
thanks

Body:
I've tried app:layout_constraintBottom_toTopOf="@id/the_view_which_will_remain_below" but it's not the desired output.
I want the same behavior from RelativeLayout's layout_above.

With this code my Textview starts appearing from the bottom and as the character increases texts goes above. But I want the texts to start from starting of parent.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context="com.fatimamostafa.restfulwebservices.asynctask.AsyncTaskRequest">
    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Run" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Clear" />

    </LinearLayout>
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/ll"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:textSize="160sp"
        android:text="Text"
      />

</android.support.constraint.ConstraintLayout>

Body:
You can use height 0dp and organize views vertically.

in relative layout we can use layout below and above like

<FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_nav"
        android:layout_below="@+id/toolbar"
        />

In constraint layout giving height is compulsory so you can give 0 height. and then you can set your view below other views like this

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tablayout" />

you can use constraintTop_toBottomOf and constraintBottom_toTopOf properties to adjust your view to above or below of other.
thanks


问:
Code for converting entire data frame to numeric
Is there an R function to convert the entire data frame to numeric. My data frame contains only numeric variables but when queried with r with the is.numeric code, it comes as false. </p>

答:
With dplyr :

mutate_all(data, function(x) as.numeric(as.character(x)))


问:
groupby - aggregate - groupby
```<code>Category | Unit | ID | Time | isReq
  1         A     x1    t1      0
  1         A     x1    t2      0
  1         A     x1    t3      0
  1         A     x1    t4      0
  1         B     x2    t5      1
  1         B     x2    t6      0
  1         B     x2    t7      0
</code>```

I am trying to find the unique number of IDs per category and unit, as well as the mean time duration for them. The final result should look like :-

```<code>Category | Unit | ID_count |            time:diff
   1        A        1         mean_time_to_completion for all ids in category and unit
</code>```

There can be multiple IDs under a given Category and Unit.
How can I go ahead  with the data that I have to get the result? I can independently get the unique IDs groupped by Category and Unit, but I'm having difficulty in getting all the fields in one query.

EDIT:- I've managed to perform the necessary operation the following way  : -

```<code> df1.groupby(['Category','Unit','ID'])['Time'].agg(['first','last']).diff(axis = 1).iloc[:,-1].reset_index().groupby(['Category','Unit']).agg({'ID' : 'count','last' : pd.Series.mean})
</code>```

I now am trying to calculate the contribution of each ID as a perc  of total isReq count in the same query as above. Any helpful suggestions will be welcome

答:
You could try this - </p>

```<code>df.groupby(['Category', 'Unit']).agg(ID_count=('ID','nunique'), time_diff=('Time', 'mean'))
</code>```

Title: groupby - aggregate - groupby

Body:
Category | Unit | ID | Time | isReq
  1         A     x1    t1      0
  1         A     x1    t2      0
  1         A     x1    t3      0
  1         A     x1    t4      0
  1         B     x2    t5      1
  1         B     x2    t6      0
  1         B     x2    t7      0

I am trying to find the unique number of IDs per category and unit, as well as the mean time duration for them. The final result should look like :-

Category | Unit | ID_count |            time:diff
   1        A        1         mean_time_to_completion for all ids in category and unit

There can be multiple IDs under a given Category and Unit.
How can I go ahead  with the data that I have to get the result? I can independently get the unique IDs groupped by Category and Unit, but I'm having difficulty in getting all the fields in one query.

EDIT:- I've managed to perform the necessary operation the following way  : -

 df1.groupby(['Category','Unit','ID'])['Time'].agg(['first','last']).diff(axis = 1).iloc[:,-1].reset_index().groupby(['Category','Unit']).agg({'ID' : 'count','last' : pd.Series.mean})

I now am trying to calculate the contribution of each ID as a perc  of total isReq count in the same query as above. Any helpful suggestions will be welcome

Body:
You could try this -

df.groupby(['Category', 'Unit']).agg(ID_count=('ID','nunique'), time_diff=('Time', 'mean'))


问:
What is context of function called inside another function without this?
I have code where LivingBeing is superType and Man is subType. I have defined toString() methods on both of them. Consider the code below:

```<code>function LivingBeing() {}

LivingBeing.prototype.toString = function () {
    return "hi";
};

function Man() {}
Object.setPrototypeOf(Man.prototype, LivingBeing.prototype);
Man.prototype.toString = function () {
    return window.toString();
};

let m1 = new Man();
console.log(m1.toString()); // Prints [object Window]
</code>```

But if I remove the window context :

```<code>function LivingBeing() {}

LivingBeing.prototype.toString = function () {
    return "hi";
};

function Man() {}
Object.setPrototypeOf(Man.prototype, LivingBeing.prototype);
Man.prototype.toString = function () {
    return toString(); // Window context removed now; Rest code same
};

let m1 = new Man();
console.log(m1.toString()); // Prints [object Undefined]
</code>```

Should not the absence of context be taken as window by the browser ? Whose toString() is it calling ?

答:
Should not the absence of context be taken as window by the browser?

No, because the native toString method (inherited by the global object from Object.prototype) is a strict mode function, and does not fall back to the global object when no context is passed.

Body:
I have code where LivingBeing is superType and Man is subType. I have defined toString() methods on both of them. Consider the code below:

function LivingBeing() {}

LivingBeing.prototype.toString = function () {
    return "hi";
};

function Man() {}
Object.setPrototypeOf(Man.prototype, LivingBeing.prototype);
Man.prototype.toString = function () {
    return window.toString();
};

let m1 = new Man();
console.log(m1.toString()); // Prints [object Window]

But if I remove the window context :

function LivingBeing() {}

LivingBeing.prototype.toString = function () {
    return "hi";
};

function Man() {}
Object.setPrototypeOf(Man.prototype, LivingBeing.prototype);
Man.prototype.toString = function () {
    return toString(); // Window context removed now; Rest code same
};

let m1 = new Man();
console.log(m1.toString()); // Prints [object Undefined]

Should not the absence of context be taken as window by the browser ? Whose toString() is it calling ?


问:
combination columns in validationRule
I'm New in Adonis.js,I Have user-migration such as this:

```<code>  table.enu('type', ['client','admin','super_admin']),
  table.string('mobile', 80).notNullable().unique();
</code>```

Now,I Want to check mobile + type be unique for all users in validation,While I just can check mobile unique with this code:

```<code>mobile : 'required|string|unique:users,mobile',
</code>```

How I can so this?

答:
I created something like that, using extending validator:

```<code>async unique_combinationFn(data, field, message, args, get) { // eslint-disable-line
const Database = use('Database');
const value = get(data, field);
if (!value) {
  return;
}
const [table, ...columns] = args;

const multipleClauses = columns.reduce(
  (oldObject, column) => ({
    ...oldObject,
    [column]: data[column],
  }),
  {}
);

const where = { ...multipleClauses, [field]: value };

const row = data.id
  ? await Database.table(table)
      .where(where)
      .whereNot('id', data.id)
      .first()
  : await Database.table(table)
      .where(where)
      .first();
if (row) {
  throw message;
}
</code>```

}

and to use:

```<code>code: [rule('required'), rule('unique_combination', ['users', 'company_id'])],
</code>```

you can find more in doc in this link:

Extending Validator

Title: combination columns in validationRule

Body:
I'm New in Adonis.js,I Have user-migration such as this:

  table.enu('type', ['client','admin','super_admin']),
  table.string('mobile', 80).notNullable().unique();

Now,I Want to check mobile + type be unique for all users in validation,While I just can check mobile unique with this code:

mobile : 'required|string|unique:users,mobile',

How I can so this?

Body:
I created something like that, using extending validator:

async unique_combinationFn(data, field, message, args, get) { // eslint-disable-line
const Database = use('Database');
const value = get(data, field);
if (!value) {
  return;
}
const [table, ...columns] = args;

const multipleClauses = columns.reduce(
  (oldObject, column) => ({
    ...oldObject,
    [column]: data[column],
  }),
  {}
);

const where = { ...multipleClauses, [field]: value };

const row = data.id
  ? await Database.table(table)
      .where(where)
      .whereNot('id', data.id)
      .first()
  : await Database.table(table)
      .where(where)
      .first();
if (row) {
  throw message;
}

}

and to use:

code: [rule('required'), rule('unique_combination', ['users', 'company_id'])],

you can find more in doc in this link:

Extending Validator


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
```<code>return ICollection<type>
</code>```

The advantage to generic return types, is that you can change the underlying implementation without changing the code that uses it. The advantage to returning the specific type, is you can use more type specific methods.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

Body:
return ICollection<type>

The advantage to generic return types, is that you can change the underlying implementation without changing the code that uses it. The advantage to returning the specific type, is you can use more type specific methods.

OwnerDisplayName: sfossen


问:
Determine whether a row is selected in a DataGridView
I'm looping through a DataGridView, and I need to do this :</p>

```<code> for(int i = 0; i < DGV.Rows.Count - 2; i)
 {
    // if the row is selected
    // do something
 }
</code>```

答:
There's a lot of missing context, but I think you mean just:

```<code>var rows = DGV.Rows;
for (int i = 0; i < rows.Count - 2; i++)
{
    if (rows[i].Selected)
    {
        // do something
    }
}
</code>```

?

Body:
I'm looping through a DataGridView, and I need to do this :

 for(int i = 0; i < DGV.Rows.Count - 2; i)
 {
    // if the row is selected
    // do something
 }

Body:
There's a lot of missing context, but I think you mean just:

var rows = DGV.Rows;
for (int i = 0; i < rows.Count - 2; i++)
{
    if (rows[i].Selected)
    {
        // do something
    }
}

?


问:
DPDK how polling is done?
What I understand about DPDK is that the ring buffer of NIC gets mapped to userspace address and data in there gets processes on a polling basis. (Please correct me if wrong)

For that, how is periodic polling carried out? Is there any process running in the background that periodically causes polling, through API provided by PMD(polling mode driver)?

答:
The polling is done straightforward in a loop, i.e.:

```<code>main() {
    // Init ports
    ...
    // Main loop
    while(!quit_flag) {
        // Receive a burst of packets (poll)
        nb_rx = rte_eth_rx_burst(...);

        // Process packets
        ...

        // Send a burst of packets
        rte_eth_tx_burst(..., nb_rx);
    }
}
</code>```

Sure, it could be done on a separate thread(s) (in DPDK we call them lcores), but the idea stays the same: the application model is up to the developer.

There are lots of examples in the DPDK repo

DPDK also has a few frameworks to facilitate an implementation of an event-driven or pipeline application architecture.

For more details see DPDK Programmers Guide

Title: DPDK how polling is done?

Body:
The polling is done straightforward in a loop, i.e.:

main() {
    // Init ports
    ...
    // Main loop
    while(!quit_flag) {
        // Receive a burst of packets (poll)
        nb_rx = rte_eth_rx_burst(...);

        // Process packets
        ...

        // Send a burst of packets
        rte_eth_tx_burst(..., nb_rx);
    }
}

Sure, it could be done on a separate thread(s) (in DPDK we call them lcores), but the idea stays the same: the application model is up to the developer.

There are lots of examples in the DPDK repo

DPDK also has a few frameworks to facilitate an implementation of an event-driven or pipeline application architecture.

For more details see DPDK Programmers Guide


问:
How to save a table I created with (DT), datatable into a high quality image?
I created a datatable that can be viewed in my "Viewer". If I use export to copy the image or save is as a .png it tends to be really low quality?

My best option has been screenshotting the image and pasting it to my work document where I type out my report, but I know there has to be a better way.

Any advice on what I can do?

答:
You can use the saveWidget function to save the datatable in a html file, then use the webshot package to take a snapshot.

```<code>library(DT)
library(webshot)
dtable <- datatable(iris[1:8,])
html <- "dtable.html"
saveWidget(dtable, html)
webshot(html, "dtableSnapshot.png") # you can also export to pdf
</code>```

Body:
You can use the saveWidget function to save the datatable in a html file, then use the webshot package to take a snapshot.

library(DT)
library(webshot)
dtable <- datatable(iris[1:8,])
html <- "dtable.html"
saveWidget(dtable, html)
webshot(html, "dtableSnapshot.png") # you can also export to pdf


问:
VSCode Extension: How to debug "Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {."
I have created a vscode extension using typescript. Normally, I'd reduce the problem to the smallest possible piece of code, but whenever I try to do that, the problem disappears.

Whenever I try to run the extension (by pressing Ctrl+Shift+P and selecting my extension's command), I get the error: (name changed)

```<code>Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {.
</code>```

Or, in previous versions of the code when I first encountered the error, ...Unexpected token ,.

The error gives no indication of which line or even which file contains the unexpected token. I have tried to run the debugger on the code that loads the extension (vscode devtools), but I couldn't find any obvious "current file" or some such in the call stack.

How do I even begin to debug this?

package.json: (name changed)

```<code>{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "Extension Descripton",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.41.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension-name.start"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension-name.start",
                "title": "Open a Extension Name window"
            }
        ]
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile",
        "test": "node ./out/test/runTest.js"
    },
    "devDependencies": {
        "@types/glob": "^7.1.1",
        "@types/mocha": "^5.2.7",
        "@types/node": "^12.11.7",
        "@types/vscode": "^1.41.0",
        "awesome-typescript-loader": "^5.2.1",
        "glob": "^7.1.5",
        "html-loader": "^0.5.5",
        "mocha": "^6.2.2",
        "tslint": "^5.20.0",
        "typescript": "^3.6.4",
        "vscode-test": "^1.2.2",
        "webpack": "^4.41.2",
        "webpack-cli": "^3.3.9"
    },
    "dependencies": {
        "cerialize": "^0.1.18",
        "ts_common": "file:../ts_common"
    },
    "private": true
}
</code>```

tsconfig.json:

```<code>{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "out",
        "lib": [
            "es2018",
            "dom"
        ],
        "sourceMap": true,
        //"rootDir": "src",
        "typeRoots": ["node_modules/@types"],
        "strict": true,   /* enable all strict type-checking options */
        /* Additional Checks */
        "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "awesomeTypescriptLoaderOptions": {
      "useCache": true,
      "isolatedModules": true,
      //"transpileOnly": true, // This is about a 2x speedup to compilation but disable type errors/warnings
      "reportFiles": [
        "src/**/*.{ts,tsx}"
      ]
    },
    "include": [
      "./src/"
    ]/*,
    "exclude": [
        "node_modules",
        "../ts_common",
        "./dist",
        ".vscode-test"
    ]*/
}
</code>```

答:
I was able to solve my issue by changing the target option in tsconfig.json from es2016 to es5. I did not try any others; es6/es2015 may also work.

I found this by changing around my code basically randomly until I got an error like unexpected token "export", at which point I suspected the target version.

Body:
I have created a vscode extension using typescript. Normally, I'd reduce the problem to the smallest possible piece of code, but whenever I try to do that, the problem disappears.

Whenever I try to run the extension (by pressing Ctrl+Shift+P and selecting my extension's command), I get the error: (name changed)

Activating extension 'undefined_publisher.extension-name' failed: Unexpected token {.

Or, in previous versions of the code when I first encountered the error, ...Unexpected token ,.

The error gives no indication of which line or even which file contains the unexpected token. I have tried to run the debugger on the code that loads the extension (vscode devtools), but I couldn't find any obvious "current file" or some such in the call stack.

How do I even begin to debug this?

package.json: (name changed)

{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "Extension Descripton",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.41.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [
        "onCommand:extension-name.start"
    ],
    "main": "./out/extension.js",
    "contributes": {
        "commands": [
            {
                "command": "extension-name.start",
                "title": "Open a Extension Name window"
            }
        ]
    },
    "scripts": {
        "vscode:prepublish": "npm run compile",
        "compile": "tsc -p ./",
        "watch": "tsc -watch -p ./",
        "pretest": "npm run compile",
        "test": "node ./out/test/runTest.js"
    },
    "devDependencies": {
        "@types/glob": "^7.1.1",
        "@types/mocha": "^5.2.7",
        "@types/node": "^12.11.7",
        "@types/vscode": "^1.41.0",
        "awesome-typescript-loader": "^5.2.1",
        "glob": "^7.1.5",
        "html-loader": "^0.5.5",
        "mocha": "^6.2.2",
        "tslint": "^5.20.0",
        "typescript": "^3.6.4",
        "vscode-test": "^1.2.2",
        "webpack": "^4.41.2",
        "webpack-cli": "^3.3.9"
    },
    "dependencies": {
        "cerialize": "^0.1.18",
        "ts_common": "file:../ts_common"
    },
    "private": true
}

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2016",
        "outDir": "out",
        "lib": [
            "es2018",
            "dom"
        ],
        "sourceMap": true,
        //"rootDir": "src",
        "typeRoots": ["node_modules/@types"],
        "strict": true,   /* enable all strict type-checking options */
        /* Additional Checks */
        "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
        // "noUnusedParameters": true,  /* Report errors on unused parameters. */
    },
    "awesomeTypescriptLoaderOptions": {
      "useCache": true,
      "isolatedModules": true,
      //"transpileOnly": true, // This is about a 2x speedup to compilation but disable type errors/warnings
      "reportFiles": [
        "src/**/*.{ts,tsx}"
      ]
    },
    "include": [
      "./src/"
    ]/*,
    "exclude": [
        "node_modules",
        "../ts_common",
        "./dist",
        ".vscode-test"
    ]*/
}


问:
Python 3.7 MultiThreading strategy
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

```<code>for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]
</code>```

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4

答:
1) Use a threadsafe queue. Queue.FIFOQueue. At the top level define

```<code>my_queue = Queue.FIFOQueue()
parsedData = []
</code>```

2) On the first thread, kick off the data loading

```<code>my_queue.put(DownloadData(x))
</code>```

On the second thread

```<code>if not (my_queue.empty()):
    myData = my_queue.get()
    parsedData.append(ParseData(myData))
</code>```

Title: Python 3.7 MultiThreading strategy

Body:
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4

Body:
1) Use a threadsafe queue. Queue.FIFOQueue. At the top level define

my_queue = Queue.FIFOQueue()
parsedData = []

2) On the first thread, kick off the data loading

my_queue.put(DownloadData(x))

On the second thread

if not (my_queue.empty()):
    myData = my_queue.get()
    parsedData.append(ParseData(myData))


问:
How to send post request in Python for Ant media API
I am trying to write a python HTTP request code to send the data to Ant media server through one of its API. But I unable to send POST request however I was successful in GET requests.

```<code>import requests
url = "http://localhost:5080/LiveApp/rest/broadcast/create"

body12 = {
    "name": "TESTAPIsss",
    "description":"hiiii",
    "type": "streamSource",
    "streamId":"650320906975923279669775",
    "streamUrl": "rlink"
}
headers = {'content-type': 'application/json'}

x = requests.post(url, data=body12, headers=headers)

print(x.text)
</code>```

The error which I am facing is

Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN
   at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 6]

答: This answer is not working anymore.</p>

Body:
I am trying to write a python HTTP request code to send the data to Ant media server through one of its API. But I unable to send POST request however I was successful in GET requests.

import requests
url = "http://localhost:5080/LiveApp/rest/broadcast/create"

body12 = {
    "name": "TESTAPIsss",
    "description":"hiiii",
    "type": "streamSource",
    "streamId":"650320906975923279669775",
    "streamUrl": "rlink"
}
headers = {'content-type': 'application/json'}

x = requests.post(url, data=body12, headers=headers)

print(x.text)

The error which I am facing is

Unrecognized token 'name': was expecting 'null', 'true', 'false' or NaN
   at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 6]

Body: This answer is not working anymore.


问:
# 5 times, where each sentence is separated by a single space
why is this wrong. I do not understand it

Write a function called show_excitement where the string "I am super excited for this course!" is returned exactly 5 times, where each
sentence is separated by a single space. Return the string with
"return". You can only have the string once in your code. Don't just
copy/paste it 5 times into a single variable!

str= "I am super excited for this course!"

for x in range(5):
    str =  str + " "
    print(str)
```

答:
In this case you'd probably want str.join

```<code>def show_excitement():
    return ' '.join(['I am super excited for this course!'] * 5)
</code>```

Example

```<code>>>> show_excitement()
'I am super excited for this course! I am super excited for this course! I am super excited for this course! I am super excited for this course! I am super excited for this course!'
</code>```

Body:
In this case you'd probably want str.join

def show_excitement():
    return ' '.join(['I am super excited for this course!'] * 5)

Example

>>> show_excitement()
'I am super excited for this course! I am super excited for this course! I am super excited for this course! I am super excited for this course! I am super excited for this course!'


问:
Alert dialog doesn't show anything
I have an Alert Dialog and when I press the button to show what I chose, it shows nothing, only the black faded screen like something has to show.

There is my code:

```<code>final AlertDialog.Builder raspunsgresit = new AlertDialog.Builder(Intrebarea644.this);
LayoutInflater factory = LayoutInflater.from(Intrebarea644.this);
final View view = factory.inflate(R.layout.raspuns644, null);
raspunsgresit.setView(view);
if(view.getParent()!=null)
   ((ViewGroup)view.getParent()).removeView(view);
raspunsgresit.setPositiveButton("", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sumthin) {
            }
    });
</code>```

答:
It's just the AlertDialog.Builder. You need to create() the AlertDialog then show() it.
So, your code will look like :

```<code>final AlertDialog.Builder raspunsgresit = new AlertDialog.Builder(Intrebarea644.this);
LayoutInflater factory = LayoutInflater.from(Intrebarea644.this);
final View view = factory.inflate(R.layout.raspuns644, null);
raspunsgresit.setView(view);
if(view.getParent()!=null)
 ((ViewGroup)view.getParent()).removeView(view);
raspunsgresit.setPositiveButton("", new DialogInterface.OnClickListener(){
 public void onClick(DialogInterface dlg, int sumthin){
 }
});
raspunsgresit.create().show();
</code>```

Title: Alert dialog doesn't show anything

Body:
I have an Alert Dialog and when I press the button to show what I chose, it shows nothing, only the black faded screen like something has to show.

There is my code:

final AlertDialog.Builder raspunsgresit = new AlertDialog.Builder(Intrebarea644.this);
LayoutInflater factory = LayoutInflater.from(Intrebarea644.this);
final View view = factory.inflate(R.layout.raspuns644, null);
raspunsgresit.setView(view);
if(view.getParent()!=null)
   ((ViewGroup)view.getParent()).removeView(view);
raspunsgresit.setPositiveButton("", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sumthin) {
            }
    });

Body:
It's just the AlertDialog.Builder. You need to create() the AlertDialog then show() it.
So, your code will look like :

final AlertDialog.Builder raspunsgresit = new AlertDialog.Builder(Intrebarea644.this);
LayoutInflater factory = LayoutInflater.from(Intrebarea644.this);
final View view = factory.inflate(R.layout.raspuns644, null);
raspunsgresit.setView(view);
if(view.getParent()!=null)
 ((ViewGroup)view.getParent()).removeView(view);
raspunsgresit.setPositiveButton("", new DialogInterface.OnClickListener(){
 public void onClick(DialogInterface dlg, int sumthin){
 }
});
raspunsgresit.create().show();


问:
Error at Command Line : 5 Column : 84 Error report - SQL Error: ORA-00917: missing comma 00917. 00000 - "missing
```<code>INSERT INTO CAPDBO.NRP_BATCH_SCHEDULE_QUEUE (
SCHEDULE_QUEUE_ID,
SCHEDULE_ID,
SCHEDULE_NAME,
SERVICE_ID,
SERVICE_NAME,
SERVICE_PARAMETERS,
TIMEOUT_INTERVAL,
STATUS,
TRACE_ID,
ERROR_MESSAGE,
CREAT_DT,
CREAT_USER,
UPD_DT,
UPD_USER
)
values
(
'capdbo.NRP_SCHEDULE_QUEUE_SEQ.nextval',
1,
'CAP_NFORM',
1,
'nrp-warehouse/capNformBatch',
accountingDate=TO_CHAR('YYYY-MM-DD'),
'YYYY-MM-DD',
600,
'PENDING',
null,
null,
to_date(sysdate,'DD-MON-RR'),
'CAPDBO',
to_date(sysdate,'DD-MON-RR'),
'CAPDBO');
</code>```

Error at Command Line : 5 Column : 84 Error report - SQL Error:
  ORA-00917: missing comma
  00917. 00000 -  "missing comma"
  *Cause:

  *Action:

答:
```<code>INSERT INTO CAPDBO.NRP_BATCH_SCHEDULE_QUEUE
( SCHEDULE_QUEUE_ID
, SCHEDULE_ID
, SCHEDULE_NAME
, SERVICE_ID
, SERVICE_NAME
, SERVICE_PARAMETERS
, TIMEOUT_INTERVAL
, STATUS
, TRACE_ID
, ERROR_MESSAGE
, CREAT_DT
, CREAT_USER
, UPD_DT
, UPD_USER
)
VALUES
( capdbo.NRP_SCHEDULE_QUEUE_SEQ.NEXTVAL
, 1
, 'CAP_NFORM'
, 1
, 'nrp-warehouse/capNformBatch'
, 'accountingDate=TO_CHAR(''YYYY-MM-DD'')'
, 600
, 'PENDING'
, NULL
, NULL
, SYSDATE
, 'CAPDBO'
, SYSDATE
, 'CAPDBO'
)
</code>```

Not at all clear what SERVICE_PARAMETERS string is supposed to mean, but in this SQL statement, it's just a string value. To included a single quote inside a string literal, the single quote can be escaped by preceding it with another single quote, e.g. string literal

```<code>'It''s fine'
   ^^
</code>```

evaluates to  "It's fine"

Body:
INSERT INTO CAPDBO.NRP_BATCH_SCHEDULE_QUEUE (
SCHEDULE_QUEUE_ID,
SCHEDULE_ID,
SCHEDULE_NAME,
SERVICE_ID,
SERVICE_NAME,
SERVICE_PARAMETERS,
TIMEOUT_INTERVAL,
STATUS,
TRACE_ID,
ERROR_MESSAGE,
CREAT_DT,
CREAT_USER,
UPD_DT,
UPD_USER
)
values
(
'capdbo.NRP_SCHEDULE_QUEUE_SEQ.nextval',
1,
'CAP_NFORM',
1,
'nrp-warehouse/capNformBatch',
accountingDate=TO_CHAR('YYYY-MM-DD'),
'YYYY-MM-DD',
600,
'PENDING',
null,
null,
to_date(sysdate,'DD-MON-RR'),
'CAPDBO',
to_date(sysdate,'DD-MON-RR'),
'CAPDBO');

Error at Command Line : 5 Column : 84 Error report - SQL Error:
  ORA-00917: missing comma
  00917. 00000 -  "missing comma"
  *Cause:

  *Action:

Body:
INSERT INTO CAPDBO.NRP_BATCH_SCHEDULE_QUEUE
( SCHEDULE_QUEUE_ID
, SCHEDULE_ID
, SCHEDULE_NAME
, SERVICE_ID
, SERVICE_NAME
, SERVICE_PARAMETERS
, TIMEOUT_INTERVAL
, STATUS
, TRACE_ID
, ERROR_MESSAGE
, CREAT_DT
, CREAT_USER
, UPD_DT
, UPD_USER
)
VALUES
( capdbo.NRP_SCHEDULE_QUEUE_SEQ.NEXTVAL
, 1
, 'CAP_NFORM'
, 1
, 'nrp-warehouse/capNformBatch'
, 'accountingDate=TO_CHAR(''YYYY-MM-DD'')'
, 600
, 'PENDING'
, NULL
, NULL
, SYSDATE
, 'CAPDBO'
, SYSDATE
, 'CAPDBO'
)

Not at all clear what SERVICE_PARAMETERS string is supposed to mean, but in this SQL statement, it's just a string value. To included a single quote inside a string literal, the single quote can be escaped by preceding it with another single quote, e.g. string literal

'It''s fine'
   ^^

evaluates to  "It's fine"


问:
CXF Rest service in Websphere 8.5
```<code>>  webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[CXFServlet]: org.apache.cxf.bus.extension.ExtensionException`
        `at org.apache.cxf.bus.extension.Extension.load(Extension.java:114)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.loadAndRegister(ExtensionManagerImpl.java:183)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.processExtension(ExtensionManagerImpl.java:158)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.loadFragment(ExtensionManagerImpl.java:151)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:143)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:96)
        at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:129)
        at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:41)
        at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:37)
        at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:33)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.loadBusNoConfig(CXFNonSpringServlet.java:45)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.loadBus(CXFNonSpringServlet.java:38)
        at org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet.loadBus(CXFNonSpringJaxrsServlet.java:69)
        at org.apache.cxf.transport.servlet.AbstractCXFServlet.init(AbstractCXFServlet.java:84)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:344)
        at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:168)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:636)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
        at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
        at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
        at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
        at com.ibm.controller.InterceptFilter.doFilter(InterceptFilter.java:28)
        at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
        at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:967)
        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1107)
        at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3951)
        at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
        at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1014)
        at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
        at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
        at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
        at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
        at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
        at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
        at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
        at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
        at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
        at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
        at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
        at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
Caused by: java.lang.InstantiationException: org.apache.cxf.wstx_msv_validation.WoodstoxValidationImpl
        at java.lang.J9VMInternals.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1781)
        at org.apache.cxf.bus.extension.Extension.load(Extension.java:110)
        ... 44 more>
</code>```

Below JARS i have used

cxf-core-3.1.6.jar

cxf-rt-frontend-jaxrs-3.1.6.jar

cxf-rt-transports-http-3.1.6.jar

javax.ws.rs-api-2.0.1.jar

```<code> <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.ibm.services.rest.Echo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</code>```

can anyone help me to fix this.. i am using CXF 3.16, WAS 8.5, JDK 1.7. WoodstoxValidationImpl is availabe in the cxf-core jar but dont why i am getting this error

答:
You may want to check with the CXF users mailing list to see if the community has seen this before or open an JIRA issue.  In short, I don't see how the WoodstoxValidationImpl class would fail to initialize - it's constructor includes a try/catch block that handles all Throwables.  Hopefully the CXF community will be able to provide more assistance.

I would advise upgrading to WebSphere v9 or WebSphere Liberty before going too far down this path.  WebSphere v8.5 ships with the JAX-RS 1.1 APIs and there is no way to "turn them off" so the only way you will be able to load your JAX-RS 2.0 APIs from the jar in your app would be to use parent-last classloading (or other such classloading hacks).  WAS v9 and Liberty both provide the 2.0 (and Liberty also provides 2.1) APIs, but more importantly, they both allow you to disable the APIs if you want.  Also, FWIW, both WAS v9 and Liberty use CXF as the underlying JAX-RS implementation, so you can use a thinner WAR and still get the JAX-RS implementation you are looking for.

HTH, Andy

Title: CXF Rest service in Websphere 8.5

Body:
>  webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[CXFServlet]: org.apache.cxf.bus.extension.ExtensionException`
        `at org.apache.cxf.bus.extension.Extension.load(Extension.java:114)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.loadAndRegister(ExtensionManagerImpl.java:183)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.processExtension(ExtensionManagerImpl.java:158)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.loadFragment(ExtensionManagerImpl.java:151)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:143)
        at org.apache.cxf.bus.extension.ExtensionManagerImpl.load(ExtensionManagerImpl.java:96)
        at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:129)
        at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:41)
        at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:37)
        at org.apache.cxf.bus.CXFBusFactory.createBus(CXFBusFactory.java:33)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.loadBusNoConfig(CXFNonSpringServlet.java:45)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.loadBus(CXFNonSpringServlet.java:38)
        at org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet.loadBus(CXFNonSpringJaxrsServlet.java:69)
        at org.apache.cxf.transport.servlet.AbstractCXFServlet.init(AbstractCXFServlet.java:84)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:344)
        at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:168)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:636)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
        at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
        at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
        at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
        at com.ibm.controller.InterceptFilter.doFilter(InterceptFilter.java:28)
        at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
        at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:967)
        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1107)
        at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3951)
        at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
        at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1014)
        at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
        at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
        at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
        at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
        at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
        at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
        at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
        at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
        at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
        at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
        at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
        at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
Caused by: java.lang.InstantiationException: org.apache.cxf.wstx_msv_validation.WoodstoxValidationImpl
        at java.lang.J9VMInternals.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1781)
        at org.apache.cxf.bus.extension.Extension.load(Extension.java:110)
        ... 44 more>

Below JARS i have used

cxf-core-3.1.6.jar

cxf-rt-frontend-jaxrs-3.1.6.jar

cxf-rt-transports-http-3.1.6.jar

javax.ws.rs-api-2.0.1.jar

 <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.ibm.services.rest.Echo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>

can anyone help me to fix this.. i am using CXF 3.16, WAS 8.5, JDK 1.7. WoodstoxValidationImpl is availabe in the cxf-core jar but dont why i am getting this error


问:
reducing the weighting of one of the x variables in glmnet
I can create a model using glmnet.
However if I know beforehand that the contribution of one variable is weak (say x[,1]) how can I reduce its contribution in the glmnet function?

```<code>library(glmnet)
x <- matrix(rnorm(100*20),100,20)
y <- rnorm(100)
fit1 <- glmnet(x,y)
print(fit1)
coef(fit1,s=0.01) # extract coefficients at a single value of lambda
predict(fit1,newx=x[1:10,],s=c(0.01,0.005)) # make predictions
</code>```

答:
This is a bit of a hack, but because penalized regression approaches assume that the variables are all scaled equally, shrinking the scale of a predictor variable should require a larger value of the parameter to characterize the same magnitude of effect, and hence a greater penalty, e.g.

```<code>x2 <- scale(x)
x2[,1] <- x2[,1]/100
fit2 <- glmnet(x2,y,standardize=FALSE)
coef(fit2,s=0.01)
</code>```

shows that the first variable has been eliminated. (You have to force glmnet not to re-standardize the x-variables internally; you should make sure you've scaled the predictors yourself ...)

Body:
I can create a model using glmnet.
However if I know beforehand that the contribution of one variable is weak (say x[,1]) how can I reduce its contribution in the glmnet function?

library(glmnet)
x <- matrix(rnorm(100*20),100,20)
y <- rnorm(100)
fit1 <- glmnet(x,y)
print(fit1)
coef(fit1,s=0.01) # extract coefficients at a single value of lambda
predict(fit1,newx=x[1:10,],s=c(0.01,0.005)) # make predictions

Body:
This is a bit of a hack, but because penalized regression approaches assume that the variables are all scaled equally, shrinking the scale of a predictor variable should require a larger value of the parameter to characterize the same magnitude of effect, and hence a greater penalty, e.g.

x2 <- scale(x)
x2[,1] <- x2[,1]/100
fit2 <- glmnet(x2,y,standardize=FALSE)
coef(fit2,s=0.01)

shows that the first variable has been eliminated. (You have to force glmnet not to re-standardize the x-variables internally; you should make sure you've scaled the predictors yourself ...)