问:
Adding a index to collection using EF 4.1 and XAML (For a highscore table)
I have a webservice I call from a WP7 app. I get a list of high scores in a table (name/score).. What is the simpliest way to add a 3rd column on the far left which is simply the row?

Do I need to add a property to the entity? Is there someway to get the row #?

I tried these things below with no success..

```<code> [OperationContract]
    public List<DMHighScore> GetScores()
    {
        using (var db = new DMModelContainer())
        {
            //  return db.DMHighScores.ToList();

            var collOrderedHighScoreItem = (from o in db.DMHighScores
                                            orderby o.UserScore ascending
                                            select new
                                            {
                                                o.UserName,
                                                o.UserScore
                                            }).Take(20);

            var collOrderedHighScoreItem2 = collOrderedHighScoreItem.AsEnumerable().Select((x, i) => new DMHighScoreDTO
            {
                UserName = x.UserName,
                UserScore = x.UserScore
            }).ToList();

        }

    }
  [DataContract]
public class DMHighScoreDTO
{
    int Rank;
    string UserName;
    string UserScore;
}
</code>```

答:
So lets assume you want to load top 100 users in leaderboard and you want to have their rank included:</p>

```<code>[OperationContract]
public List<ScoreDto> GetTop100()
{
    // Linq to entities query
    var query = (from u from context.Users
                 order by u.Score
                 select new
                     {
                         u.Name,
                         u.Score
                     }).Take(100);

    // Linq to objects query from working on 100 records loaded from DB
    // Select with index doesn't work in linq to entities
    var data = query.AsEnumerable().Select((x, i) => new ScoreDto
        {
            Rank = i + 1,
            Name = x.Name,
            Score = x.Score
        }).ToList();

    return data;
 }
</code>```

Body:
I have a webservice I call from a WP7 app. I get a list of high scores in a table (name/score).. What is the simpliest way to add a 3rd column on the far left which is simply the row?

Do I need to add a property to the entity? Is there someway to get the row #?

I tried these things below with no success..

 [OperationContract]
    public List<DMHighScore> GetScores()
    {
        using (var db = new DMModelContainer())
        {
            //  return db.DMHighScores.ToList();

            var collOrderedHighScoreItem = (from o in db.DMHighScores
                                            orderby o.UserScore ascending
                                            select new
                                            {
                                                o.UserName,
                                                o.UserScore
                                            }).Take(20);

            var collOrderedHighScoreItem2 = collOrderedHighScoreItem.AsEnumerable().Select((x, i) => new DMHighScoreDTO
            {
                UserName = x.UserName,
                UserScore = x.UserScore
            }).ToList();

        }

    }
  [DataContract]
public class DMHighScoreDTO
{
    int Rank;
    string UserName;
    string UserScore;
}

Body:
So lets assume you want to load top 100 users in leaderboard and you want to have their rank included:

[OperationContract]
public List<ScoreDto> GetTop100()
{
    // Linq to entities query
    var query = (from u from context.Users
                 order by u.Score
                 select new
                     {
                         u.Name,
                         u.Score
                     }).Take(100);

    // Linq to objects query from working on 100 records loaded from DB
    // Select with index doesn't work in linq to entities
    var data = query.AsEnumerable().Select((x, i) => new ScoreDto
        {
            Rank = i + 1,
            Name = x.Name,
            Score = x.Score
        }).ToList();

    return data;
 }


来源: stackexchange

问:
How to improve single insert performance in oracle
In my business case, I need insert one row and can't use batch insert  . So I want to know what the throughput can made by Oracle. I try these ways:

Effective way

I use multi-thread, each thread owns one connection to insert data

I use ssd to store oracle datafile

Ineffective way

I use multi table to store data in one schema

I use table partition

I use multi schema to store data

Turn up data file block size

Use append hint in insert SQL

In the end the best TPS is 1w/s+

Other:

Oracle 11g

Single insert data size 1k

CPU i7, 64GB memory

答:
Oracle is highly optimized for anything from one row inserts to batches of hundreds of rows.  You do not mention whether you are having performance problems with this one row insert nor how long the insert takes.  For such a simple operation, you don't need to worry about any of those details.  If you have thousands of web-based users inserting one row into a table every minute, no problem.  If you are committing your work at the appropriate time, and you don't have a huge number of indexes, a single row insert should not take more than a few milliseconds.

In SQL*Plus try the commands

```<code>set autotrace on explain statistics
set timing on
</code>```

and run your insert statement.

Edit your question to include the results of the explain plan.  And be sure to indent the results 4 spaces.

ContentLicense: CC BY-SA 4.0

Body:
Oracle is highly optimized for anything from one row inserts to batches of hundreds of rows.  You do not mention whether you are having performance problems with this one row insert nor how long the insert takes.  For such a simple operation, you don't need to worry about any of those details.  If you have thousands of web-based users inserting one row into a table every minute, no problem.  If you are committing your work at the appropriate time, and you don't have a huge number of indexes, a single row insert should not take more than a few milliseconds.

In SQL*Plus try the commands

set autotrace on explain statistics
set timing on

and run your insert statement.

Edit your question to include the results of the explain plan.  And be sure to indent the results 4 spaces.


问:
How can I grab the .pdf files from source to copy it under daily folder in destination?
click to see Folder directory image How can I grab the .pdf files from source to copy it under daily folder in destination? There are multiple {project folders} and each project folder need to copy to their corresponding destination.

These are my folder directory:

Source Example: root: {project folder}/.pdf   ,     {project folder1}/.pdf   ,    {project folder2}/.pdf   …….

Destination Example: root: {project folder}/daily folder/.pdf         ,          {project folder1}/daily folder/.pdf  ,         {project folder2}/daily folder/.pdf  …..

```<code> static void Main(string[] args)
        {
            CopyFolder(@"C:\Desktop\Source\pdf-reports", @"C:\Desktop\Destination\Parks");
            Console.ReadLine();
    }

    static public void CopyFolder(string sourceFolder, string destFolder)
        {
        if (!Directory.Exists(destFolder))
                Directory.CreateDirectory(destFolder);
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(destFolder, name);
                File.Copy(file, dest);
            }
            string[] folders = Directory.GetDirectories(sourceFolder, "l*", SearchOption.TopDirectoryOnly);

        foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                string dest = Path.Combine(destFolder, name);
                CopyFolder(folder, dest);
            }
</code>```

答:
Ok here it is.

```<code>Imports System.IO

'get the list of all pdf files from the source folder'
Dim FileList() As String = Directory.GetFiles("Replace for Source Folder", "*.pdf")
Dim FileName As String

'Set the root of the destination folder and create a new folder using as name the current date'
Dim DestPath As String = "Replace for Destination Folder" & DateTime.Now.ToString("yyyy-MM-dd")
Dim DestFolder As DirectoryInfo = Directory.CreateDirectory(DestPath)

'go through each of the files and move those one by one'
For F = 0 To FileList.Length - 1
    FileName = Path.GetFileName(FileList(F))
    File.Move(FileList(F), DestPath & "\" & FileName.toString)
Next
</code>```

`

Body:
click to see Folder directory image How can I grab the .pdf files from source to copy it under daily folder in destination? There are multiple {project folders} and each project folder need to copy to their corresponding destination.

These are my folder directory:

Source Example: root: {project folder}/.pdf   ,     {project folder1}/.pdf   ,    {project folder2}/.pdf   …….

Destination Example: root: {project folder}/daily folder/.pdf         ,          {project folder1}/daily folder/.pdf  ,         {project folder2}/daily folder/.pdf  …..

 static void Main(string[] args)
        {
            CopyFolder(@"C:\Desktop\Source\pdf-reports", @"C:\Desktop\Destination\Parks");
            Console.ReadLine();
    }

    static public void CopyFolder(string sourceFolder, string destFolder)
        {
        if (!Directory.Exists(destFolder))
                Directory.CreateDirectory(destFolder);
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(destFolder, name);
                File.Copy(file, dest);
            }
            string[] folders = Directory.GetDirectories(sourceFolder, "l*", SearchOption.TopDirectoryOnly);

        foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                string dest = Path.Combine(destFolder, name);
                CopyFolder(folder, dest);
            }

Body:
Ok here it is.

Imports System.IO

'get the list of all pdf files from the source folder'
Dim FileList() As String = Directory.GetFiles("Replace for Source Folder", "*.pdf")
Dim FileName As String

'Set the root of the destination folder and create a new folder using as name the current date'
Dim DestPath As String = "Replace for Destination Folder" & DateTime.Now.ToString("yyyy-MM-dd")
Dim DestFolder As DirectoryInfo = Directory.CreateDirectory(DestPath)

'go through each of the files and move those one by one'
For F = 0 To FileList.Length - 1
    FileName = Path.GetFileName(FileList(F))
    File.Move(FileList(F), DestPath & "\" & FileName.toString)
Next

`


问:
Add row values for each groupby column in Pandas DataFrame
I have a dataset that have binary values for flags for each sinid like this:

```<code>>>> df = pd.DataFrame({'sinid':['abc','def','ghi','abc','ghi'],'flag1':[1,1,0,0,1],'flag2':[1,0,1,0,0]})
>>> df
  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      0      1
3   abc      0      0
4   ghi      1      0
</code>```

I want to add values for each sinid, I think I need groupby but not sure how to use it...

This is the expected result:

```<code>  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      1      1
</code>```

答:
Just summarize grouped dataframe:

df.groupby('sinid').sum()

```<code>    flag1   flag2
sinid
abc     1   1
def     1   0
ghi     1   1
</code>```

Body:
I have a dataset that have binary values for flags for each sinid like this:

>>> df = pd.DataFrame({'sinid':['abc','def','ghi','abc','ghi'],'flag1':[1,1,0,0,1],'flag2':[1,0,1,0,0]})
>>> df
  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      0      1
3   abc      0      0
4   ghi      1      0

I want to add values for each sinid, I think I need groupby but not sure how to use it...

This is the expected result:

  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      1      1

Body:
Just summarize grouped dataframe:

df.groupby('sinid').sum()

    flag1   flag2
sinid
abc     1   1
def     1   0
ghi     1   1


问:
How to define css variables in style attribute in React and TypeScript
I want to define jsx like this:

```<code><table style={{'--length': array.lenght}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>
</code>```

and I use --length in CSS, I also have cells that have --count that shows count using CSS pseudo selector (using the counter hack).

but typescript throws error:

```<code>TS2326: Types of property 'style' are incompatible.
  Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
    Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.
</code>```

is it possible to change type of style attribute to accept CSS variable (custom properties) or is there a way to force any on style object?

答:
You can add a type assertion to the variable. i.e. {['--css-variable' as any]: value }

```<code><table style={{['--length' as any]: array.length}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>
</code>```

Body:
I want to define jsx like this:

{array}

and I use --length in CSS, I also have cells that have --count that shows count using CSS pseudo selector (using the counter hack).

but typescript throws error:

TS2326: Types of property 'style' are incompatible.
  Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
    Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.

is it possible to change type of style attribute to accept CSS variable (custom properties) or is there a way to force any on style object?

Body:
You can add a type assertion to the variable. i.e. {['--css-variable' as any]: value }

<table style={{['--length' as any]: array.length}}>
   <tbody>
      <tr>{array}</tr>
   </tbody>
</table>


问:
How to use grep to extract ip adresses and date/time strings from log file?
I have a log file that looks like this:

```<code>May 25 05:34:16 server sshd[1203]: Received disconnect from 192.0.2.2 port 39102:11
May 25 05:34:16 server sshd[1203]: Disconnected from 192.0.2.1 port 39102
</code>```

Now i want to extract all of the ip addresses and the date/time strings at the beginning using grep. I already know how to get the ips:

```<code>grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' /log.txt
</code>```

and the dates/times:

```<code>grep -o '[A-Z][a-z][a-z] [0-3][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]' /log.txt
</code>```

but i don't know how to get both at the same time in a format like:

```<code>May 25 05:34:16 192.0.2.1
</code>```

I've read something like:

```<code> grep -oE 'match1|match2' /log.txt
</code>```

but that doesn't seem to work.

Body:
I have a log file that looks like this:

May 25 05:34:16 server sshd[1203]: Received disconnect from 192.0.2.2 port 39102:11
May 25 05:34:16 server sshd[1203]: Disconnected from 192.0.2.1 port 39102

Now i want to extract all of the ip addresses and the date/time strings at the beginning using grep. I already know how to get the ips:

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' /log.txt

and the dates/times:

grep -o '[A-Z][a-z][a-z] [0-3][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]' /log.txt

but i don't know how to get both at the same time in a format like:

May 25 05:34:16 192.0.2.1

I've read something like:

 grep -oE 'match1|match2' /log.txt

but that doesn't seem to work.

Body:
You could use your 2 patterns in a capturing group and use those in the replacement using sed:

sed -i -E 's#^([A-Z][a-z][a-z] [0-3][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]).* ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*$#\1 \2#g' log.txt

That will match:

^ Start of string

([A-Z][a-z][a-z] [0-3][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]) Your date/time like pattern

.* Match any char 0+ times

([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) Match space followed your ip like pattern

.* Match any char 0+ times

$ End of string

Result

May 25 05:34:16 192.0.2.2
May 25 05:34:16 192.0.2.1


问:
need help connecting to mysql database
0

hi need to connect to a mysql server i have set up on godaddy.com

my code is

```<code>var dbcon : IDbConnection; //port is 3303
var connectionString : String = "Server=xxxxx.xx.xx.x; Uid=lxxxx; Pwd=xxxx; Database=lxxx;";

dbcon = new SqlConnection(connectionString);
dbcon.Open();
</code>```

however my connection is rejected, i suspect i need to put in a port number.can anyone tell me how would i specify a port number in my connection string?? thx

答:
```<code>String = "Server=xxxxx.xx.xx.x; Uid=lxxxx; Pwd=xxxx; Database=lxxx; Port=3303;";
</code>```

Found here: http://www.connectionstrings.com/mysql

ContentLicense: CC BY-SA 3.0

Title: need help connecting to mysql database

Body:
0

hi need to connect to a mysql server i have set up on godaddy.com

my code is

var dbcon : IDbConnection; //port is 3303
var connectionString : String = "Server=xxxxx.xx.xx.x; Uid=lxxxx; Pwd=xxxx; Database=lxxx;";

dbcon = new SqlConnection(connectionString);
dbcon.Open();

however my connection is rejected, i suspect i need to put in a port number.can anyone tell me how would i specify a port number in my connection string?? thx

Body:
String = "Server=xxxxx.xx.xx.x; Uid=lxxxx; Pwd=xxxx; Database=lxxx; Port=3303;";

Found here: http://www.connectionstrings.com/mysql


问:
Laravel Excel Maatwebsite 3.1 Row Validation Not Working
I'm trying to find duplicated rows on the import array using the WithValidation concern (will use SkipsOnError to remove duplicated rows later). But the validation set in my import class to find the duplicated rows doesn't seems to work.
No error is returned and all rows are imported to database when I upload an excel file (just a column with no headers)  containing duplicated data

```<code><?php

namespace App\Imports;

use App\Contactlist;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

class ContactsImport implements ToModel, WithValidation
{
    use Importable;

    private $data;

    public function __construct(array $data = [])
    {
        $this->data = $data;
    }

    public function model(array $row)
    {
        if (!isset($row[0])) {
            return null;
        }

        return new Contactlist(array_merge([
            'nums'   => $row[0],
        ], $this->data));

    }

    public function rules(): array
    {
        return [
            //find duplicate records
            '0.*' => 'distinct',
            //'*.0' => 'distinct' Tried this also
        ];
  }

}
</code>```

code snippet of my controller

```<code>$data = [
            'contact_id' => $contact->id,
        ];

        Excel::import(new ContactsImport($data), request()->file('contact_file'));
</code>```

答:
```<code>class ExempleImport implements ToCollection, WithHeadingRow
{

   /** @var Collection */
   public $collection;

  /**
   * @param Collection $collection
   */
  public function collection(Collection $collection)
  {
    $this->collection = $collection->transform(function ($row) {

        $this->validationFields($row);

        return [
            'curso'             => $row['curso'],
            'marca'             => $row['marca'],
            'status'            => $row['status_do_curso'],
            'emissor'           => $row['emissor_cliente'],
            'nome_da_conta'     => $row['nome_da_conta'],
        ];
    });
  }

  public function validationFields( $row )
  {

      $customMessages = [
          'required' => 'O campo :attribute deve estar preenchido'
      ];

      Validator::make($row->toArray(), [
          'curso' => 'required',
          'marca' => 'required',
          'status_do_curso' => 'required',
          'emissor_cliente' => 'required',
          'nome_da_conta' => 'required',
      ], $customMessages)->validate();
 }
}
</code>```

In your controller

```<code>    $exampleImport = new ExampleImport;

   try{
        Excel::import( $exampleImport, $updateFile);
    }catch ( ValidationException $e ){

        return response()->json(['success'=>'errorList','message'=> $e->errors()]);
    }
</code>```

Body:
I'm trying to find duplicated rows on the import array using the WithValidation concern (will use SkipsOnError to remove duplicated rows later). But the validation set in my import class to find the duplicated rows doesn't seems to work.
No error is returned and all rows are imported to database when I upload an excel file (just a column with no headers)  containing duplicated data

<?php

namespace App\Imports;

use App\Contactlist;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

class ContactsImport implements ToModel, WithValidation
{
    use Importable;

    private $data;

    public function __construct(array $data = [])
    {
        $this->data = $data;
    }

    public function model(array $row)
    {
        if (!isset($row[0])) {
            return null;
        }

        return new Contactlist(array_merge([
            'nums'   => $row[0],
        ], $this->data));

    }

    public function rules(): array
    {
        return [
            //find duplicate records
            '0.*' => 'distinct',
            //'*.0' => 'distinct' Tried this also
        ];
  }

}

code snippet of my controller

$data = [
            'contact_id' => $contact->id,
        ];

        Excel::import(new ContactsImport($data), request()->file('contact_file'));

Body:
class ExempleImport implements ToCollection, WithHeadingRow
{

   /** @var Collection */
   public $collection;

  /**
   * @param Collection $collection
   */
  public function collection(Collection $collection)
  {
    $this->collection = $collection->transform(function ($row) {

        $this->validationFields($row);

        return [
            'curso'             => $row['curso'],
            'marca'             => $row['marca'],
            'status'            => $row['status_do_curso'],
            'emissor'           => $row['emissor_cliente'],
            'nome_da_conta'     => $row['nome_da_conta'],
        ];
    });
  }

  public function validationFields( $row )
  {

      $customMessages = [
          'required' => 'O campo :attribute deve estar preenchido'
      ];

      Validator::make($row->toArray(), [
          'curso' => 'required',
          'marca' => 'required',
          'status_do_curso' => 'required',
          'emissor_cliente' => 'required',
          'nome_da_conta' => 'required',
      ], $customMessages)->validate();
 }
}

In your controller

    $exampleImport = new ExampleImport;

   try{
        Excel::import( $exampleImport, $updateFile);
    }catch ( ValidationException $e ){

        return response()->json(['success'=>'errorList','message'=> $e->errors()]);
    }


问:
How to spread one column into two based on ID
I would like to spread one column of my dataframe into two columns based on an ID variable.

My data looks like this

```<code>df = data.frame(ID = c("M1", "M2", "M2", "M3", "M4", "M4", "M5"),
                Core = c("A", "A","B","B","A","B","A"))

> df
  ID Core
1 M1    A
2 M2    A
3 M2    B
4 M3    B
5 M4    A
6 M4    B
7 M5    A

</code>```

I would like to make the "Core" column into two based on the "ID" so there are no duplicate IDs. I would like it to look like this:

```<code>  ID CoreA CoreB
1 M1     1     0
2 M2     1     1
3 M3     0     1
4 M4     1     1
5 M5     1     0
</code>```

I'm sure there is an easy solution but I am stumped.

答:
An option would be spread

```<code>library(tidyverse)
df %>%
   mutate(n = 1, Core = str_c("Core", Core)) %>%
   spread(Core, n, fill = 0)
#   ID CoreA CoreB
#1 M1     1     0
#2 M2     1     1
#3 M3     0     1
#4 M4     1     1
#5 M5     1     0
</code>```

Or with data.table

```<code>library(data.table)
dcast(setDT(df), ID ~ paste0("Core", Core), length)
</code>```

Body:
I would like to spread one column of my dataframe into two columns based on an ID variable.

My data looks like this

df = data.frame(ID = c("M1", "M2", "M2", "M3", "M4", "M4", "M5"),
                Core = c("A", "A","B","B","A","B","A"))

> df
  ID Core
1 M1    A
2 M2    A
3 M2    B
4 M3    B
5 M4    A
6 M4    B
7 M5    A

I would like to make the "Core" column into two based on the "ID" so there are no duplicate IDs. I would like it to look like this:

  ID CoreA CoreB
1 M1     1     0
2 M2     1     1
3 M3     0     1
4 M4     1     1
5 M5     1     0

I'm sure there is an easy solution but I am stumped.

Body:
An option would be spread

library(tidyverse)
df %>%
   mutate(n = 1, Core = str_c("Core", Core)) %>%
   spread(Core, n, fill = 0)
#   ID CoreA CoreB
#1 M1     1     0
#2 M2     1     1
#3 M3     0     1
#4 M4     1     1
#5 M5     1     0

Or with data.table

library(data.table)
dcast(setDT(df), ID ~ paste0("Core", Core), length)


问:
NLP - How to add more features?
I want to use a sklearn classifier to train a model to classify data entries (yes,no) using a text feature (content), a numerical feature (population) and a categorical feature (location).

The model below is using only the text data to classify each entry. The text is converted with TF-IDF into a sparse matrix before being imported into the classifier.

Is there a way to add/use also the other features? These features are not in sparse matrix format so not sure how to combine them with the text sparse matrix.

    #import libraries
    import string, re, nltk
    import pandas as pd
    from pandas import Series, DataFrame
    from nltk.corpus import stopwords
    from nltk.stem.porter import PorterStemmer
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_extraction.text import TfidfTransformer
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import classification_report
    from sklearn.pipeline import Pipeline

    # read data and remove empty lines
    dataset = pd.read_csv('sample_data.txt',
                           sep='\t',
                           names=['content','location','population','target'])
                           .dropna(how='all')
                           .dropna(subset=['target'])

    df = dataset[1:]

    #reset dataframe index
    df.reset_index(inplace = True)

    #add an extra column which is the length of text
    df['length'] = df['content'].apply(len)

    #create a dataframe that contains only two columns the text and the target class
    df_cont = df.copy()
    df_cont = df_cont.drop(
        ['location','population','length'],axis = 1)

    # function that takes in a string of text, removes all punctuation, stopwords and returns a list of cleaned text

    def text_process(mess):
        # lower case for string
        mess = mess.lower()

        # check characters and removes URLs
       nourl = re.sub(r'http\S+', ' ', mess)

        # check characters and removes punctuation
        nopunc = [char for char in nourl if char not in string.punctuation]

        # join the characters again to form the string and removes numbers
        nopunc = ''.join([i for i in nopunc if not i.isdigit()])

        # remove stopwords
        return [ps.stem(word) for word in nopunc.split() if word not in set(stopwords.words('english'))]

    #split the data in train and test set and train/test the model

    cont_train, cont_test, target_train, target_test = train_test_split(df_cont['content'],df_cont['target'],test_size = 0.2,shuffle = True, random_state = 1)

    pipeline = Pipeline([('bag_of_words',CountVectorizer(analyzer=text_process)),
                         ('tfidf',TfidfTransformer()),
                         ('classifier',MultinomialNB())])

    pipeline.fit(cont_train,target_train)
    predictions = pipeline.predict(cont_test)

    print(classification_report(predictions,target_test))

```

The model is expected to return the following: accuracy, precision, recall ,f1-score

答: It doesn't seem like we can directly encode text as a feature. So you probably need to normalize it. You can pick one of the text rows and set it as a standard. Use TFIDF to calculate the match score between your standard text and the text for each row. You can then encode that percentage as a feature. I realize it is a very roundabout way to encode, but depending on the text you choose as a standard it may work.</p>

Title: NLP - How to add more features?

Body:
I want to use a sklearn classifier to train a model to classify data entries (yes,no) using a text feature (content), a numerical feature (population) and a categorical feature (location).

The model below is using only the text data to classify each entry. The text is converted with TF-IDF into a sparse matrix before being imported into the classifier.

Is there a way to add/use also the other features? These features are not in sparse matrix format so not sure how to combine them with the text sparse matrix.

    #import libraries
    import string, re, nltk
    import pandas as pd
    from pandas import Series, DataFrame
    from nltk.corpus import stopwords
    from nltk.stem.porter import PorterStemmer
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_extraction.text import TfidfTransformer
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import classification_report
    from sklearn.pipeline import Pipeline

    # read data and remove empty lines
    dataset = pd.read_csv('sample_data.txt',
                           sep='\t',
                           names=['content','location','population','target'])
                           .dropna(how='all')
                           .dropna(subset=['target'])

    df = dataset[1:]

    #reset dataframe index
    df.reset_index(inplace = True)

    #add an extra column which is the length of text
    df['length'] = df['content'].apply(len)

    #create a dataframe that contains only two columns the text and the target class
    df_cont = df.copy()
    df_cont = df_cont.drop(
        ['location','population','length'],axis = 1)

    # function that takes in a string of text, removes all punctuation, stopwords and returns a list of cleaned text

    def text_process(mess):
        # lower case for string
        mess = mess.lower()

        # check characters and removes URLs
       nourl = re.sub(r'http\S+', ' ', mess)

        # check characters and removes punctuation
        nopunc = [char for char in nourl if char not in string.punctuation]

        # join the characters again to form the string and removes numbers
        nopunc = ''.join([i for i in nopunc if not i.isdigit()])

        # remove stopwords
        return [ps.stem(word) for word in nopunc.split() if word not in set(stopwords.words('english'))]

    #split the data in train and test set and train/test the model

    cont_train, cont_test, target_train, target_test = train_test_split(df_cont['content'],df_cont['target'],test_size = 0.2,shuffle = True, random_state = 1)

    pipeline = Pipeline([('bag_of_words',CountVectorizer(analyzer=text_process)),
                         ('tfidf',TfidfTransformer()),
                         ('classifier',MultinomialNB())])

    pipeline.fit(cont_train,target_train)
    predictions = pipeline.predict(cont_test)

    print(classification_report(predictions,target_test))

The model is expected to return the following: accuracy, precision, recall ,f1-score


答:
This works:</p>

```<code>df.groupby(['sinid'])['flag1', 'flag2'].sum().reset_index()

  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      1      1
</code>```

Title: Add row values for each groupby column in Pandas DataFrame

Body:
This works:

df.groupby(['sinid'])['flag1', 'flag2'].sum().reset_index()

  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      1      1


问:
xorm example not working: "runtime error: invalid memory address or nil pointer dereference"
Based on this example i tried to write a program that would return some data from a database. Unfortunately, (more-or-less) the same program structure causes memory errors here err := orm.Find(&sensorDataEntry) according to runtime console output.

What am i missing here? Both example and my program has the slice created using make() and uses reference in Find() method.

Code in question:

```<code>package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
    //"database/sql"
    "github.com/go-xorm/xorm"

)

var orm *xorm.Engine

func newRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/sensorentries", GetSensorEntriesHandler).Methods("GET")

    return r
}

type SensorDataEntry struct {
    id int `xorm:"int"`
    sensor_id string `xorm:"varchar(32)"`
    key string `xorm:"varchar(128)"`
    value float64 `xorm:"numeric(20,2)"`
    created_at time.Time `xorm:"timestamp"`
}

func main() {
    connString := "host=server.lan user=x password=x dbname=testdb sslmode=disable"
    orm, err := xorm.NewEngine("postgres", connString)
    //orm.ShowSQL(true)

    if err != nil {
        println(err)
        return
    }

    if err = orm.Sync2(SensorDataEntry{}); err != nil {
        return
    }

    r := newRouter()
    http.ListenAndServe(":8080", r)
}

func GetSensorEntriesHandler(resp http.ResponseWriter, req *http.Request) {
    sensorDataEntry := make([]SensorDataEntry, 0)
    err := orm.Find(&sensorDataEntry)

    if err != nil {
        println(err)
    }

    fmt.Println(sensorDataEntry)

    fmt.Fprintf(resp, "return text")
}
</code>```

答:
As noted by mkopriva, the problem was using the same variable name for assignment.

Solution for the problem was:

instead of

```<code>orm, err := xorm.NewEngine("postgres", connString)
</code>```

use

```<code>var err error
orm, err = xorm.NewEngine("postgres", connString)
</code>```

Body:
Based on this example i tried to write a program that would return some data from a database. Unfortunately, (more-or-less) the same program structure causes memory errors here err := orm.Find(&sensorDataEntry) according to runtime console output.

What am i missing here? Both example and my program has the slice created using make() and uses reference in Find() method.

Code in question:

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
    //"database/sql"
    "github.com/go-xorm/xorm"

)

var orm *xorm.Engine

func newRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/sensorentries", GetSensorEntriesHandler).Methods("GET")

    return r
}

type SensorDataEntry struct {
    id int `xorm:"int"`
    sensor_id string `xorm:"varchar(32)"`
    key string `xorm:"varchar(128)"`
    value float64 `xorm:"numeric(20,2)"`
    created_at time.Time `xorm:"timestamp"`
}

func main() {
    connString := "host=server.lan user=x password=x dbname=testdb sslmode=disable"
    orm, err := xorm.NewEngine("postgres", connString)
    //orm.ShowSQL(true)

    if err != nil {
        println(err)
        return
    }

    if err = orm.Sync2(SensorDataEntry{}); err != nil {
        return
    }

    r := newRouter()
    http.ListenAndServe(":8080", r)
}

func GetSensorEntriesHandler(resp http.ResponseWriter, req *http.Request) {
    sensorDataEntry := make([]SensorDataEntry, 0)
    err := orm.Find(&sensorDataEntry)

    if err != nil {
        println(err)
    }

    fmt.Println(sensorDataEntry)

    fmt.Fprintf(resp, "return text")
}

Body:
As noted by mkopriva, the problem was using the same variable name for assignment.

Solution for the problem was:

instead of

orm, err := xorm.NewEngine("postgres", connString)

use

var err error
orm, err = xorm.NewEngine("postgres", connString)


问:
How to input a Numpy array
I was going through a solution to a problem which printed the inner and outer array. But while going the solution I was not able to understand the first line in which they took the input. I'm not able to get why they have used int there. The syntax is quite confusing to me. Here is the code:</p>

```<code>A,B = [np.array([input().split()],int) for _ in range(2)]
print(np.inner(A,B)[0][0],np.outer(A,B),sep="\n")
</code>```

答: The syntax of the first line is a list comprehensions that builds a list of numpy arrays where each array contains an int</p>

Title: How to input a Numpy array

Body:
I was going through a solution to a problem which printed the inner and outer array. But while going the solution I was not able to understand the first line in which they took the input. I'm not able to get why they have used int there. The syntax is quite confusing to me. Here is the code:

A,B = [np.array([input().split()],int) for _ in range(2)]
print(np.inner(A,B)[0][0],np.outer(A,B),sep="\n")


答:
The usage for numpy.array is numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)

All of the named parameters in the form "name"="something" are optional. In that example they are using numpy.array(List, dtype) where the list is the split input and dtype (which stands for data type) is int or integer.

So all [np.array([input().split()],int) does is splits user input (which is input()) into a list and tells numpy to store that as a numpy.array of Integers (rather than strings or floats)

Title: How to input a Numpy array


问:
Intersect with row dynamically
I am trying to intersect a target range with some row, changing dynamically:
I was using this :

```<code>If Not intersect ([1:7],target) Is Nothing Then
</code>```

And it works, but :

```<code>Dim n as Integer : n = 7
If Not intersect ([1:n],target) Is Nothing Then
</code>```

Returns Error 424

答:
[] does not allow variables you will need to spell it out:

```<code>Dim n as Integer : n = 7
If Not intersect (Range("1:" & n),target) Is Nothing Then
</code>```

Title: Intersect with row dynamically

Body:
I am trying to intersect a target range with some row, changing dynamically:
I was using this :

If Not intersect ([1:7],target) Is Nothing Then

And it works, but :

Dim n as Integer : n = 7
If Not intersect ([1:n],target) Is Nothing Then

Returns Error 424

Body:
[] does not allow variables you will need to spell it out:

Dim n as Integer : n = 7
If Not intersect (Range("1:" & n),target) Is Nothing Then


问:
window.href open new window?
when ever i use

```<code>window.location.href=//some url
</code>```

it always open a new window, this only happens when the parent window is an dialog box. Any idea what i did wrong?

i tried using

```<code>window.open("http://asdf.com", "_self");
</code>```

as suggested on this thread window.location.href opens another window but it is still not working

thanks

答:
Stumbled upon this question and thought I would offer an alternative.  If you run into trouble with popup blockers, you can use plain old HTML to launch a url in a new window/tab.  You won't have as much control over that is displayed (scrollbars, toolbar, etc), but it works even if javascript is disabled and is 508 compliant:

```<code><a href="http://www.google.com/" target="_blank">Open new window</a>
</code>```

You can read more about the various target attributes here: https://developer.mozilla.org/en/HTML/Element/a

ContentLicense: CC BY-SA 2.5

Title: window.href open new window?

Body:
when ever i use

window.location.href=//some url

it always open a new window, this only happens when the parent window is an dialog box. Any idea what i did wrong?

i tried using

window.open("http://asdf.com", "_self");

as suggested on this thread window.location.href opens another window but it is still not working

thanks

Body:
Stumbled upon this question and thought I would offer an alternative.  If you run into trouble with popup blockers, you can use plain old HTML to launch a url in a new window/tab.  You won't have as much control over that is displayed (scrollbars, toolbar, etc), but it works even if javascript is disabled and is 508 compliant:

<a href="http://www.google.com/" target="_blank">Open new window</a>

You can read more about the various target attributes here: https://developer.mozilla.org/en/HTML/Element/a


问:
Run Command-Failed! Error in compiling Ionic Project

npm install --save-dev --save-exact @ionic/cli-plugin-angular@latest
  ✖ Running command - failed!
  [ERROR] An error occurred while running npm install --save-dev --save-exact @ionic/cli-plugin-angular@latest (exit code 1):

```<code>    npm ERR! code E404
    npm ERR! 404 Not Found: @ionic/cli-plugin-angular@latest

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /home/miracle/.npm/_logs/2019-05-31T13_48_39_761Z-debug.log
</code>```

答:
try npm i ionic-angular --save. I think it must w
ork , you can try this

Body:
npm install --save-dev --save-exact @ionic/cli-plugin-angular@latest
  ✖ Running command - failed!
  [ERROR] An error occurred while running npm install --save-dev --save-exact @ionic/cli-plugin-angular@latest (exit code 1):

    npm ERR! code E404
    npm ERR! 404 Not Found: @ionic/cli-plugin-angular@latest

    npm ERR! A complete log of this run can be found in:
    npm ERR!     /home/miracle/.npm/_logs/2019-05-31T13_48_39_761Z-debug.log


答:
Group by then do a sum and reset the index.

```<code>df = df.groupby(['sinid']).sum().reset_index()
df
</code>```

Result:

```<code>  sinid flag1   flag2
0   abc  1      1
1   def  1      0
2   ghi  1      1
</code>```

Body:
I have a dataset that have binary values for flags for each sinid like this:

>>> df = pd.DataFrame({'sinid':['abc','def','ghi','abc','ghi'],'flag1':[1,1,0,0,1],'flag2':[1,0,1,0,0]})
>>> df
  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      0      1
3   abc      0      0
4   ghi      1      0

I want to add values for each sinid, I think I need groupby but not sure how to use it...

This is the expected result:

  sinid  flag1  flag2
0   abc      1      1
1   def      1      0
2   ghi      1      1

Body:
Group by then do a sum and reset the index.

df = df.groupby(['sinid']).sum().reset_index()
df

Result:

  sinid flag1   flag2
0   abc  1      1
1   def  1      0
2   ghi  1      1


问:
Parse an HTML template as you require it in JavaScript
I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform  the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

```<code>   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]
</code>```

It doesn't return any error but it looks like is totally ignoring the  posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

答:
Believe it or not this is not a common use case, importing html files into JavaScript and displaying them sounds like a workaround or a mid-port hack. JavaScript libraries are used to generate dynamic html on the the fly in the browser in response to user input. If this is what you want you should be using React, Vue, Angular, jQuery or similar.

As others have mentioned, the solution to your problem is not to look for a loader that converts HTML into a DOM node, it's for you to do it yourself. The DOM is not present till code is executed in the browser, It's not a compile time transformation. It's a run-time transformation.

```<code>import template from 'src/test.html'

const html = document.createElement('div')
html.innerHTML = template

</code>```

A loader simply cannot do what you ask for. The browser is responsible for parsing HTML and building the DOM tree based on it's platform and vendor specific implementation. querySelector or createElement are API methods for us to access this browser functionality. But we do not own DOM nodes in our code. They are created for us by the platform. Our JavaScript is merely consuming it.

There are some solutions such as DOMParser and jsDOM that can do this on the server. But they are incomplete implementations of the browser DOM and they should not be brought into front-end code meant to be shipped to the browser. They are meant to be used for things such as headless testing, web crawling and other forms of machine consumption of web pages.

If you can present a specific scenario where you cannot have a HTML string parsed in the browser along with the rest of the code and just before it is consumed by JavaScript, by all means show us and we will present a solution. But It is highly likely that you have misunderstood the roles of JavaScript, Webpack, and HTML and the relationship between them.

TLDR: HTML is a string that gets sent to the browser via HTTP and the browser decides how to build a DOM tree based on it's vendor specific implemenation. In front end code there is no alternative except to get the browser to build a DOM  tree for you with a string you provide and then consume it with the DOM Api.

Body:
I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform  the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]

It doesn't return any error but it looks like is totally ignoring the  posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here

Body:
Believe it or not this is not a common use case, importing html files into JavaScript and displaying them sounds like a workaround or a mid-port hack. JavaScript libraries are used to generate dynamic html on the the fly in the browser in response to user input. If this is what you want you should be using React, Vue, Angular, jQuery or similar.

As others have mentioned, the solution to your problem is not to look for a loader that converts HTML into a DOM node, it's for you to do it yourself. The DOM is not present till code is executed in the browser, It's not a compile time transformation. It's a run-time transformation.

import template from 'src/test.html'

const html = document.createElement('div')
html.innerHTML = template

A loader simply cannot do what you ask for. The browser is responsible for parsing HTML and building the DOM tree based on it's platform and vendor specific implementation. querySelector or createElement are API methods for us to access this browser functionality. But we do not own DOM nodes in our code. They are created for us by the platform. Our JavaScript is merely consuming it.

There are some solutions such as DOMParser and jsDOM that can do this on the server. But they are incomplete implementations of the browser DOM and they should not be brought into front-end code meant to be shipped to the browser. They are meant to be used for things such as headless testing, web crawling and other forms of machine consumption of web pages.

If you can present a specific scenario where you cannot have a HTML string parsed in the browser along with the rest of the code and just before it is consumed by JavaScript, by all means show us and we will present a solution. But It is highly likely that you have misunderstood the roles of JavaScript, Webpack, and HTML and the relationship between them.

TLDR: HTML is a string that gets sent to the browser via HTTP and the browser decides how to build a DOM tree based on it's vendor specific implemenation. In front end code there is no alternative except to get the browser to build a DOM  tree for you with a string you provide and then consume it with the DOM Api.


问:
Can't find main class after libraries have been imported
I'm trying to configure a preexistent Java project by importing into Eclipse 2019-3 and Java SE 11. By the moment I import the project I'm able to run it as usual: Right-click on the main.java -> Run As -> Java Application.

Although it stops because of some missing libraries, it's still able to find the main class.  But as soon as I import the missing jar files stored in a UserLibrary I've created on purpose, I'm not able to run the project any more. If I try run it by clicking on the main.java file it returns me the following message:

Editor does not contains a main type

If I try run it by right-clicking on the project instead, I get a list of all the possible mains I could run the project from, but all of them comes from the libraries and the main I actually need is not present.

List of mains it returns me :

答: I found where the problem was. For the ones who might experience a similar issue: basically, it was a problem of compatibility between the version of JRE I was using for the project and one of the third party library I imported in it. Lowering the JRE version down to Java 10 solved the problem.</p>


问:
Extract information from std::string
Too many string related queries yet some doubt remains, for each string is different and each requirement is different too.

I have a single string in this form:
Random1A:Random1B::String1 Random2A:Random2B::String2 ... RandomNA:RandomNB::StringN

And I want to get back a single string in this form:
String1 String2  ... StringN

In short, the input string would look like A:B::Val1 P:Q::Val2, and o/p result string would look like "Val1 Val2".

PS: Randoms and Strings are small (variable) length alphanumeric strings.

```<code>std::string GetCoreStr ( std::string inputStr, int & vSeqLen )
{
    std::string seqStr;
    std::string strNew;
    seqStr = inputStr;
    size_t firstFind = 0;
    while ( !seqStr.empty() )
    {
        firstFind = inputStr.find("::");
        size_t lastFind = (inputStr.find(" ") < inputStr.length())? inputStr.find(" ") : inputStr.length();
        strNew += inputStr.substr(firstFind+2, lastFind-firstFind-1);
        vSeqStr = inputStr.erase( 0, lastFind+1 );
    }
    vSeqLen = strNew.length();
    return strNew;
}
</code>```

I want to get back a single string String1 String2 ... StringN.

My code works and I get result of my choice, but it is not an optimal form. I want help in improving the code quality.

I ended up doing it the C-way.

```<code>std::string GetCoreStr ( const std::string & inputStr )
{
    std::string strNew;
    for ( int i = 0; i < inputStr.length(); ++i )
    {
        if ( inputStr[i] == ':' && inputStr[i + 1] == ':' )
        {
            i += 2;
            while ( ( inputStr[i] != ' ' && inputStr[i] != '\0' ) )
            {
                strNew += inputStr[i++];
            }
            if ( inputStr[i] == ' ' )
            {
                strNew += ' ';
            }
        }
    }
return strNew;
}
</code>```

答:
I am having trouble deciding on how to adjust the offset. [...]

```<code>std::string getCoreString(std::string const& input)
{
    std::string result;
    // optional: avoid reallocations:
    result.reserve(input.length());
    // (we likely reserved too much – if you have some reliable hint how many
    // input parts we have, you might subtract appropriate number)

    size_t end = 0;
    do
    {
        size_t begin = input.find("::", end);
        // added check: double colon not found at all...
        if(begin == std::string::npos)
            break;
        // single character variant is more efficient, if you need to find just such one:
        end = std::min(input.find(' ', begin) + 1, input.length());
        result.append(input.begin() + begin + 2, input.begin() + end);
    }
    while(end < input.length());
    return result;
}
</code>```

Side note: you do not need the additional 'length' output parameter; it's redundant, as the returned string contains the same value...

Title: Extract information from std::string

Body:
Too many string related queries yet some doubt remains, for each string is different and each requirement is different too.

I have a single string in this form:
Random1A:Random1B::String1 Random2A:Random2B::String2 ... RandomNA:RandomNB::StringN

And I want to get back a single string in this form:
String1 String2  ... StringN

In short, the input string would look like A:B::Val1 P:Q::Val2, and o/p result string would look like "Val1 Val2".

PS: Randoms and Strings are small (variable) length alphanumeric strings.

std::string GetCoreStr ( std::string inputStr, int & vSeqLen )
{
    std::string seqStr;
    std::string strNew;
    seqStr = inputStr;
    size_t firstFind = 0;
    while ( !seqStr.empty() )
    {
        firstFind = inputStr.find("::");
        size_t lastFind = (inputStr.find(" ") < inputStr.length())? inputStr.find(" ") : inputStr.length();
        strNew += inputStr.substr(firstFind+2, lastFind-firstFind-1);
        vSeqStr = inputStr.erase( 0, lastFind+1 );
    }
    vSeqLen = strNew.length();
    return strNew;
}

I want to get back a single string String1 String2 ... StringN.

My code works and I get result of my choice, but it is not an optimal form. I want help in improving the code quality.

I ended up doing it the C-way.

std::string GetCoreStr ( const std::string & inputStr )
{
    std::string strNew;
    for ( int i = 0; i < inputStr.length(); ++i )
    {
        if ( inputStr[i] == ':' && inputStr[i + 1] == ':' )
        {
            i += 2;
            while ( ( inputStr[i] != ' ' && inputStr[i] != '\0' ) )
            {
                strNew += inputStr[i++];
            }
            if ( inputStr[i] == ' ' )
            {
                strNew += ' ';
            }
        }
    }
return strNew;
}

Body:
I am having trouble deciding on how to adjust the offset. [...]

std::string getCoreString(std::string const& input)
{
    std::string result;
    // optional: avoid reallocations:
    result.reserve(input.length());
    // (we likely reserved too much – if you have some reliable hint how many
    // input parts we have, you might subtract appropriate number)

    size_t end = 0;
    do
    {
        size_t begin = input.find("::", end);
        // added check: double colon not found at all...
        if(begin == std::string::npos)
            break;
        // single character variant is more efficient, if you need to find just such one:
        end = std::min(input.find(' ', begin) + 1, input.length());
        result.append(input.begin() + begin + 2, input.begin() + end);
    }
    while(end < input.length());
    return result;
}

Side note: you do not need the additional 'length' output parameter; it's redundant, as the returned string contains the same value...


问:
What's the return value of DBSet.Add(object o)
Consider the situation.

I have a userlogin table. the userlogin has the following fields.

  userid(identity(1,1)), username(unique), password(string)
I have another table, userRole with following fields.

userid(fk referencing userlogin), role(string)

Now suppose I want to add an admin user to my empty application database.
What I am currently doing is:

```<code>// Check Userlogin if it contains adminuser1 as username, if not, add adminuser1 with password xyz.

UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
context.UserLogins.Add(login);
context.SaveChanges();

// query again from database to get the userid
Userlogin user = context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password == "xyz"));
int userid = user.userid;
UserRole admin = new UserRole();
admin.userid = userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
</code>```

I want to make it a less troublesome, if we can get the userid of userRecently Added, without making another request.

I mean I want to do this if it is possible.

```<code>UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
UserLogin user = context.UserLogins.Add(login);
UserRole admin = new UserRole();
admin.userid = user.userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();
</code>```

Update

I also wanted to know if there is some way to do

context.UserLogins.Single(l => l == login);

instead of

```<code>context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));
</code>```

because I use the same method in large classes in many fields.

答:
For the question

What's the return value of DBSet.Add(object o)

The answer is: it will return the same object o(i.e. without the userid). Simply because userid is an identity column and relies on the database, its value is only available after context.SaveChanges() is called. Since Add() method only registers that a change will take place after SaveChanges() is called.

For the answer to update,

Instead of using

```<code>context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));
</code>```

For classes that have many fields, I can check if there are any unique columns. For example. I could use, simply

```<code>context.UserLogins.Single(l => l.username == "adminuser1");
</code>```

Just because, username(unique) is specified in the question.

I would rather recommend people use a single Stored Procedure. The calling of context.SaveChanges() and the context.xyz.Single() require opening database connection multiple times. For optimising performance you can use Stored Procedures, as they require only one connection per task. For more information.

Understang Performance Considerations

As I am using database first approach, I found this link also helpful.

Use Stored Procedure in Entity Framework

Thanks :)

Body:
Consider the situation.

I have a userlogin table. the userlogin has the following fields.

  userid(identity(1,1)), username(unique), password(string)
I have another table, userRole with following fields.

userid(fk referencing userlogin), role(string)

Now suppose I want to add an admin user to my empty application database.
What I am currently doing is:

// Check Userlogin if it contains adminuser1 as username, if not, add adminuser1 with password xyz.

UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
context.UserLogins.Add(login);
context.SaveChanges();

// query again from database to get the userid
Userlogin user = context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password == "xyz"));
int userid = user.userid;
UserRole admin = new UserRole();
admin.userid = userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();

I want to make it a less troublesome, if we can get the userid of userRecently Added, without making another request.

I mean I want to do this if it is possible.

UserLogin login = new UserLogin();
login.username = "adminuser1";
login.password = "xyz";
UserLogin user = context.UserLogins.Add(login);
UserRole admin = new UserRole();
admin.userid = user.userid;
admin.role = "admin";
context.UserRoles.Add(admin);
context.SaveChanges();

Update

I also wanted to know if there is some way to do

context.UserLogins.Single(l => l == login);

instead of

context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));

because I use the same method in large classes in many fields.

Body:
For the question

What's the return value of DBSet.Add(object o)

The answer is: it will return the same object o(i.e. without the userid). Simply because userid is an identity column and relies on the database, its value is only available after context.SaveChanges() is called. Since Add() method only registers that a change will take place after SaveChanges() is called.

For the answer to update,

Instead of using

context.UserLogins.Single(l => (l.username == "adminuser1") && (l.password=="xyz"));

For classes that have many fields, I can check if there are any unique columns. For example. I could use, simply

context.UserLogins.Single(l => l.username == "adminuser1");

Just because, username(unique) is specified in the question.

I would rather recommend people use a single Stored Procedure. The calling of context.SaveChanges() and the context.xyz.Single() require opening database connection multiple times. For optimising performance you can use Stored Procedures, as they require only one connection per task. For more information.

Understang Performance Considerations

As I am using database first approach, I found this link also helpful.

Use Stored Procedure in Entity Framework

Thanks :)


问:
silverlight picking basic instead of wsHttpBinding
When I add a service silverlight is picking basic instead of wsHttpBinding.  What might cause this and how can I avoid it?  This is my web.config:</p>

```<code><configuration>
        <system.web>
            <compilation debug="true" targetFramework="4.0" />
        </system.web>

        <system.serviceModel>
            <standardEndpoints />
            <bindings />
            <services>
                <service name="Service2">
                    <endpoint binding="wsHttpBinding" bindingConfiguration="" name="Service2Endpoint"
                        bindingName="wsHttpBindingFirst" contract="IService2" />
                </service>
            </services>
            <behaviors>
                <serviceBehaviors>
                    <behavior name="">
                        <serviceMetadata httpGetEnabled="true" />
                        <serviceDebug includeExceptionDetailInFaults="false" />
                    </behavior>
                </serviceBehaviors>
            </behaviors>
            <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
    </configuration>
</code>```

答:
Didn't put the namespace in
Not supported by silverlight</p>

Body:
When I add a service silverlight is picking basic instead of wsHttpBinding.  What might cause this and how can I avoid it?  This is my web.config:

<configuration>
        <system.web>
            <compilation debug="true" targetFramework="4.0" />
        </system.web>

        <system.serviceModel>
            <standardEndpoints />
            <bindings />
            <services>
                <service name="Service2">
                    <endpoint binding="wsHttpBinding" bindingConfiguration="" name="Service2Endpoint"
                        bindingName="wsHttpBindingFirst" contract="IService2" />
                </service>
            </services>
            <behaviors>
                <serviceBehaviors>
                    <behavior name="">
                        <serviceMetadata httpGetEnabled="true" />
                        <serviceDebug includeExceptionDetailInFaults="false" />
                    </behavior>
                </serviceBehaviors>
            </behaviors>
            <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
    </configuration>


答:
[] syntax is shortcut for Evaluate :

```<code>If Not intersect (Evaluate("1:" & n), target) Is Nothing Then
</code>```

Title: Intersect with row dynamically

Body:
[] syntax is shortcut for Evaluate :

If Not intersect (Evaluate("1:" & n), target) Is Nothing Then


问:
How to Autowired service dynamically
I have a interface like BaseService and two Class CoreServiceImpl and TenantServiceImpl both of them extend BaseService. Now I want to Autowired BaseService in My controller, how to run specific service (core/tenant) by passing any param ?</p>

答:
You could do it with @Profile:

```<code>@Component
@Profile("core")
public class CoreServiceImpl {}

@Component
@Profile("tenant")
public class TenantServiceImpl {}
</code>```

And then run spring with --spring.profiles.active=core/tenant

Title: How to Autowired service dynamically

Body:
You could do it with @Profile:

@Component
@Profile("core")
public class CoreServiceImpl {}

@Component
@Profile("tenant")
public class TenantServiceImpl {}

And then run spring with --spring.profiles.active=core/tenant


问:
Asp.NET MVC Inserting data into mssql database gives table object error
when a user register i want to insert some extra data into a other table AspNetUserStatics. But when the user register i got this error: System.Data.SqlClient.SqlException: The request for procedure 'AspNetUserStatics' failed because 'AspNetUserStatics' is a table object.

I tried multiple ways to add code data into my database with other stack overflow posts. But i can't find the solution. Maybe it is a simple stupid thing that wil solve this but i am new and need to learn things. So it will great if someone can help me.

```<code>                    connection();

                    SqlCommand com = new SqlCommand("AspNetUserStatics", con);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@Id", user.Id);
                    com.Parameters.AddWithValue("@Points", 5);
                    com.Parameters.AddWithValue("@Day", DateTime.Now.DayOfWeek);
                    com.Parameters.AddWithValue("@PointsNewUser", 1);

                    con.Open();
                    com.ExecuteNonQuery();
                    con.Close();

                    return RedirectToAction("Index", "Home");
</code>```

Here is the the full code: https://pastr.io/view/iPeGBL

Error: The request for procedure 'AspNetUserStatics' failed because 'AspNetUserStatics' is a table object.

Full Error Page: https://pastr.io/view/I59Q2a

I want all the data will be insert into the table AspNetUserStatics.

Regards,
Bart

答:
For what I can see you are trying to send data to a stroed procedure, but "AspNetUserStatics" is a table. you should use an insert statement instead, something like</p>

```<code>insert into AspNetUserStatics (Id, points, ....) values (@Id, @Points,....)
</code>```

Body:
when a user register i want to insert some extra data into a other table AspNetUserStatics. But when the user register i got this error: System.Data.SqlClient.SqlException: The request for procedure 'AspNetUserStatics' failed because 'AspNetUserStatics' is a table object.

I tried multiple ways to add code data into my database with other stack overflow posts. But i can't find the solution. Maybe it is a simple stupid thing that wil solve this but i am new and need to learn things. So it will great if someone can help me.

                    connection();

                    SqlCommand com = new SqlCommand("AspNetUserStatics", con);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@Id", user.Id);
                    com.Parameters.AddWithValue("@Points", 5);
                    com.Parameters.AddWithValue("@Day", DateTime.Now.DayOfWeek);
                    com.Parameters.AddWithValue("@PointsNewUser", 1);

                    con.Open();
                    com.ExecuteNonQuery();
                    con.Close();

                    return RedirectToAction("Index", "Home");

Here is the the full code: https://pastr.io/view/iPeGBL

Error: The request for procedure 'AspNetUserStatics' failed because 'AspNetUserStatics' is a table object.

Full Error Page: https://pastr.io/view/I59Q2a

I want all the data will be insert into the table AspNetUserStatics.

Regards,
Bart

Body:
For what I can see you are trying to send data to a stroed procedure, but "AspNetUserStatics" is a table. you should use an insert statement instead, something like

insert into AspNetUserStatics (Id, points, ....) values (@Id, @Points,....)


问:
Why accumulate Cloud Firestore doc.id?
I stored some data using db.collection("articles").doc(); and update it using  db.collection("articles").doc(postData.articleId).update(postData);. But creating new article next time, the postData.articleId is accumulated.

First, I create a doc, then update data in real time using socket.io. but I create another doc later, postData.id was accumulated.

```<code>var doc = db.collection("articles").doc();
var postData = {
    author: user.email,
    articleId: doc.id,
    currentTime: new Date()
}
doc.set(postData);

--- get data from client code here (using socket) ---

db.collection("articles").doc(postData.articleId).update(postData); /*Update Data to postData.id.*/
</code>```

The expected result is not accumulation postData.id when new data added.

(For more info: https://github.com/officialmansu/opinion-express/tree/develop)

答:
The update() method of Cloud Firestore is specifically meant to provide partial updates (sometimes also known as patches) to an existing document.

If you want to instead replace all existing data of the document, use set(). So:

```<code>db.collection("articles").doc(postData.articleId).set(postData);
</code>```

Title: Why accumulate Cloud Firestore doc.id?

Body:
I stored some data using db.collection("articles").doc(); and update it using  db.collection("articles").doc(postData.articleId).update(postData);. But creating new article next time, the postData.articleId is accumulated.

First, I create a doc, then update data in real time using socket.io. but I create another doc later, postData.id was accumulated.

var doc = db.collection("articles").doc();
var postData = {
    author: user.email,
    articleId: doc.id,
    currentTime: new Date()
}
doc.set(postData);

--- get data from client code here (using socket) ---

db.collection("articles").doc(postData.articleId).update(postData); /*Update Data to postData.id.*/

The expected result is not accumulation postData.id when new data added.

(For more info: https://github.com/officialmansu/opinion-express/tree/develop)

Body:
The update() method of Cloud Firestore is specifically meant to provide partial updates (sometimes also known as patches) to an existing document.

If you want to instead replace all existing data of the document, use set(). So:

db.collection("articles").doc(postData.articleId).set(postData);


问:
IE 9 does not use sub-pixel antialiasing under certain conditions
[Original title: IE 9 text renders very poorly; is there a workaround?)

IE 9 is rendering the text in my application very poorly.  The problem is not in my monitor's Clear Type settings, since IE 9 in compatibility mode, Firefox, and Chrome all render text nicely.  Here's a side-by-side comparison of how the text is rendered with IE 9, IE 9 in compatibility mode, and Chrome:

I tried applying this answer, but it doesn't seem to apply to anything after IE 7.  Does anybody know of any workarounds we can apply to our site to fix IE 9's bad text rendering?

Edit:

I've boiled down the problem page to the bare essentials.  As you can see, it doesn't take much to reproduce.  Be sure that IE has a browser mode if IE9 and document mode of IE9 standards:

```<code><html xmlns="http://www.w3.org/1999/xhtml">
  <body style="background-color: rgb(30, 34, 59); color: rgb(255, 85, 0); font-size: 20px">
    Home
  </body>
</html>
</code>```

答:
Short answer: this is an issue when you specify font sizes in pt (points), rather than pixels.

So what happens is that the new IE9 rendering engine uses DirectWrite, which won't snap to the nearest pixel as it did with GDI+, so if your pt size doesn't map to a whole pixel number, it will draw it exactly that way, which makes it appear blurry.

The IE8 compatibility mode wouldn't suffer this issue as it uses regular GDI rendering that we are used to.

So check out all your style sheets etc and if you are asking for point size font's, that's exactly what will be given in IE9, and depending on your font used etc, your point size might or might not map to a crisp and clear size.

This is explained in detail here:

IE9's blurry font text - www.hanselman.com/blog/TheUltimateGuideOfFiveThingsForNewIE9UsersWhoFearChange.aspx

Body:
[Original title: IE 9 text renders very poorly; is there a workaround?)

IE 9 is rendering the text in my application very poorly.  The problem is not in my monitor's Clear Type settings, since IE 9 in compatibility mode, Firefox, and Chrome all render text nicely.  Here's a side-by-side comparison of how the text is rendered with IE 9, IE 9 in compatibility mode, and Chrome:

I tried applying this answer, but it doesn't seem to apply to anything after IE 7.  Does anybody know of any workarounds we can apply to our site to fix IE 9's bad text rendering?

Edit:

I've boiled down the problem page to the bare essentials.  As you can see, it doesn't take much to reproduce.  Be sure that IE has a browser mode if IE9 and document mode of IE9 standards:

    Home


问:
How can I select specific values from list and plot a seaborn boxplot?
I have a list (length 300) of lists (each length 1000).  I want to sort the list of 300 by the median of each list of 1000, and then plot a seaborn boxplot of the top 10 (i.e. the 10 lists with the greatest median).

I am able to plot the entire list of 300 but don't know where to go from there.

I can plot a range of the points but how to I plot, for example: data[3],data[45], data[129] all in the same plot?

```<code>ax = sns.boxplot(data = data[0:50])
</code>```

I can also work out which items in the list are in the top 10 by doing this (but I realise this is not the most elegant way!)

```<code>array_median = np.median(data, axis=1)
np_sortedarray = np.sort(np.array(array_median))

sort_panda = pd.DataFrame(array_median)
TwoL = sort_panda.reset_index()
TwoL.sort_values(0)
</code>```

Ultimately I want a boxplot with 10 boxes, showing the list items that have the greatest median values.

Example of data: list of 300 x 1000
    [[1.236762285232544,
     1.2303414344787598,
     1.196462631225586,
     ...1.1787045001983643,
     1.1760116815567017,
     1.1614983081817627,
     1.1546586751937866],
     [1.1349891424179077,
     1.1338907480239868,
     1.1239897012710571,
     1.1173863410949707,
     ...1.1015456914901733,
     1.1005324125289917,
     1.1005228757858276],
     [1.0945734977722168,
      ...1.091795563697815]]

答:
See this answer for fetching top 10 elements

```<code>idx = (-median).argsort()[:10]
data[idx]
</code>```

Also, you can get particular elements of data like this

```<code>data[[3, 45, 129]]
</code>```

Body:
I have a list (length 300) of lists (each length 1000).  I want to sort the list of 300 by the median of each list of 1000, and then plot a seaborn boxplot of the top 10 (i.e. the 10 lists with the greatest median).

I am able to plot the entire list of 300 but don't know where to go from there.

I can plot a range of the points but how to I plot, for example: data[3],data[45], data[129] all in the same plot?

ax = sns.boxplot(data = data[0:50])

I can also work out which items in the list are in the top 10 by doing this (but I realise this is not the most elegant way!)

array_median = np.median(data, axis=1)
np_sortedarray = np.sort(np.array(array_median))

sort_panda = pd.DataFrame(array_median)
TwoL = sort_panda.reset_index()
TwoL.sort_values(0)

Ultimately I want a boxplot with 10 boxes, showing the list items that have the greatest median values.

Example of data: list of 300 x 1000
    [[1.236762285232544,
     1.2303414344787598,
     1.196462631225586,
     ...1.1787045001983643,
     1.1760116815567017,
     1.1614983081817627,
     1.1546586751937866],
     [1.1349891424179077,
     1.1338907480239868,
     1.1239897012710571,
     1.1173863410949707,
     ...1.1015456914901733,
     1.1005324125289917,
     1.1005228757858276],
     [1.0945734977722168,
      ...1.091795563697815]]

Body:
See this answer for fetching top 10 elements

idx = (-median).argsort()[:10]
data[idx]

Also, you can get particular elements of data like this

data[[3, 45, 129]]


问:
Connecting to cloudant from java using TLSv1.2
I'm trying to connect to my Cloudant database from Java using TLSv1.2 from Liberty server running IBM JRE.

Support for connection lower than TLSv1.2 is ending and I need this working.

I added a customSSLSocketFactory to the builder configured for TLSv1.2 communication , when I run it in my local environment, which runs on Oracle JRE there is no error , but when I run it on a newer environment, which runs the Liberty server with IBM JRE (latest versions Java 8) I get an error.

```<code>SSLSocketFactory sslSocketFactory;
try {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init((KeyStore) null);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
    }
    X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

    SSLContext ssl = SSLContext.getInstance("TLSv1.2");
    ssl.init(null, new TrustManager[] { trustManager }, new SecureRandom());
    sslSocketFactory = ssl.getSocketFactory();
} catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
}

client = ClientBuilder.url(new URL(restServerURL)).username(userid)
         .password(password).connectTimeout(60, TimeUnit.SECONDS).customSSLSocketFactory(sslSocketFactory)
         .build();
</code>```

Error received is:

```<code>R java.lang.IllegalStateException: Unable to extract the trust manager on okhttp3.internal.platform.Platform@5194035f, sslSocketFactory is class com.ibm.jsse2.SSLSocketFactoryImpl
R   at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.java:654)
R   at okhttp3.internal.huc.OkHttpsURLConnection.setSSLSocketFactory(OkHttpsURLConnection.java:63)
R   at com.cloudant.http.internal.interceptors.SSLCustomizerInterceptor.interceptRequest(SSLCustomizerInterceptor.java:71)
R   at com.cloudant.http.HttpConnection.execute(HttpConnection.java:290)
R   at com.cloudant.client.org.lightcouch.CouchDbClient.execute(CouchDbClient.java:485)
R   at com.cloudant.client.api.CloudantClient.executeRequest(CloudantClient.java:339)
R   at com.cloudant.client.internal.views.ViewRequester.executeRequestWithResponseAsJson(ViewRequester.java:34)
R   at com.cloudant.client.internal.views.ViewRequester.getResponseAsJson(ViewRequester.java:28)
R   at com.cloudant.client.internal.views.ViewRequestImpl.getResponse(ViewRequestImpl.java:34)
R   at com.profility.database.cloudant.CloudantConnector.getQuestionnaire(CloudantConnector.java:470)
R   at com.profility.database.Database.getQuestionnaire(Database.java:159)
R   at com.profility.questionnaire.QuestionnaireCache.getTheQuestionnaire(QuestionnaireCache.java:21)
R   at com.profility.scheduer.ApplicationStarter.run(ApplicationStarter.java:31)
R   at java.lang.Thread.run(Thread.java:812)
</code>```

答:
You don't need a custom SSLSocketFactory to use TLS1.2 you just need to configure your JVM to provide TLSv1.2.

Likely you just need the property as described in this support document com.ibm.jsse2.overrideDefaultTLS=true to match the Oracle behaviour and enable TLS 1.0, 1.1. and 1.2 (instead of the default of just 1.0).

If that is insufficient you may need the properties described in this support document to enable the TLSv1.2 for the protocols.

Body:
I'm trying to connect to my Cloudant database from Java using TLSv1.2 from Liberty server running IBM JRE.

Support for connection lower than TLSv1.2 is ending and I need this working.

I added a customSSLSocketFactory to the builder configured for TLSv1.2 communication , when I run it in my local environment, which runs on Oracle JRE there is no error , but when I run it on a newer environment, which runs the Liberty server with IBM JRE (latest versions Java 8) I get an error.

SSLSocketFactory sslSocketFactory;
try {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init((KeyStore) null);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
    }
    X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

    SSLContext ssl = SSLContext.getInstance("TLSv1.2");
    ssl.init(null, new TrustManager[] { trustManager }, new SecureRandom());
    sslSocketFactory = ssl.getSocketFactory();
} catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
}

client = ClientBuilder.url(new URL(restServerURL)).username(userid)
         .password(password).connectTimeout(60, TimeUnit.SECONDS).customSSLSocketFactory(sslSocketFactory)
         .build();

Error received is:

R java.lang.IllegalStateException: Unable to extract the trust manager on okhttp3.internal.platform.Platform@5194035f, sslSocketFactory is class com.ibm.jsse2.SSLSocketFactoryImpl
R   at okhttp3.OkHttpClient$Builder.sslSocketFactory(OkHttpClient.java:654)
R   at okhttp3.internal.huc.OkHttpsURLConnection.setSSLSocketFactory(OkHttpsURLConnection.java:63)
R   at com.cloudant.http.internal.interceptors.SSLCustomizerInterceptor.interceptRequest(SSLCustomizerInterceptor.java:71)
R   at com.cloudant.http.HttpConnection.execute(HttpConnection.java:290)
R   at com.cloudant.client.org.lightcouch.CouchDbClient.execute(CouchDbClient.java:485)
R   at com.cloudant.client.api.CloudantClient.executeRequest(CloudantClient.java:339)
R   at com.cloudant.client.internal.views.ViewRequester.executeRequestWithResponseAsJson(ViewRequester.java:34)
R   at com.cloudant.client.internal.views.ViewRequester.getResponseAsJson(ViewRequester.java:28)
R   at com.cloudant.client.internal.views.ViewRequestImpl.getResponse(ViewRequestImpl.java:34)
R   at com.profility.database.cloudant.CloudantConnector.getQuestionnaire(CloudantConnector.java:470)
R   at com.profility.database.Database.getQuestionnaire(Database.java:159)
R   at com.profility.questionnaire.QuestionnaireCache.getTheQuestionnaire(QuestionnaireCache.java:21)
R   at com.profility.scheduer.ApplicationStarter.run(ApplicationStarter.java:31)
R   at java.lang.Thread.run(Thread.java:812)


问:
Camera preview appears stretched
Im trying to use camera 2 with and AutoFitTextureView from the google sample.

Im setting it up like this

```<code>private void setUpCameraOutputs() {
    CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (manager != null) {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

                // We don't use a front facing camera in this sample.
                //noinspection ConstantConditions
                if (characteristics.get(LENS_FACING) == LENS_FACING_FRONT) continue;

                StreamConfigurationMap map = characteristics.get(SCALER_STREAM_CONFIGURATION_MAP);

                if(map != null) {
                    // For still image captures, we use the largest available size.
                    List<Size> outputSizes = Arrays.asList(map.getOutputSizes(sImageFormat));
                    Size largest = Collections.max(outputSizes, new CompareSizesByArea());
                    mImageReader = ImageReader.newInstance(640, 480, sImageFormat, 8);
                    mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
                    // Danger, W.R.! Attempting to use too large a preview size could exceed the camera
                    // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                    // garbage capture data.
                    mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), largest.getWidth(), largest.getHeight(), largest);
                    //mPreviewSize = new Size(largest.getWidth(), largest.getHeight());
                    setAspectRatio2(mPreviewSize);
                    Logging.e(TAG, "WIDTH: " + mPreviewSize.getWidth() + " HEIGHT: " + mPreviewSize.getHeight());

                    mCameraId = cameraId;
                }
                //return;
            }
        }else{
            Logging.e(TAG,"No Manager");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void setAspectRatio(){
    int orientation = mContext.getResources().getConfiguration().orientation;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        mTextureView.setAspectRatio(mPreviewSize.getWidth(),mPreviewSize.getHeight());
    } else {
        mTextureView.setAspectRatio(mPreviewSize.getHeight(),mPreviewSize.getWidth());
    }
}

private void setAspectRatio2(Size largest){
    float cameraAspectRatio = (float) largest.getHeight() / largest.getWidth();
    //Preparation
    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager wm = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE));
    wm.getDefaultDisplay().getMetrics(metrics);
    int screenWidth = metrics.widthPixels;
    int screenHeight = metrics.heightPixels;
    int finalWidth = screenWidth;
    int finalHeight = screenHeight;
    int widthDifference = 0;
    int heightDifference = 0;
    float screenAspectRatio = (float) screenWidth / screenHeight;

    //Determines whether we crop width or crop height
    if (screenAspectRatio > cameraAspectRatio) { //Keep width crop height
        finalHeight = (int) (screenWidth / cameraAspectRatio);
        heightDifference = finalHeight - screenHeight;
    } else { //Keep height crop width
        finalWidth = (int) (screenHeight * cameraAspectRatio);
        widthDifference = finalWidth - screenWidth;
    }

    //Apply the result to the Preview
    LayoutParams lp = (FrameLayout.LayoutParams) mTextureView.getLayoutParams();
    lp.width = finalWidth;
    lp.height = finalHeight;
    //Below 2 lines are to center the preview, since cropping default occurs at the right and bottom
    lp.leftMargin = - (widthDifference / 2);
    lp.topMargin = - (heightDifference / 2);
    mTextureView.setLayoutParams(lp);
}

private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    double ratio = (double) h / w;
    for (Size option : choices) {
        double optionRatio = (double) option.getHeight() / option.getWidth();
        if (ratio == optionRatio) {
            bigEnough.add(option);
        }
    }

    // Pick the smallest of those, assuming we found any
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else {
        Logging.e(TAG, "Couldn't find any suitable preview size");
        return choices[1];
    }
}
</code>```

I've tried to set the aspect ratio with 2 different methods, but none of them seem to do what i need.
The preview takes all screen as i want, but camera preview always appear streeched, things look thiner.
I've tried a few sugestions from stackoverflow but still haven't got the perfect result.

答:
There are a lot of libraries which ease the use of CameraView.
You can have a look at this one or this one for example.</p>

Title: Camera preview appears stretched

Body:
Im trying to use camera 2 with and AutoFitTextureView from the google sample.

Im setting it up like this

private void setUpCameraOutputs() {
    CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (manager != null) {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

                // We don't use a front facing camera in this sample.
                //noinspection ConstantConditions
                if (characteristics.get(LENS_FACING) == LENS_FACING_FRONT) continue;

                StreamConfigurationMap map = characteristics.get(SCALER_STREAM_CONFIGURATION_MAP);

                if(map != null) {
                    // For still image captures, we use the largest available size.
                    List<Size> outputSizes = Arrays.asList(map.getOutputSizes(sImageFormat));
                    Size largest = Collections.max(outputSizes, new CompareSizesByArea());
                    mImageReader = ImageReader.newInstance(640, 480, sImageFormat, 8);
                    mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
                    // Danger, W.R.! Attempting to use too large a preview size could exceed the camera
                    // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                    // garbage capture data.
                    mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), largest.getWidth(), largest.getHeight(), largest);
                    //mPreviewSize = new Size(largest.getWidth(), largest.getHeight());
                    setAspectRatio2(mPreviewSize);
                    Logging.e(TAG, "WIDTH: " + mPreviewSize.getWidth() + " HEIGHT: " + mPreviewSize.getHeight());

                    mCameraId = cameraId;
                }
                //return;
            }
        }else{
            Logging.e(TAG,"No Manager");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void setAspectRatio(){
    int orientation = mContext.getResources().getConfiguration().orientation;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        mTextureView.setAspectRatio(mPreviewSize.getWidth(),mPreviewSize.getHeight());
    } else {
        mTextureView.setAspectRatio(mPreviewSize.getHeight(),mPreviewSize.getWidth());
    }
}

private void setAspectRatio2(Size largest){
    float cameraAspectRatio = (float) largest.getHeight() / largest.getWidth();
    //Preparation
    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager wm = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE));
    wm.getDefaultDisplay().getMetrics(metrics);
    int screenWidth = metrics.widthPixels;
    int screenHeight = metrics.heightPixels;
    int finalWidth = screenWidth;
    int finalHeight = screenHeight;
    int widthDifference = 0;
    int heightDifference = 0;
    float screenAspectRatio = (float) screenWidth / screenHeight;

    //Determines whether we crop width or crop height
    if (screenAspectRatio > cameraAspectRatio) { //Keep width crop height
        finalHeight = (int) (screenWidth / cameraAspectRatio);
        heightDifference = finalHeight - screenHeight;
    } else { //Keep height crop width
        finalWidth = (int) (screenHeight * cameraAspectRatio);
        widthDifference = finalWidth - screenWidth;
    }

    //Apply the result to the Preview
    LayoutParams lp = (FrameLayout.LayoutParams) mTextureView.getLayoutParams();
    lp.width = finalWidth;
    lp.height = finalHeight;
    //Below 2 lines are to center the preview, since cropping default occurs at the right and bottom
    lp.leftMargin = - (widthDifference / 2);
    lp.topMargin = - (heightDifference / 2);
    mTextureView.setLayoutParams(lp);
}

private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    double ratio = (double) h / w;
    for (Size option : choices) {
        double optionRatio = (double) option.getHeight() / option.getWidth();
        if (ratio == optionRatio) {
            bigEnough.add(option);
        }
    }

    // Pick the smallest of those, assuming we found any
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else {
        Logging.e(TAG, "Couldn't find any suitable preview size");
        return choices[1];
    }
}

I've tried to set the aspect ratio with 2 different methods, but none of them seem to do what i need.
The preview takes all screen as i want, but camera preview always appear streeched, things look thiner.
I've tried a few sugestions from stackoverflow but still haven't got the perfect result.


问:
how to resolve The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))
```<code>PowerPoint.Application PowerPoint_App;
PowerPoint_App = new PowerPoint.ApplicationClass();
PowerPoint_App.DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone;
PowerPoint.Presentation presentation;
presentation = null;
try
{
    PowerPoint_App.Visible = MsoTriState.msoTrue;
    presentation = PowerPoint_App.Presentations.Open(strPptFilePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
    PowerPoint.Slide tempSlide = null;
    int totalSlides = presentation.Slides.Count;
    int slideNo = 0;
</code>```

I am getting the below exception on PowerPoint_App.Presentations.Open code.

Exception Message: The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

I did not received this error previously on this block of code. Everything was working perfectly before. Can anyone help?

答: Check your Task Manager; you may have an orphaned application instance from a debugging session. Kill it and try again. That has been the case for me before.</p>

Body:
PowerPoint.Application PowerPoint_App;
PowerPoint_App = new PowerPoint.ApplicationClass();
PowerPoint_App.DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone;
PowerPoint.Presentation presentation;
presentation = null;
try
{
    PowerPoint_App.Visible = MsoTriState.msoTrue;
    presentation = PowerPoint_App.Presentations.Open(strPptFilePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
    PowerPoint.Slide tempSlide = null;
    int totalSlides = presentation.Slides.Count;
    int slideNo = 0;

I am getting the below exception on PowerPoint_App.Presentations.Open code.

Exception Message: The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))

I did not received this error previously on this block of code. Everything was working perfectly before. Can anyone help?


问:
How to show HTTP response status of rest API in serenity report through feature file
I want to show the http status code and response  in serenity report. I am using the cucumber plus java and serenity framework.
Please find below my code.

Feature file

Feature: Get Google address

Scenario: Predit google Address

Given API is set up

Then  I get the Http status code and response

Step definition file:

```<code>@Given("^API is set up$")
public void setUp() {

}

@Then("^I get the Http status code and response$")
</code>```

Serenity BDD Report

Given API is set up

SUCCESS

Then I get the status code and response

SUCCESS

答:
You can define global variable in your framework and use it as you can see in the custom reporting Tutorial of Serenity.</p>

```<code>report.customfields.user = ${API_RESPONSE_CODE}
</code>```

Body:
I want to show the http status code and response  in serenity report. I am using the cucumber plus java and serenity framework.
Please find below my code.

Feature file

Feature: Get Google address

Scenario: Predit google Address

Given API is set up

Then  I get the Http status code and response

Step definition file:

@Given("^API is set up$")
public void setUp() {

}

@Then("^I get the Http status code and response$")

Serenity BDD Report

Given API is set up

SUCCESS

Then I get the status code and response

SUCCESS

Body:
You can define global variable in your framework and use it as you can see in the custom reporting Tutorial of Serenity.

report.customfields.user = ${API_RESPONSE_CODE}