问:
Time formatting issues with Moment.JS
I have some DB objects coming back from my server as so:

```<code>client_id: 24
created_at: "2022-02-11 17:41:39.330443"
id: 22
report: "sfsf"
report_category: "Client Assigned"
volunteer_id: 23

client_id: 24
created_at: "2022-02-11 17:43:04.837869"
id: 23
report: "one more"
report_category: "Client Assigned"
volunteer_id: 23
</code>```

In my React code I am trying to apply formatting with moment to the created_at field:

```<code>{moment(comment.createdAt).format('DD/MM/YY, h:mm a')}
</code>```

which returns something like:

```<code>11/02/22, 12:46 pm
</code>```

For all the objects the time just seems to default to the current time it is right now and not the time in the created_at field. All the entries show 12:46 pm. Any advice on this issue?

答:
Your object call looks to be incorrect and may be defaulting to current time because in your sample object:

```<code>{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}
</code>```

your code calls createdAt when you likely need created_at:

```<code>moment(comment.created_at).format('DD/MM/YY, h:mm a')
</code>```

sample test run as string:

const out = document.getElementById('output')
const testDate = "2022-02-11 17:41:39.330443"
const momentCode = moment(testDate).format('DD/MM/YY, h:mm a')
out.innerText = momentCode```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="output"></p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script></code>```

Title: Time formatting issues with Moment.JS

Body:
I have some DB objects coming back from my server as so:

client_id: 24
created_at: "2022-02-11 17:41:39.330443"
id: 22
report: "sfsf"
report_category: "Client Assigned"
volunteer_id: 23

client_id: 24
created_at: "2022-02-11 17:43:04.837869"
id: 23
report: "one more"
report_category: "Client Assigned"
volunteer_id: 23

In my React code I am trying to apply formatting with moment to the created_at field:

{moment(comment.createdAt).format('DD/MM/YY, h:mm a')}

which returns something like:

11/02/22, 12:46 pm

For all the objects the time just seems to default to the current time it is right now and not the time in the created_at field. All the entries show 12:46 pm. Any advice on this issue?

Body:
Your object call looks to be incorrect and may be defaulting to current time because in your sample object:

{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}

your code calls createdAt when you likely need created_at:

moment(comment.created_at).format('DD/MM/YY, h:mm a')

sample test run as string:

const out = document.getElementById('output')
const testDate = "2022-02-11 17:41:39.330443"
const momentCode = moment(testDate).format('DD/MM/YY, h:mm a')
out.innerText = momentCode

<p id="output"></p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


来源: stackexchange

问:
Printing in JS page an array from React method in other file
I'm using React.
I have two files: biologia.js and fleekstorage-functions.js
In fleekstorage-functions.js there are Fleek Storage method that can list files from my bucket:

```<code>const ListFiles = async () => {
    const input = {
        apiKey,
        apiSecret,
        getOptions: [
            'bucket',
            'key',
            'hash',
            'publicUrl'
        ],
    };

    try {
        const result = await fleek.listFiles(input);
        return result
    } catch (e) {
        console.log('error', e);
    }
}
</code>```

And in biologia.js I have:

```<code>var articoli = ListFiles()
const Biologia = () => {
    return (
        <>
            <br/><br/>
            <h1 className="titolo">Articoli di Biologia:</h1>
            <p className="titolo">Qui si parlerà di biologia.</p>
            {articoli}
        </>
    );
}
</code>```

As you look I wanted to print on a page the output of ListFiles, but console returned me this error:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

Could you please help me to print the array and single elements of it on biologia.js?

答:
Your main problem here seems to be that ListFiles() is an async function. In other words, it will always return a Promise, meaning var articoli = ListFiles() will always store a Promise inside articoli.

As indicated by the error you're seeing, a Promise isn't a renderable element. You'll have to wait for the Promise to be resolved, then transform the results as desired into what you want to render. For example, set up your state with a Hook:

```<code>const [articoli, setArticoli] = useState(null);
</code>```

Then you can set the value after the Promise from ListFiles() has resolved:

```<code>ListFiles().then((list) => {
    // If the file list needs to be converted into JSX, do it here. E.g.:
    const mappedList = list.map((item, index) => {
        return (
            <p key={index}>{item}</p>
        );
    });
    setArticoli(mappedList);

    // Otherwise, just set the value directly:
    setArticoli(list);
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using React.
I have two files: biologia.js and fleekstorage-functions.js
In fleekstorage-functions.js there are Fleek Storage method that can list files from my bucket:

const ListFiles = async () => {
    const input = {
        apiKey,
        apiSecret,
        getOptions: [
            'bucket',
            'key',
            'hash',
            'publicUrl'
        ],
    };

    try {
        const result = await fleek.listFiles(input);
        return result
    } catch (e) {
        console.log('error', e);
    }
}

And in biologia.js I have:

var articoli = ListFiles()
const Biologia = () => {
    return (
        <>

Articoli di Biologia:

Qui si parlerà di biologia.

            {articoli}
        </>
    );
}

As you look I wanted to print on a page the output of ListFiles, but console returned me this error:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

Could you please help me to print the array and single elements of it on biologia.js?

Body:
Your main problem here seems to be that ListFiles() is an async function. In other words, it will always return a Promise, meaning var articoli = ListFiles() will always store a Promise inside articoli.

As indicated by the error you're seeing, a Promise isn't a renderable element. You'll have to wait for the Promise to be resolved, then transform the results as desired into what you want to render. For example, set up your state with a Hook:

const [articoli, setArticoli] = useState(null);

Then you can set the value after the Promise from ListFiles() has resolved:

ListFiles().then((list) => {
    // If the file list needs to be converted into JSX, do it here. E.g.:
    const mappedList = list.map((item, index) => {
        return (
            <p key={index}>{item}</p>
        );
    });
    setArticoli(mappedList);

    // Otherwise, just set the value directly:
    setArticoli(list);
});


问:
Nodejs and Sequelize Limitations regarding creating dynamic models
I've a simple question related to my scenario. I've a react frontend where admin have a form to define it's own sign up form for the users.

Admin will send a set of fields with it's data types

Backend NodeJs will take those fields and run some script/function to create table in a database with the data types accordingly

It also needs to create a model for the respective table dynamically
I'm just finding a way to get it done. Any alternate solution is welcomed or any suggestions to refine my scenario?
Thanks in advance

答:
You can just map all indicated fields into field definitions for Sequielize like:

    fieldName: {
        field: 'field_name',
        type: DataTypes.TEXT,
        allowNull: false
    },
```
<p>and call <code>sequelize.define</code> which will return you a Sequilize model that you can use to execute queries:</p>
<pre class="lang-js prettyprint-override"><code>// NOTE "sequelize" should be an instance of Sequelize, i.e. an existing connection.
function registerModel(tableName, modelName, fields) {
  const model = sequelize.define(modelName, {
    ...fields
  }, {
    tableName: tableName,
    timestamps: false,
  });
  return model;
}
</code>```

Register a new model:

const fields = [{
    fieldName: {
        field: 'field_name',
        type: DataTypes.TEXT,
        allowNull: false
    },
}]
const newModel = registerModel('some_table', 'someModel', fields);
```
<p>Use the registered model:</p>
<pre class="lang-js prettyprint-override"><code>  const items = await newModel.findAll({
    where: {
      // some conditions
    }
  })
</code>```

Body:
You can just map all indicated fields into field definitions for Sequielize like:

    fieldName: {
        field: 'field_name',
        type: DataTypes.TEXT,
        allowNull: false
    },

and call sequelize.define which will return you a Sequilize model that you can use to execute queries:

// NOTE "sequelize" should be an instance of Sequelize, i.e. an existing connection.
function registerModel(tableName, modelName, fields) {
  const model = sequelize.define(modelName, {
    ...fields
  }, {
    tableName: tableName,
    timestamps: false,
  });
  return model;
}

Register a new model:

const fields = [{
    fieldName: {
        field: 'field_name',
        type: DataTypes.TEXT,
        allowNull: false
    },
}]
const newModel = registerModel('some_table', 'someModel', fields);

Use the registered model:

  const items = await newModel.findAll({
    where: {
      // some conditions
    }
  })


问:
Distance Point Cloud to Mesh in Python
I have a large 3D point cloud and a mesh consisting of triangular elements. I need to calculate the minimum distance of every point to the mesh as described in this paper (https://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf). However, because of the large number of points and elements a brute force approach is not feasible.

It is my understanding that storing the elements and data points in a tree-structure (e.g. octree), would considerably speed up the calculation.

Is there a Python library that would allow me to do the calculation very efficiently even for a large number of points and elements?

答:
Unfortunately I cannot comment, but if I am not mistaken, Tobi's very helpful answer is lacking normalization of the normal vectors, resulting in wrong absolute distance-values. This can be solved using np.linalg.norm:

```<code>normals = np.cross(plane_vecs[:, 0, :], plane_vecs[:, 1, :], axis=1)
normals_norm = normals / (np.linalg.norm(normals, ord=2, axis=1)[:, None])
</code>```

Also, be aware that the sign of the distances is not giving a direction of the distance.

Title: Distance Point Cloud to Mesh in Python

Body:
Unfortunately I cannot comment, but if I am not mistaken, Tobi's very helpful answer is lacking normalization of the normal vectors, resulting in wrong absolute distance-values. This can be solved using np.linalg.norm:

normals = np.cross(plane_vecs[:, 0, :], plane_vecs[:, 1, :], axis=1)
normals_norm = normals / (np.linalg.norm(normals, ord=2, axis=1)[:, None])

Also, be aware that the sign of the distances is not giving a direction of the distance.


问:
How to compare the content of 2 columns in functions on object?
I am trying to build a query to match two columns and I have tried the following:

```<code>obj= obj.filter(e => e.colOne.exactMatch(e.colTwo))
</code>```

I am not be able to get this working, is there any way to filter by comparing the content of 2 columns?

答:
It is not possible to compare two columns when writing Functions. A recommended strategy here would be to create a new column that captures your equality. For example in your pyspark pipeline, right before you generate the end objects that get indexed:

```<code>df.withColumn("colOneEqualsColTwo", F.when(
     F.col("colOne") == F.col("colTwo"), True
).otherwise(False)
</code>```

And then filter on that new column:

```<code>obj = obj.filter(e => e.colOneEqualsColTwo.exactMatch(true))
</code>```

Body:
I am trying to build a query to match two columns and I have tried the following:

obj= obj.filter(e => e.colOne.exactMatch(e.colTwo))

I am not be able to get this working, is there any way to filter by comparing the content of 2 columns?

Body:
It is not possible to compare two columns when writing Functions. A recommended strategy here would be to create a new column that captures your equality. For example in your pyspark pipeline, right before you generate the end objects that get indexed:

df.withColumn("colOneEqualsColTwo", F.when(
     F.col("colOne") == F.col("colTwo"), True
).otherwise(False)

And then filter on that new column:

obj = obj.filter(e => e.colOneEqualsColTwo.exactMatch(true))


问:
How to use BeautifulSoup 4 to extract Tweet text?
Tweets are found under a class called TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text.

I tried scraping with BeautifulSoup 4 to obtain the Tweet text only, but I don't get the Tweet text, I only get the class printed. How can I get only the Tweet text? I only want the part highlighted in yellow in the screenshot below:

Script

```<code>import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html")

tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})

content = str(tweet_text)

print(content)
</code>```

Actual output:

<p class="TweetTextSize TweetTextSize--jumbo js-tw

Expected output:

i’m gonna need to take a moment to formulate an opinion and i’ll try to get back to y’all

答:
I was able to get the text from the tweet, i then used regex to remove a link of a child element that was showing up.
Hope it helped!</p>
```<code>import bs4
from bs4 import BeautifulSoup
import re
link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html.parser")

tweet_text = soup.find(
    "p", class_="TweetTextSize--jumbo").text
content = re.sub(r'http\S+', '', tweet_text)

strencode = content.encode("ascii", "ignore")
strdecode = strencode.decode()

print(strdecode)```
</code>```

Body:
Tweets are found under a class called TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text.

I tried scraping with BeautifulSoup 4 to obtain the Tweet text only, but I don't get the Tweet text, I only get the class printed. How can I get only the Tweet text? I only want the part highlighted in yellow in the screenshot below:

Script

import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html")

tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})

content = str(tweet_text)

print(content)

Actual output:

<p class="TweetTextSize TweetTextSize--jumbo js-tw

Expected output:

i’m gonna need to take a moment to formulate an opinion and i’ll try to get back to y’all

Body:
I was able to get the text from the tweet, i then used regex to remove a link of a child element that was showing up.
Hope it helped!

import bs4
from bs4 import BeautifulSoup
import re
link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html.parser")

tweet_text = soup.find(
    "p", class_="TweetTextSize--jumbo").text
content = re.sub(r'http\S+', '', tweet_text)

strencode = content.encode("ascii", "ignore")
strdecode = strencode.decode()

print(strdecode)```


问:
Why does Dapper throw an OracleException when i run a query or command with parameters?
I am evaluation dapper but i already running into some problems.

I am trying to do this

```<code>using (IDbConnection connection = GetConnection())
{
    connection.Open();
    var result = connection.Query(
        "select * from myTable where ID_PK = @a;", new { a = 1 });
}
</code>```

It throws an ORA-00936: missing expression OracleException at line 393 in the SqlMapper.cs

```<code>using (var reader = cmd.ExecuteReader())
</code>```

When i remove the parameter i get the whole table into the result variable.

The query works without problems in sqldeveloper. I am using the Oracle.DataAccess Assembly 2.112.2.0

答: I think oracle has a different schema for named parameter, did you try :a instead of @a?

ContentLicense: CC BY-SA 3.0

Body:
I am evaluation dapper but i already running into some problems.

I am trying to do this

using (IDbConnection connection = GetConnection())
{
    connection.Open();
    var result = connection.Query(
        "select * from myTable where ID_PK = @a;", new { a = 1 });
}

It throws an ORA-00936: missing expression OracleException at line 393 in the SqlMapper.cs

using (var reader = cmd.ExecuteReader())

When i remove the parameter i get the whole table into the result variable.

The query works without problems in sqldeveloper. I am using the Oracle.DataAccess Assembly 2.112.2.0


问:
Function that takes data structure and returns integer
I have received the following code challenge and I am not sure as to what to do. As a front-end developer, I have not used data structures up to this point as well. Any solutions or help would be greatly appreciated. Attached below is the whole challenge.

```<code>const data = [
  { max: 5, min: -23, code: 'ATGCAGTG', epoch: '1465992000000' },
  { max: 66, min: 33, code: 'CGCCCCGG', epoch: '1466078400000' },
  { max: 93, min: 26, code: 'AGCGCATT', epoch: '1466164800000' },
  { max: 56, min: 44, code: 'CCAGCTCG', epoch: '1466251200000' },
  { max: 29, min: 19, code: 'GCTGTAGT', epoch: '1466337600000' },
  { max: 21, min: -66, code: 'TGGTGATT', epoch: '1466424000000' },
  { max: 91, min: 76, code: 'TCACAGCA', epoch: '1466510400000' },
  { max: 86, min: -14, code: 'TAGAGCCT', epoch: null },
  { max: 63, min: 23, code: 'TTCTCCCG', epoch: '1466683200000' },
];
</code>```

INSTRUCTIONS

Write a function (which may use other functions) that takes the above data structure as input and returns an integer which is the largest difference between max and min, where  code starts with the character
'T' or 'C' and contains the sequence 'AG', and epoch represents a weekday.

The fields max and min will be positive or negative integers, code and epoch will always be a string.

The field epoch may be null.

You may use javascript Date and Math functions. Please avoid using external libraries. Please code in javascript.

答:
So if i understood correctly, the epoch may be null, but it cannot be Saturday or Sunday. If this is the case, this would be a possible solution</p>
```<code>const findMax = (data) => {
 const result = data.filter(element => {
    const isWeekDay = new Date(+element.epoch)
    if(isWeekDay.toString().includes("Sat") || isWeekDay.toString().includes("Sun")){
        return false
    } else {
        return true
    }
}).filter(element => {
    if(element.code.slice(0,1) == "T" || element.code.slice(0,1) == "C"){
        return true
    } else {
        return false
    }
}).filter(element=> element.code.includes("AG")).map(element=> {
    element.difference = element.max - element.min
    return element
}).reduce((prev, curr) => {
      return Math.max(prev.difference, curr.difference)
})
 return result
}

console.log(findMax(data))
</code>```

Body:
I have received the following code challenge and I am not sure as to what to do. As a front-end developer, I have not used data structures up to this point as well. Any solutions or help would be greatly appreciated. Attached below is the whole challenge.

const data = [
  { max: 5, min: -23, code: 'ATGCAGTG', epoch: '1465992000000' },
  { max: 66, min: 33, code: 'CGCCCCGG', epoch: '1466078400000' },
  { max: 93, min: 26, code: 'AGCGCATT', epoch: '1466164800000' },
  { max: 56, min: 44, code: 'CCAGCTCG', epoch: '1466251200000' },
  { max: 29, min: 19, code: 'GCTGTAGT', epoch: '1466337600000' },
  { max: 21, min: -66, code: 'TGGTGATT', epoch: '1466424000000' },
  { max: 91, min: 76, code: 'TCACAGCA', epoch: '1466510400000' },
  { max: 86, min: -14, code: 'TAGAGCCT', epoch: null },
  { max: 63, min: 23, code: 'TTCTCCCG', epoch: '1466683200000' },
];

INSTRUCTIONS

Write a function (which may use other functions) that takes the above data structure as input and returns an integer which is the largest difference between max and min, where  code starts with the character
'T' or 'C' and contains the sequence 'AG', and epoch represents a weekday.

The fields max and min will be positive or negative integers, code and epoch will always be a string.

The field epoch may be null.

You may use javascript Date and Math functions. Please avoid using external libraries. Please code in javascript.

Body:
So if i understood correctly, the epoch may be null, but it cannot be Saturday or Sunday. If this is the case, this would be a possible solution

const findMax = (data) => {
 const result = data.filter(element => {
    const isWeekDay = new Date(+element.epoch)
    if(isWeekDay.toString().includes("Sat") || isWeekDay.toString().includes("Sun")){
        return false
    } else {
        return true
    }
}).filter(element => {
    if(element.code.slice(0,1) == "T" || element.code.slice(0,1) == "C"){
        return true
    } else {
        return false
    }
}).filter(element=> element.code.includes("AG")).map(element=> {
    element.difference = element.max - element.min
    return element
}).reduce((prev, curr) => {
      return Math.max(prev.difference, curr.difference)
})
 return result
}

console.log(findMax(data))


问:
HowTo Flatten simple Json file in Azure Synapse Spark Notebook and convert to Parquet
I needed to flatten a simple Json file (json lines) and convert it into a Parquet format within a Spark Notebook in Azure Synapse Analytics.
There is only one level of nested object for any column.  However, I discovered that getting the schema of the dataframe did not return the schema of the nested object.  I was using c# so that other company developers would not have to learn the other supported languages.</p>

答:
The code below will work for the situation indicated above.  Hope it saves someone else a few hours.
It also drops the parent column from the data frame after the properties of the child are added into the parent dataframe.

I had no need to make this code into a recursive transversal because we have no nested objects.

```<code>using System;
using System.Collections.Generic;
using Microsoft.Spark.Sql;
using Microsoft.Spark.Sql.Types;
using System.Diagnostics;

var df = spark.Read().Json("{Your source file path here}");

//get the schema of the data frame
var dfSchema = df.Schema() ;
// traverse the schema of the dataframe
foreach(var parentSchemaField in dfSchema.Fields) {

    if (parentSchemaField.DataType is StructType) {
        // get a new dataframe that just contains the child data from the parent
        var childFrame = df.Select($"{parentSchemaField.Name}.*") ;
        // traverse the schema of the child dataframe
        foreach(var childSchemaField in childFrame.Schema().Fields) {
            //make a new column in the parent dataframe for each parents child property
            df = df.WithColumn($"{parentSchemaField.Name}.{childSchemaField.Name}",Col($"{parentSchemaField.Name}.{childSchemaField.Name}")) ;
        }
        // drop the parent column from the data frame its no longer needed
        df = df.Drop(parentSchemaField.Name) ;
    }
}
df.Write().Parquet("{Your sink file path here}") ;
</code>```

Body:
The code below will work for the situation indicated above.  Hope it saves someone else a few hours.
It also drops the parent column from the data frame after the properties of the child are added into the parent dataframe.

I had no need to make this code into a recursive transversal because we have no nested objects.

using System;
using System.Collections.Generic;
using Microsoft.Spark.Sql;
using Microsoft.Spark.Sql.Types;
using System.Diagnostics;

var df = spark.Read().Json("{Your source file path here}");

//get the schema of the data frame
var dfSchema = df.Schema() ;
// traverse the schema of the dataframe
foreach(var parentSchemaField in dfSchema.Fields) {

    if (parentSchemaField.DataType is StructType) {
        // get a new dataframe that just contains the child data from the parent
        var childFrame = df.Select($"{parentSchemaField.Name}.*") ;
        // traverse the schema of the child dataframe
        foreach(var childSchemaField in childFrame.Schema().Fields) {
            //make a new column in the parent dataframe for each parents child property
            df = df.WithColumn($"{parentSchemaField.Name}.{childSchemaField.Name}",Col($"{parentSchemaField.Name}.{childSchemaField.Name}")) ;
        }
        // drop the parent column from the data frame its no longer needed
        df = df.Drop(parentSchemaField.Name) ;
    }
}
df.Write().Parquet("{Your sink file path here}") ;


问:
How can I insert into a table that is connected to another table with a 1-1 relationship

I dont know much about SQL, and I've got a problem using it.

I have two tables that connected to each other 1-1

Tbl1 (int_id1, str_desc1,....) and

Tbl2 (int_id2, str_desc2,....)

And these two are connected to each other
int_id1  ----  int_id2

First I want to know that is my design true?

And how can I insert into one of these of two together.

Cause I've got problem when I try to insert into one

here's the error description:

The INSERT statement conflicted with the FOREIGN KEY constraint
  "FK_Tbl2_Tbl1". The conflict occurred in database "project", table
  "dbo.Tbl1", column 'int_id1'.

Tnx...

答:
Assuming you have 2 tables that have a 1to1 relationship.  You can use a transaction to add rows to each.  Lets say you have a Classes and Professors table, with a 1to1 relationship.  Then you would do something like this:</p>
```<code>begin tran;

insert into Classes (title) values ('Math 101');
insert into Professors(name) values ('Tim Rogers');

commit tran;

begin tran;

insert into Classes (title) values ('History 101');
insert into Professors(name) values ('Suzanne Bethany');

insert into Classes (title) values ('PE 101');
insert into Professors(name) values ('Emily Williams');

commit tran;

select * from Classes;
select * from Professors;
</code>```

Body:
Assuming you have 2 tables that have a 1to1 relationship.  You can use a transaction to add rows to each.  Lets say you have a Classes and Professors table, with a 1to1 relationship.  Then you would do something like this:

begin tran;

insert into Classes (title) values ('Math 101');
insert into Professors(name) values ('Tim Rogers');

commit tran;

begin tran;

insert into Classes (title) values ('History 101');
insert into Professors(name) values ('Suzanne Bethany');

insert into Classes (title) values ('PE 101');
insert into Professors(name) values ('Emily Williams');

commit tran;

select * from Classes;
select * from Professors;


问:
Dynamic scoped dependency resolution in a console app for multiple tenants using dependency injection
In case of a Web API, each request is a distinct scope and dependencies registered as scoped will get resolved per request. So resolving dependencies per request per tenant is easy as the tenant information (like TenantId) can be passed in the HTTP Request headers like below:

```<code>services.TryAddScoped<ITenantContext>(x =>
{
    var context = x.GetService<IHttpContextAccessor>().HttpContext;
    var tenantId = context.Request.Headers["TenantId"].ToString();
    var tenantContext = GetTenantContext(tenantId);
    return tenantContext;
}
</code>```

Other registrations first resolve TenantContext and use it to resolve other dependencies. For example, IDatabase will be registered as below. During resolution it will resolve and connect to specific tenant database.

```<code>services.TryAddScoped<IDatabase>(x =>
{
    var tenantContext = x.GetService<ITenantContext>();
    return new Database(tenantContext.DatabaseConnectionString);
}
</code>```

This is all good in a Web API service because each request is a scope. I am facing challenges using dependency injection in a multi-tenant Console App. Suppose the app processes items from a
multi-tenant queue and each message can belong to a different tenant. While processing each message, it commits data to tenant specific database. So in this case the scope is each message in a queue and message contains the tenantId.

So when the app reads a message from queue, it needs to get TenantContext. Then resolve other dependencies based on this TenantContext.

One straightforward option I see how this dynamic resolution can be achieved is to create the dependent objects manually using the TenantContext but then I wouldn't be able to leverage dependency injection. All objects would get created manually and disposed after going out of scope after the message is processed.

```<code>var messgage = GetMessageFromQueue(queueName);
var tenantContext = GetTenantContext(message.TenantId);
var database = GetDatabaseObject(tenantContext);
// Do other processing now we got the database object connected to specific tenant DB
</code>```

Is there an option in DI where I can pass in the TenantId dynamically so that TenantContext gets set for this scope and then all further resolution within this scope leverage this TenantContext?

答:
Because the role of the tenancy goes beyond the implementation ("this uses X database") and is actually contextual to the action being performed ("this uses X database and must use this connection string based on the context being handled in the action"), there's some risk of assuming that ambient context is present in alternate implementations due to it not expressly being described in your interface in some way, which is where the DI issue is coming up here.

You might be able to:

Update your interfaces so that the tenancy information is an expected parameter of your methods. This ensures that regardless of future implementation, the presence of the tenant ID is explicit in their signature:

```<code>public interface ITenantDatabase {
   public TResponse Get(string TenantId, int Id);
   //... other methods ...
}
</code>```

Add a factory wrapper around your existing interfaces to handle assigning the context at object creation and have that factory return the IDatabase instance. This is basically what you are proposing manually but with an abstraction around it that you could register and inject to keep the code that leverages it from being responsible for the logic:

```<code>public interface ITenantDatabaseFactory {
   public IDatabase GetDatabaseForTenant(int TenantId);
}

// Add an implementation that manually generates and returns the scoped objects
</code>```

Body:
In case of a Web API, each request is a distinct scope and dependencies registered as scoped will get resolved per request. So resolving dependencies per request per tenant is easy as the tenant information (like TenantId) can be passed in the HTTP Request headers like below:

services.TryAddScoped<ITenantContext>(x =>
{
    var context = x.GetService<IHttpContextAccessor>().HttpContext;
    var tenantId = context.Request.Headers["TenantId"].ToString();
    var tenantContext = GetTenantContext(tenantId);
    return tenantContext;
}

Other registrations first resolve TenantContext and use it to resolve other dependencies. For example, IDatabase will be registered as below. During resolution it will resolve and connect to specific tenant database.

services.TryAddScoped<IDatabase>(x =>
{
    var tenantContext = x.GetService<ITenantContext>();
    return new Database(tenantContext.DatabaseConnectionString);
}

This is all good in a Web API service because each request is a scope. I am facing challenges using dependency injection in a multi-tenant Console App. Suppose the app processes items from a
multi-tenant queue and each message can belong to a different tenant. While processing each message, it commits data to tenant specific database. So in this case the scope is each message in a queue and message contains the tenantId.

So when the app reads a message from queue, it needs to get TenantContext. Then resolve other dependencies based on this TenantContext.

One straightforward option I see how this dynamic resolution can be achieved is to create the dependent objects manually using the TenantContext but then I wouldn't be able to leverage dependency injection. All objects would get created manually and disposed after going out of scope after the message is processed.

var messgage = GetMessageFromQueue(queueName);
var tenantContext = GetTenantContext(message.TenantId);
var database = GetDatabaseObject(tenantContext);
// Do other processing now we got the database object connected to specific tenant DB

Is there an option in DI where I can pass in the TenantId dynamically so that TenantContext gets set for this scope and then all further resolution within this scope leverage this TenantContext?

Body:
Because the role of the tenancy goes beyond the implementation ("this uses X database") and is actually contextual to the action being performed ("this uses X database and must use this connection string based on the context being handled in the action"), there's some risk of assuming that ambient context is present in alternate implementations due to it not expressly being described in your interface in some way, which is where the DI issue is coming up here.

You might be able to:

Update your interfaces so that the tenancy information is an expected parameter of your methods. This ensures that regardless of future implementation, the presence of the tenant ID is explicit in their signature:

public interface ITenantDatabase {
   public TResponse Get(string TenantId, int Id);
   //... other methods ...
}

Add a factory wrapper around your existing interfaces to handle assigning the context at object creation and have that factory return the IDatabase instance. This is basically what you are proposing manually but with an abstraction around it that you could register and inject to keep the code that leverages it from being responsible for the logic:

public interface ITenantDatabaseFactory {
   public IDatabase GetDatabaseForTenant(int TenantId);
}

// Add an implementation that manually generates and returns the scoped objects


问:
What is the fastest way to find partial string in arrays with filter using lodash?
Is there any way to find a partial string in an array more quickly than I have below?

Here is my example data:

```<code>const products = [
  {
    "product": "test1",
    "price": 11
  },
  {
    "product": "test2",
    "price": 31
  },
  {
    "product": "xxxx",
    "price": 21
  },
  {
    "product": "ssss",
    "price": 22
  },
]
</code>```

Here are my keywords (but in reality, there are a lot more):

```<code>const keywords = [ "test", "xx" ]
</code>```

I want to filter products with keywords then sum all product price my output should be

```
63
```

Here is what I tried to do: I filter my products first, I'm using indexOf because it faster than includes:

```<code>const fil = _.filter(products, (product) => {
    return _.some(keywords, (v) => product.name.indexOf(v) >= 0 );
});
</code>```

then I sum them using reduce:

```<code>const sum = fil.reduce(function (sum, data) {
    return sum + data.price;
}, 0);
</code>```

Everything works well but if I have to work with around 300k elements and 100k keywords, it takes around 3 min to find this query. Is there any way to decrease that time? (The product values are very unique, there aren't a lot of duplicates.)

答:
You've said you only need the sum, not the list of filtered products, so we can reduce that time slightly, but probably not by a lot, by:

Reducing the amount of memory churn by not producing an array we don't need

Not making two passes through products when we only need one.

Avoiding function calls (although function calls are fast in JavaScript engines)

So:

```<code>let sum = 0;
for (const {product, price} of products) {
    for (const keyword of keywords) {
        if (product.includes(keyword)) {
            sum += price;
            break;
        }
    }
}
</code>```

That uses the new(ish) for-of loop. Under the covers, though, for-of involves function calls and creating objects (although when looping through a native array, the JavaScript engine may be able to optimize those away entirely). You might want to try it against a classic for loop to see which gives you the best speed:

```<code>let sum = 0;
let productsLength = products.length;
let keywordsLength = keywords.length;
let pIndex, kIndex;
for (pIndex = 0; pIndex < productsLength; ++pIndex) {
    const {product, price} = products[pIndex];
    for (kIndex = 0; kIndex < keywordsLength; ++kIndex) {
        if (product.includes(keywords[kIndex])) {
            sum += price;
            break;
        }
    }
}
</code>```

Similarly, experiment with putting the loop variables inside the for (...) part vs. having them outside as above, but I'd tend to think outside would be just that tiny bit faster (because of how let works in for loops).

And finally, you might compare that against using the native (not lodash) forEach and some methods rather than for loops.

Body:
Is there any way to find a partial string in an array more quickly than I have below?

Here is my example data:

const products = [
  {
    "product": "test1",
    "price": 11
  },
  {
    "product": "test2",
    "price": 31
  },
  {
    "product": "xxxx",
    "price": 21
  },
  {
    "product": "ssss",
    "price": 22
  },
]

Here are my keywords (but in reality, there are a lot more):

const keywords = [ "test", "xx" ]

I want to filter products with keywords then sum all product price my output should be

63

Here is what I tried to do: I filter my products first, I'm using indexOf because it faster than includes:

const fil = _.filter(products, (product) => {
    return _.some(keywords, (v) => product.name.indexOf(v) >= 0 );
});

then I sum them using reduce:

const sum = fil.reduce(function (sum, data) {
    return sum + data.price;
}, 0);

Everything works well but if I have to work with around 300k elements and 100k keywords, it takes around 3 min to find this query. Is there any way to decrease that time? (The product values are very unique, there aren't a lot of duplicates.)

Body:
You've said you only need the sum, not the list of filtered products, so we can reduce that time slightly, but probably not by a lot, by:

Reducing the amount of memory churn by not producing an array we don't need

Not making two passes through products when we only need one.

Avoiding function calls (although function calls are fast in JavaScript engines)

So:

let sum = 0;
for (const {product, price} of products) {
    for (const keyword of keywords) {
        if (product.includes(keyword)) {
            sum += price;
            break;
        }
    }
}

That uses the new(ish) for-of loop. Under the covers, though, for-of involves function calls and creating objects (although when looping through a native array, the JavaScript engine may be able to optimize those away entirely). You might want to try it against a classic for loop to see which gives you the best speed:

let sum = 0;
let productsLength = products.length;
let keywordsLength = keywords.length;
let pIndex, kIndex;
for (pIndex = 0; pIndex < productsLength; ++pIndex) {
    const {product, price} = products[pIndex];
    for (kIndex = 0; kIndex < keywordsLength; ++kIndex) {
        if (product.includes(keywords[kIndex])) {
            sum += price;
            break;
        }
    }
}

Similarly, experiment with putting the loop variables inside the for (...) part vs. having them outside as above, but I'd tend to think outside would be just that tiny bit faster (because of how let works in for loops).

And finally, you might compare that against using the native (not lodash) forEach and some methods rather than for loops.


问:
Doc2Vec results not as expected
I'm evaluating Doc2Vec for a recommender API. I wasn't able to find a decent pre-trained model, so I trained a model on the corpus, which is about 8,000 small documents.

```<code>    model = Doc2Vec(vector_size=25,
                    alpha=0.025,
                    min_alpha=0.00025,
                    min_count=1,
                    dm=1)
</code>```

I then looped through the corpus to find similar documents for each document. Results were not very good (in comparison to TF-IDF). Note this is after testing different epochs and vector sizes.

```<code>    inferred_vector = model.infer_vector(row['cleaned'].split())
    sims = model.docvecs.most_similar([inferred_vector], topn=4)
</code>```

I also tried extracting the trained vectors and using cosine_similarty, but results were oddly even worse.

```<code>cosine_similarities = cosine_similarity(model.docvecs.vectors_docs, model.docvecs.vectors_docs)
</code>```

Am I doing something wrong or is the smallish corpus the problem?

Edit:
Prep and training code

```<code>def unesc(s):
    for idx, row in s.iteritems():
        s[idx] = html.unescape(row)
    return s

custom_pipeline = [
    preprocessing.lowercase,
    unesc,
    preprocessing.remove_urls,
    preprocessing.remove_html_tags,
    preprocessing.remove_diacritics,
    preprocessing.remove_digits,
    preprocessing.remove_punctuation,
    lambda s: hero.remove_stopwords(s, stopwords=custom_stopwords),
    preprocessing.remove_whitespace,
    preprocessing.tokenize
]

ds['cleaned'] = ds['body'].pipe(hero.clean, pipeline=custom_pipeline)
w2v_total_data = list(ds['cleaned'])
tag_data = [TaggedDocument(words=doc, tags=[str(i)]) for i, doc in enumerate(w2v_total_data)]

model = Doc2Vec(vector_size=25,
                alpha=0.025,
                min_alpha=0.00025,
                min_count=1,
                epochs=20,
                dm=1)

model.build_vocab(tag_data)
model.train(tag_data, total_examples=model.corpus_count, epochs=model.epochs)
model.save("lmdocs_d2v.model")
</code>```

答:
Without seeing your training code, there could easily be errors in text prep & training. Many online code examples are bonkers wrong in their Doc2Vec training technique!

Note that min_count=1 is essentially always a bad idea with this sort of algorithm: any example suggesting that was likely from a misguided author.

Is a mere .split() also the only tokenization applied for training? (The inference list-of-tokens should be prepped the same as the training lists-of-tokens.)

How was "not very good" and "oddly even worse" evaluated? For example, did the results seem arbitrary, or in-the-right-direction-but-just-weak?

"8,000 small documents" is a bit on the thin side for a training corpus, but it somewhat depends on "how small" – a few words, a sentence, a few sentences? Moving to smaller vectors, or more training epochs, can sometimes make the best of a smallish training set - but this sort of algorithm works best with lots of data, such that dense 100d-or-more vectors can be trained.

Title: Doc2Vec results not as expected

Body:
I'm evaluating Doc2Vec for a recommender API. I wasn't able to find a decent pre-trained model, so I trained a model on the corpus, which is about 8,000 small documents.

    model = Doc2Vec(vector_size=25,
                    alpha=0.025,
                    min_alpha=0.00025,
                    min_count=1,
                    dm=1)

I then looped through the corpus to find similar documents for each document. Results were not very good (in comparison to TF-IDF). Note this is after testing different epochs and vector sizes.

    inferred_vector = model.infer_vector(row['cleaned'].split())
    sims = model.docvecs.most_similar([inferred_vector], topn=4)

I also tried extracting the trained vectors and using cosine_similarty, but results were oddly even worse.

cosine_similarities = cosine_similarity(model.docvecs.vectors_docs, model.docvecs.vectors_docs)

Am I doing something wrong or is the smallish corpus the problem?

Edit:
Prep and training code

def unesc(s):
    for idx, row in s.iteritems():
        s[idx] = html.unescape(row)
    return s

custom_pipeline = [
    preprocessing.lowercase,
    unesc,
    preprocessing.remove_urls,
    preprocessing.remove_html_tags,
    preprocessing.remove_diacritics,
    preprocessing.remove_digits,
    preprocessing.remove_punctuation,
    lambda s: hero.remove_stopwords(s, stopwords=custom_stopwords),
    preprocessing.remove_whitespace,
    preprocessing.tokenize
]

ds['cleaned'] = ds['body'].pipe(hero.clean, pipeline=custom_pipeline)
w2v_total_data = list(ds['cleaned'])
tag_data = [TaggedDocument(words=doc, tags=[str(i)]) for i, doc in enumerate(w2v_total_data)]

model = Doc2Vec(vector_size=25,
                alpha=0.025,
                min_alpha=0.00025,
                min_count=1,
                epochs=20,
                dm=1)

model.build_vocab(tag_data)
model.train(tag_data, total_examples=model.corpus_count, epochs=model.epochs)
model.save("lmdocs_d2v.model")


问:
**ERROR*** TypeError: Cannot read property 'replace' of undefined
I am facing this TypeError: "Cannot read property 'replace' of undefined" when I made a small application with nodejs, express.js, MongoDB, mongoose and when I connect my express applications with mongoose at that time when I replace my password I face this type of error

```<code>const mongoose = require('mongoose');

const dotenv = require('dotenv');

const app = require('./app');

dotenv.config({ path: './config.env' });

const DB = process.env.DATABASE.replace(
  '<PASSWORD>',
  process.env.DATABASE_PASSWORD
);

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log(con.connections);
    console.log('DB connection succesful!!');
  });

const port = process.env.PORT || 3001;

app.listen(port, (req, res) => {
  console.log(`App is running on ${port}...`);
});
</code>```

How to resolve this error?

答: The issue usually occurs due to not assigning the environment configuration file path properly. Pay attention to the dotenv.config({ path: './config.env' }); line. You are searching for the config.env file within the current folder. Make sure that the file exists on the current working directory. If not, assign the path of the config file properly. The issue will be solved right after that.

Body:
I am facing this TypeError: "Cannot read property 'replace' of undefined" when I made a small application with nodejs, express.js, MongoDB, mongoose and when I connect my express applications with mongoose at that time when I replace my password I face this type of error

const mongoose = require('mongoose');

const dotenv = require('dotenv');

const app = require('./app');

dotenv.config({ path: './config.env' });

const DB = process.env.DATABASE.replace(
  '<PASSWORD>',
  process.env.DATABASE_PASSWORD
);

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log(con.connections);
    console.log('DB connection succesful!!');
  });

const port = process.env.PORT || 3001;

app.listen(port, (req, res) => {
  console.log(`App is running on ${port}...`);
});

How to resolve this error?


问:
creating multiple plots for each file within lapply
I have several files which I am looping via lapply. Within lapply, I want to make for each file, 1 MAPLOT and 1 Volcano plot. Here is my code :

```<code>library(ggplot2)
library(dplyr)

files <- list.files(path = baseDir,pattern = "*.txt",full.names = T,recursive = F)

fun <- function(x){
  a <- basename(x)
  a <- gsub(".txt","",a)

  df <- read.table(x,header = TRUE,sep = "\t")
  df <- df[,c(1,(ncol(df)-5):(ncol(df)))]
  df <- mutate(df,threshold = ifelse(padj < 0.05,"sig","non-sig"))
  df$sigtype <- paste(df$threshold,df$type,sep="-")

  ## Make MAPLOT
  ggplot(df, aes(x = baseMean, y = log2FoldChange)) +
    scale_x_continuous(trans = "log10")+
    geom_point(aes(col = threshold), size = 1, shape = 20)+
    scale_color_manual(values = c("non-sig" = "gray70","sig" = "red")) +
    ylim(-5, 10)+geom_hline(yintercept = 0, linetype = "dashed",color = "black") +
    xlab("mean of normalized counts")+ theme_classic()

  ## Make Volcano plot
  ggplot(df, aes(x = log2FoldChange, y = -log10(padj))) +
    scale_x_continuous()+ geom_point()+ xlab("fold change")+ theme_classic()
}

lapply(files,fun)
</code>```

Running this under Rstudio, I expected it to generate 1 MAPLOT and 1 Volcano plot for every input file present in the character vector files(there are 8 input text files). But instead, it only plotted the 8 volcano plot.

What am I missing here?

Also I want to output all the volcano plots in 1 pdf(volcano.pdf), 1 per page and all the MAPLOT's in another pdf(maplot.pdf), 1 per page. How can I achieve this?

答:
Here is a mostly didactic example with dev.set, which I have run in a new R process without any open graphics devices:

## Report active device
dev.cur()
## null device
##           1

## Open device 2 and make it the active device
pdf("bar.pdf")
## Open device 3 and make it the active device
pdf("foo.pdf")

## List all open devices
dev.list()
## pdf pdf
##   2   3

f <- function() {
    ## Plot in device 3
    plot(1:10, 1:10, main = "foo")
    ## Cycle to device 2
    dev.set()
    ## Plot in device 2
    plot(rnorm(10L), rnorm(10L), main = "bar")
    ## Cycle to device 3
    dev.set()
    invisible(NULL)
}

## Call 'f' four times
replicate(4L, f())

## Close device 3 and report active device
dev.off()
## pdf
##   2

## Close device 2 and report active device
dev.off()
## null device
##           1

## Clean up
unlink(c("foo.pdf", "bar.pdf"))
```
<p>@Limey's suggestion is to work in one device at a time to avoid the bookkeeping required by <code>dev.set</code>:</p>
<pre class="lang-r prettyprint-override"><code>pdf("foo.pdf")
f1 <- function() {
    plot(1:10, 1:10, main = "foo")
    invisible(NULL)
}
replicate(4L, f1())
dev.off()

pdf("bar.pdf")
f2 <- function() {
    plot(rnorm(10L), rnorm(10L), main = "bar")
    invisible(NULL)
}
replicate(4L, f2())
dev.off()

unlink(c("foo.pdf", "bar.pdf"))
</code>```

Body:
I have several files which I am looping via lapply. Within lapply, I want to make for each file, 1 MAPLOT and 1 Volcano plot. Here is my code :

library(ggplot2)
library(dplyr)

files <- list.files(path = baseDir,pattern = "*.txt",full.names = T,recursive = F)

fun <- function(x){
  a <- basename(x)
  a <- gsub(".txt","",a)

  df <- read.table(x,header = TRUE,sep = "\t")
  df <- df[,c(1,(ncol(df)-5):(ncol(df)))]
  df <- mutate(df,threshold = ifelse(padj < 0.05,"sig","non-sig"))
  df$sigtype <- paste(df$threshold,df$type,sep="-")

  ## Make MAPLOT
  ggplot(df, aes(x = baseMean, y = log2FoldChange)) +
    scale_x_continuous(trans = "log10")+
    geom_point(aes(col = threshold), size = 1, shape = 20)+
    scale_color_manual(values = c("non-sig" = "gray70","sig" = "red")) +
    ylim(-5, 10)+geom_hline(yintercept = 0, linetype = "dashed",color = "black") +
    xlab("mean of normalized counts")+ theme_classic()

  ## Make Volcano plot
  ggplot(df, aes(x = log2FoldChange, y = -log10(padj))) +
    scale_x_continuous()+ geom_point()+ xlab("fold change")+ theme_classic()
}

lapply(files,fun)

Running this under Rstudio, I expected it to generate 1 MAPLOT and 1 Volcano plot for every input file present in the character vector files(there are 8 input text files). But instead, it only plotted the 8 volcano plot.

What am I missing here?

Also I want to output all the volcano plots in 1 pdf(volcano.pdf), 1 per page and all the MAPLOT's in another pdf(maplot.pdf), 1 per page. How can I achieve this?

Body:
Here is a mostly didactic example with dev.set, which I have run in a new R process without any open graphics devices:

## Report active device
dev.cur()
## null device
##           1

## Open device 2 and make it the active device
pdf("bar.pdf")
## Open device 3 and make it the active device
pdf("foo.pdf")

## List all open devices
dev.list()
## pdf pdf
##   2   3

f <- function() {
    ## Plot in device 3
    plot(1:10, 1:10, main = "foo")
    ## Cycle to device 2
    dev.set()
    ## Plot in device 2
    plot(rnorm(10L), rnorm(10L), main = "bar")
    ## Cycle to device 3
    dev.set()
    invisible(NULL)
}

## Call 'f' four times
replicate(4L, f())

## Close device 3 and report active device
dev.off()
## pdf
##   2

## Close device 2 and report active device
dev.off()
## null device
##           1

## Clean up
unlink(c("foo.pdf", "bar.pdf"))

@Limey's suggestion is to work in one device at a time to avoid the bookkeeping required by dev.set:

pdf("foo.pdf")
f1 <- function() {
    plot(1:10, 1:10, main = "foo")
    invisible(NULL)
}
replicate(4L, f1())
dev.off()

pdf("bar.pdf")
f2 <- function() {
    plot(rnorm(10L), rnorm(10L), main = "bar")
    invisible(NULL)
}
replicate(4L, f2())
dev.off()

unlink(c("foo.pdf", "bar.pdf"))


问:
Typescript - How to create a type with the same properties as an interface, but with different property types
I'm making a query builder. I have data models that look like this:

```<code>export interface SalesOrder {
  id: number
  customerName: string;
  date: Date;
}
</code>```

In my query builder, I want to have the columns look something like this:

```<code>{
  id: 'salesOrder.id',
  customerName: 'customer.name',
  date: 'salesOrder.date',
}
</code>```

I'm trying to figure out how I can type the Columns object generically so that it will have all the keys from the model, but all of the types will be a string. So then I would be able to declare it like const columns: Columns<SalesOrder> and it would understand that the object must have all the same keys as in the SalesOrder model, but with all the values being string.

I tried this:

```<code>export interface Columns<T> {
  [alias: keyof T]: string;
}
</code>```

But it complains about the keyof T part, saying "An index signature parameter type must be either 'string' or 'number'."

答:
The end of that error message should have been:

Consider using a mapped object type instead.

See the documentation on mapped types.

Here's what that means:

```<code>export type Columns<T> = {
  [alias in keyof T]: string;
}
</code>```

It needs to be a type, because this is actually a mapped type. It walks all possibilities of keyof T and evaluates each member of that union individually. This isn't really supported in interfaces.

And [key: MyType] is an index signature. It says that for any MyType there is a value of a consistent type. Where [key in MyType] define the keys of a mapped type.

Playground

Alternatively, you could try the Record type.

```<code>export type Columns<T> = Record<keyof T, string>
</code>```

Playground

Body:
I'm making a query builder. I have data models that look like this:

export interface SalesOrder {
  id: number
  customerName: string;
  date: Date;
}

In my query builder, I want to have the columns look something like this:

{
  id: 'salesOrder.id',
  customerName: 'customer.name',
  date: 'salesOrder.date',
}

I'm trying to figure out how I can type the Columns object generically so that it will have all the keys from the model, but all of the types will be a string. So then I would be able to declare it like const columns: Columns<SalesOrder> and it would understand that the object must have all the same keys as in the SalesOrder model, but with all the values being string.

I tried this:

export interface Columns<T> {
  [alias: keyof T]: string;
}

But it complains about the keyof T part, saying "An index signature parameter type must be either 'string' or 'number'."

Body:
The end of that error message should have been:

Consider using a mapped object type instead.

See the documentation on mapped types.

Here's what that means:

export type Columns<T> = {
  [alias in keyof T]: string;
}

It needs to be a type, because this is actually a mapped type. It walks all possibilities of keyof T and evaluates each member of that union individually. This isn't really supported in interfaces.

And [key: MyType] is an index signature. It says that for any MyType there is a value of a consistent type. Where [key in MyType] define the keys of a mapped type.

Playground

Alternatively, you could try the Record type.

export type Columns<T> = Record<keyof T, string>

Playground


问:
Nightwatch - How can I CSS select a nested button with no unique identifiers on the button itself
In image 'UI' I need to select the second 'Setup' button on the page.

I've tried many different combinations of trying to select this element but have had no luck. I've seen some related posts but most talk about having 1 parent and 1 or 2 child elements. In this case I need to go along this path: li2/div2/div/a. I'm just unsure of how to string that together.

Xpath is not an option unfortunately as the id changes from session to session.

UI

Inspecting the DOM

For additional context, the other options in the ul (Google Auth & Voice Auth) are identical to the SMS li.

Ideally, I would want to do something like this, but I feel that I am way off:

```<code>selector: 'li[data-se$="SMS"] + a[class$="button link-button"]'
</code>```

答:
I was able to select the button with use of the descendant combinator.

https://www.w3.org/TR/selectors-3/#descendant-combinators

```<code>selector: 'li[data-se="SMS"] * a[data-se$="button"]'
</code>```

Body:
In image 'UI' I need to select the second 'Setup' button on the page.

I've tried many different combinations of trying to select this element but have had no luck. I've seen some related posts but most talk about having 1 parent and 1 or 2 child elements. In this case I need to go along this path: li2/div2/div/a. I'm just unsure of how to string that together.

Xpath is not an option unfortunately as the id changes from session to session.

UI

Inspecting the DOM

For additional context, the other options in the ul (Google Auth & Voice Auth) are identical to the SMS li.

Ideally, I would want to do something like this, but I feel that I am way off:

selector: 'li[data-se$="SMS"] + a[class$="button link-button"]'

Body:
I was able to select the button with use of the descendant combinator.

https://www.w3.org/TR/selectors-3/#descendant-combinators

selector: 'li[data-se="SMS"] * a[data-se$="button"]'


问:
how to drop an index key from a table
I'm using sql server 2005/2008 and I have a table that it's PK (rec_index) is also indexed.

```<code>CREATE TABLE [dbo].[MyTable]
(
    [rec_index] INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    file_desc nvarchar(50),
    is_modified bit
)
</code>```

However unfortunately I already have a table like this in my DB which O created without the index.

How can I ask if the table already is indexed do nothing, else add an index?  I can't drop it and than re-create it since i will loose data.

I'm looking for something like "if not exists <index for rec_index> do <create index for rec_index>"

答:
maybe something like:</p>

```<code>IF NOT EXISTS ( select *
                  from sys.objects
                 where parent_object_id = object_id('MyTable')
                   and type = 'PK' )

do <create index for rec_index>
</code>```

Title: how to drop an index key from a table

Body:
I'm using sql server 2005/2008 and I have a table that it's PK (rec_index) is also indexed.

CREATE TABLE [dbo].[MyTable]
(
    [rec_index] INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    file_desc nvarchar(50),
    is_modified bit
)

However unfortunately I already have a table like this in my DB which O created without the index.

How can I ask if the table already is indexed do nothing, else add an index?  I can't drop it and than re-create it since i will loose data.

I'm looking for something like "if not exists <index for rec_index> do <create index for rec_index>"

Body:
maybe something like:

IF NOT EXISTS ( select *
                  from sys.objects
                 where parent_object_id = object_id('MyTable')
                   and type = 'PK' )

do <create index for rec_index>


问:
How could double validation be added in marshmallow "fields"?(PeeWee)
I send requests to a RESTful API. Also I have a PeeWee model to keep the responses. I check the validations with Marshmallow.

In the response body, there is a variable that is not certain data type(Integer or String). I want my PeeWee model have multiple validation.

Here is the example:

```<code>class Example(Schema):
    availableLimit = fields.Str(
        required=False, allow_none=True, validate=validate.Regexp(REGEX.NUMBER_LARGE)
    )
</code>```

In the API response, availableLimit have exactly 2 possibilities:  the string "UNLIMITED" or any Integer.
How can I validate it with the Marshmallow fields validation like validate=validate.Regexp(REGEX.NUMBER_LARGE && REGEX.UNLIMITED_STRING)?

Additionally REGEX.NUMBER_LARGE and REGEX.UNLIMITED_STRING are my patterns.

答:
I think you can import post_dump from marshmallow. You can then use post_dump as a decorator method in your schema class.

eg

```<code>from marshmallow import ValidationError, post_dump
class Example(Schema):
    availableLimit = fields.Str(required=False, allow_none=True,validate=validate.Regexp(REGEX.NUMBER_LARGE))
    @post_dump('availableLimit')
    def multiple_validation(self, value):
        ....
</code>```

I hope this is clear

Body:
I send requests to a RESTful API. Also I have a PeeWee model to keep the responses. I check the validations with Marshmallow.

In the response body, there is a variable that is not certain data type(Integer or String). I want my PeeWee model have multiple validation.

Here is the example:

class Example(Schema):
    availableLimit = fields.Str(
        required=False, allow_none=True, validate=validate.Regexp(REGEX.NUMBER_LARGE)
    )

In the API response, availableLimit have exactly 2 possibilities:  the string "UNLIMITED" or any Integer.
How can I validate it with the Marshmallow fields validation like validate=validate.Regexp(REGEX.NUMBER_LARGE && REGEX.UNLIMITED_STRING)?

Additionally REGEX.NUMBER_LARGE and REGEX.UNLIMITED_STRING are my patterns.

Body:
I think you can import post_dump from marshmallow. You can then use post_dump as a decorator method in your schema class.

eg

from marshmallow import ValidationError, post_dump
class Example(Schema):
    availableLimit = fields.Str(required=False, allow_none=True,validate=validate.Regexp(REGEX.NUMBER_LARGE))
    @post_dump('availableLimit')
    def multiple_validation(self, value):
        ....

I hope this is clear


问:
Loop through a tuple and printing each loop
I'm randomly generating a tuple from a dictionary. I want to run this a random number of times, and each run should return a true or false. How do I run this randomly N times and also have a counter and print out the amount of times it's True?</p>

答:
First, you need to generate a random number within a specified number range:

n = random.randint(0, 10)

Then, you need to add a base counter from which to count onto for each of the specified True outcomes:

```<code>reds = 0
blacks = 0
</code>```

When iterating with a for loop, you need to set the starting point and ending point. You were missing the starting index and a colon here. You say you want to loop a random number of times, which is where n comes into play:

```<code>for i in range(0, n):
</code>```

If the conditions are met, you want to increment either the reds or blacks variable by one, so you're able to see how many of each condition were True. I'd recommend changing your operator from < or > to <= or >=. As it's written, you aren't handling the third iteration of the loop. I left it in in my example below, because I'm not sure what your desired outcome is there.

At the end, you have something like this:

```<code>    n = random.randint(0, 10)
    bag = {}
    reds = 0
    blacks = 0
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1

        entry_list = list(bag.items())
        random_entry = random.choice(entry_list)
        print(random_entry)
    print(reds)
    print(blacks)
</code>```
```<code>(0, 'red')
(1, 'red')
(2, 'red')
(1, 'red')
(1, 'red')
(5, 'black')
(6, 'black')
(4, 'black')
(8, 'black')
3
5
</code>```

If you wanted to also explicitly keep track of True and False runs for each variable, you just add a little logic for that, as such:

```<code>    blackfalse = True
    redfalse = True
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
            blackfalse = True
            redfalse = False
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1
            redfalse = True
            blackfalse = False
        print(redfalse)
        print(blackfalse)
</code>```

Body:
First, you need to generate a random number within a specified number range:

n = random.randint(0, 10)

Then, you need to add a base counter from which to count onto for each of the specified True outcomes:

reds = 0
blacks = 0

When iterating with a for loop, you need to set the starting point and ending point. You were missing the starting index and a colon here. You say you want to loop a random number of times, which is where n comes into play:

for i in range(0, n):

If the conditions are met, you want to increment either the reds or blacks variable by one, so you're able to see how many of each condition were True. I'd recommend changing your operator from < or > to <= or >=. As it's written, you aren't handling the third iteration of the loop. I left it in in my example below, because I'm not sure what your desired outcome is there.

At the end, you have something like this:

    n = random.randint(0, 10)
    bag = {}
    reds = 0
    blacks = 0
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1

        entry_list = list(bag.items())
        random_entry = random.choice(entry_list)
        print(random_entry)
    print(reds)
    print(blacks)

(0, 'red')
(1, 'red')
(2, 'red')
(1, 'red')
(1, 'red')
(5, 'black')
(6, 'black')
(4, 'black')
(8, 'black')
3
5

If you wanted to also explicitly keep track of True and False runs for each variable, you just add a little logic for that, as such:

    blackfalse = True
    redfalse = True
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
            blackfalse = True
            redfalse = False
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1
            redfalse = True
            blackfalse = False
        print(redfalse)
        print(blackfalse)


问:
rewriting fetch api request with axios
I do have a simple fetch API call inside a React useEffect hook that works just fine:

```<code>useEffect(() => {
    (async () => {
      const foo = (await (await fetch('/api/foo')).json())
    })()
}, []);
</code>```

I am now trying to rewrite this api call using axios but all I get is...nothing. Here is one way I tried:

```<code>axios.get('/api/foo')
.then((res) => {
  console.log(res);
}).catch((error) => {
  console.log(error);
});
</code>```

Nothing happens, neither the res nor the error get logged in the console.

The funky thing though is that other (!) api urls work using axios. It is just this one request that leads to nothing?! What could be the problem here?

PS: In Postman, the /api/foo request returns a result (some json) just fine which makes it even more odd.

PPS: Even with Axios code generated directly from Postman nothing gets returned...?!!!

PPPS: When I look at the Promise that gets returned it keeps hanging in the "pending" state forever and does not get fulfilled.

答:
Did you set the default url?
Try axios.defaults.baseURL = 'https://api.example.com';
and then try:

```<code>axios.get('/api/foo')
.then((res) => {
  console.log(res);})
.catch((error) => {
  console.log(error);});
</code>```

Title: rewriting fetch api request with axios

Body:
I do have a simple fetch API call inside a React useEffect hook that works just fine:

useEffect(() => {
    (async () => {
      const foo = (await (await fetch('/api/foo')).json())
    })()
}, []);

I am now trying to rewrite this api call using axios but all I get is...nothing. Here is one way I tried:

axios.get('/api/foo')
.then((res) => {
  console.log(res);
}).catch((error) => {
  console.log(error);
});

Nothing happens, neither the res nor the error get logged in the console.

The funky thing though is that other (!) api urls work using axios. It is just this one request that leads to nothing?! What could be the problem here?

PS: In Postman, the /api/foo request returns a result (some json) just fine which makes it even more odd.

PPS: Even with Axios code generated directly from Postman nothing gets returned...?!!!

PPPS: When I look at the Promise that gets returned it keeps hanging in the "pending" state forever and does not get fulfilled.

Body:
Did you set the default url?
Try axios.defaults.baseURL = 'https://api.example.com';
and then try:

axios.get('/api/foo')
.then((res) => {
  console.log(res);})
.catch((error) => {
  console.log(error);});


问:
Check for Text within an Image C#. Is using memcmp an option?
I'm working on a research project which requires me to identify text within an image. Over the forum I saw a post of using memcmp, but I'm having no luck with this.

To give more details on my task :

I screen capture this. My image reads "GPS: Initial Location 34 45 23".

I then dip into a predefined map of images that I load at the start of my application.The map contains images for text - Initial, Reset, Launch, ....

How do I check if the image I captured matches to one of the predefined images in the map.

Kindly help.

Attaching a snapshot of code

```<code>public static bool CompareMemCmp(Bitmap b1, Bitmap b2)
{
  if ((b1 == null) != (b2 == null)) return false;

  var bd1 = b1.LockBits(new Rectangle(new Point(0, 0), b1.Size), ImageLockMode.ReadOnly, b1.PixelFormat);
  var bd2 = b2.LockBits(new Rectangle(new Point(0, 0), b2.Size), ImageLockMode.ReadOnly, b2.PixelFormat);

  try
  {
    IntPtr bd1scan0 = bd1.Scan0;
    IntPtr bd2scan0 = bd2.Scan0;

    int stride = bd1.Stride;
    int len = stride * b1.Height;

    int stride2 = bd2.Stride;
    int len2 = stride2 * b2.Height;

    for (int i = 0; i < len; ++i)
    {
      bd1scan0 = bd1.Scan0 + i;

      int test = memcmp(bd1scan0, bd2scan0, len2);
      if (test == 0)
      {
        Console.WriteLine("Found the string");
        return true;
      }
    }

    return false;
  }
  finally
  {
    b1.UnlockBits(bd1);
    b2.UnlockBits(bd2);
  }
}
</code>```

答: If you are looking for an exact match, i.e. a match where every bit is the same, you could use this approach. However, if this is not the case, other algorithms might be better. One example would be to use cross correlation. I used it to compare audio files and it works great. See this question</p>

Body:
I'm working on a research project which requires me to identify text within an image. Over the forum I saw a post of using memcmp, but I'm having no luck with this.

To give more details on my task :

I screen capture this. My image reads "GPS: Initial Location 34 45 23".

I then dip into a predefined map of images that I load at the start of my application.The map contains images for text - Initial, Reset, Launch, ....

How do I check if the image I captured matches to one of the predefined images in the map.

Kindly help.

Attaching a snapshot of code

public static bool CompareMemCmp(Bitmap b1, Bitmap b2)
{
  if ((b1 == null) != (b2 == null)) return false;

  var bd1 = b1.LockBits(new Rectangle(new Point(0, 0), b1.Size), ImageLockMode.ReadOnly, b1.PixelFormat);
  var bd2 = b2.LockBits(new Rectangle(new Point(0, 0), b2.Size), ImageLockMode.ReadOnly, b2.PixelFormat);

  try
  {
    IntPtr bd1scan0 = bd1.Scan0;
    IntPtr bd2scan0 = bd2.Scan0;

    int stride = bd1.Stride;
    int len = stride * b1.Height;

    int stride2 = bd2.Stride;
    int len2 = stride2 * b2.Height;

    for (int i = 0; i < len; ++i)
    {
      bd1scan0 = bd1.Scan0 + i;

      int test = memcmp(bd1scan0, bd2scan0, len2);
      if (test == 0)
      {
        Console.WriteLine("Found the string");
        return true;
      }
    }

    return false;
  }
  finally
  {
    b1.UnlockBits(bd1);
    b2.UnlockBits(bd2);
  }
}


问:
Mockito fails with inlined mocks enabled with Invalid paramter name exception
I've enabled inlined mocks so that I can mock final classes but now I get the following exception when running tests with Junit.

When I run all the tests at once only two tests fail, but if I run tests individually then most of them fail.

I'm not using any scala or android classes (that I'm aware of). I am using lombok but I tried removing lombok annotations any it didn't fix the problem.

When removing mock-maker-inline the problem goes away, but I'd rather keep it.

How should I address this problem?

```<code>org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.example.MyClass.

If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.112-b15
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_112-b15
JVM info           : mixed mode
OS name            : Windows 10
OS version         : 10.0

You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.

Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface java.lang.AutoCloseable, class com.example.MyClass, interface java.io.Closeable, class java.lang.Object]
    at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:42)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface java.lang.AutoCloseable, class com.example.MyClass, interface java.io.Closeable, class java.lang.Object]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    ... 18 more
Caused by: java.lang.IllegalStateException:
Byte Buddy could not instrument all classes within the mock's type hierarchy

This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:
 - Compiled by older versions of scalac
 - Classes that are part of the Android distribution
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:120)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.mockClass(InlineBytecodeGenerator.java:97)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMockType(InlineByteBuddyMockMaker.java:200)
    at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMock(InlineByteBuddyMockMaker.java:181)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
    at org.mockito.Mockito.mock(Mockito.java:1821)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:36)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
    ... 18 more
Caused by: java.lang.IllegalStateException: Error invoking java.lang.reflect.Executable#getParameters
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter$Dispatcher$ForJava8CapableVm.getParameter(ParameterDescription.java:387)
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter$Dispatcher$ForJava8CapableVm.isNamePresent(ParameterDescription.java:355)
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter.isNamed(ParameterDescription.java:227)
    at net.bytebuddy.description.method.ParameterDescription$AbstractBase.asToken(ParameterDescription.java:147)
    at net.bytebuddy.description.method.ParameterDescription$AbstractBase.asToken(ParameterDescription.java:107)
    at net.bytebuddy.description.method.ParameterList$AbstractBase.asTokenList(ParameterList.java:80)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asToken(MethodDescription.java:693)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asToken(MethodDescription.java:334)
    at net.bytebuddy.description.method.MethodList$AbstractBase.asTokenList(MethodList.java:53)
    at net.bytebuddy.dynamic.scaffold.InstrumentedType$Factory$Default$1.represent(InstrumentedType.java:223)
    at net.bytebuddy.ByteBuddy.redefine(ByteBuddy.java:698)
    at net.bytebuddy.ByteBuddy.redefine(ByteBuddy.java:676)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.transform(InlineBytecodeGenerator.java:167)
    at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
    at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
    at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:117)
    ... 38 more
Caused by: java.lang.reflect.MalformedParametersException: Invalid parameter name ""
    at java.lang.reflect.Executable.verifyParameters(Executable.java:386)
    at java.lang.reflect.Executable.privateGetParameters(Executable.java:416)
    at java.lang.reflect.Executable.getParameters(Executable.java:357)
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter$Dispatcher$ForJava8CapableVm.getParameter(ParameterDescription.java:383)
    ... 55 more
</code>```

Using mockito-core 2.13.0 and byte-buddy 1.7.9.

答: In my case, it was because my enum class that I wanted to mock (not exactly me but...) had a constructor with parameters that was marked with @org.springframework.lang.NonNull and then it failed with ArrayIndexOutOfBoundsException in the byte-buddy. So removing that annotation fixed the issue... The End.

Body:
I've enabled inlined mocks so that I can mock final classes but now I get the following exception when running tests with Junit.

When I run all the tests at once only two tests fail, but if I run tests individually then most of them fail.

I'm not using any scala or android classes (that I'm aware of). I am using lombok but I tried removing lombok annotations any it didn't fix the problem.

When removing mock-maker-inline the problem goes away, but I'd rather keep it.

How should I address this problem?

org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.example.MyClass.

If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.112-b15
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_112-b15
JVM info           : mixed mode
OS name            : Windows 10
OS version         : 10.0

You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.

Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface java.lang.AutoCloseable, class com.example.MyClass, interface java.io.Closeable, class java.lang.Object]
    at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:42)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface java.lang.AutoCloseable, class com.example.MyClass, interface java.io.Closeable, class java.lang.Object]
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    ... 18 more
Caused by: java.lang.IllegalStateException:
Byte Buddy could not instrument all classes within the mock's type hierarchy

This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:
 - Compiled by older versions of scalac
 - Classes that are part of the Android distribution
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:120)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.mockClass(InlineBytecodeGenerator.java:97)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMockType(InlineByteBuddyMockMaker.java:200)
    at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMock(InlineByteBuddyMockMaker.java:181)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
    at org.mockito.Mockito.mock(Mockito.java:1821)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:36)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
    ... 18 more
Caused by: java.lang.IllegalStateException: Error invoking java.lang.reflect.Executable#getParameters
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter$Dispatcher$ForJava8CapableVm.getParameter(ParameterDescription.java:387)
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter$Dispatcher$ForJava8CapableVm.isNamePresent(ParameterDescription.java:355)
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter.isNamed(ParameterDescription.java:227)
    at net.bytebuddy.description.method.ParameterDescription$AbstractBase.asToken(ParameterDescription.java:147)
    at net.bytebuddy.description.method.ParameterDescription$AbstractBase.asToken(ParameterDescription.java:107)
    at net.bytebuddy.description.method.ParameterList$AbstractBase.asTokenList(ParameterList.java:80)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asToken(MethodDescription.java:693)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asToken(MethodDescription.java:334)
    at net.bytebuddy.description.method.MethodList$AbstractBase.asTokenList(MethodList.java:53)
    at net.bytebuddy.dynamic.scaffold.InstrumentedType$Factory$Default$1.represent(InstrumentedType.java:223)
    at net.bytebuddy.ByteBuddy.redefine(ByteBuddy.java:698)
    at net.bytebuddy.ByteBuddy.redefine(ByteBuddy.java:676)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.transform(InlineBytecodeGenerator.java:167)
    at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
    at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
    at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
    at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:117)
    ... 38 more
Caused by: java.lang.reflect.MalformedParametersException: Invalid parameter name ""
    at java.lang.reflect.Executable.verifyParameters(Executable.java:386)
    at java.lang.reflect.Executable.privateGetParameters(Executable.java:416)
    at java.lang.reflect.Executable.getParameters(Executable.java:357)
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.bytebuddy.description.method.ParameterDescription$ForLoadedParameter$Dispatcher$ForJava8CapableVm.getParameter(ParameterDescription.java:383)
    ... 55 more

Using mockito-core 2.13.0 and byte-buddy 1.7.9.


问:
How to redirect cin and cout to files?
How can I redirect cin to in.txt and cout to out.txt?

答:
The accepted answer shows the right way to redirect cin and cout. You need to construct another stream object whose life time exceeds that of cin or cout. If you want to write a function works like freopen, you can alloc an array for each stream to be redirected, to save the allocated stream objects.

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

template<typename>
    struct fstream_traits { };
template<typename CharT, typename Traits>
    struct fstream_traits<basic_istream<CharT, Traits>> { using type = basic_ifstream<CharT, Traits>; };
template<typename CharT, typename Traits>
    struct fstream_traits<basic_ostream<CharT, Traits>> { using type = basic_ofstream<CharT, Traits>; };

template <typename Stream>
void redirect(Stream& str, string filename)
{
    using fstream_type = typename fstream_traits<Stream>::type;
    static int index = std::ios_base::xalloc();
    if (str.pword(index) == nullptr)
    {
        str.pword(index)= new vector<ios_base*>{};
        str.register_callback([](ios_base::event event, std::ios_base& stream, int index) {
            if (event == ios_base::erase_event)
            {
                for (auto fs : *(vector<ios_base*>*)stream.pword(index))
                    delete fs;
                delete (vector<ios_base*>*)stream.pword(index);
            }
        }, index);
    }
    vector<ios_base*>* list = (vector<ios_base*>*)str.pword(index);
    list->push_back(new fstream_type{filename});
    str.rdbuf(dynamic_cast<fstream_type*>(list->back())->rdbuf())->~basic_streambuf();
}

int main()
{
    redirect(cout, "out.txt");
    cout << "Redirected text!";
    return 0;
}
```

The template and alias are not required if you explicitly use istream/ostream instead of Stream.

Title: How to redirect cin and cout to files?

Body:
The accepted answer shows the right way to redirect cin and cout. You need to construct another stream object whose life time exceeds that of cin or cout. If you want to write a function works like freopen, you can alloc an array for each stream to be redirected, to save the allocated stream objects.

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

template<typename>
    struct fstream_traits { };
template<typename CharT, typename Traits>
    struct fstream_traits<basic_istream<CharT, Traits>> { using type = basic_ifstream<CharT, Traits>; };
template<typename CharT, typename Traits>
    struct fstream_traits<basic_ostream<CharT, Traits>> { using type = basic_ofstream<CharT, Traits>; };

template <typename Stream>
void redirect(Stream& str, string filename)
{
    using fstream_type = typename fstream_traits<Stream>::type;
    static int index = std::ios_base::xalloc();
    if (str.pword(index) == nullptr)
    {
        str.pword(index)= new vector<ios_base*>{};
        str.register_callback([](ios_base::event event, std::ios_base& stream, int index) {
            if (event == ios_base::erase_event)
            {
                for (auto fs : *(vector<ios_base*>*)stream.pword(index))
                    delete fs;
                delete (vector<ios_base*>*)stream.pword(index);
            }
        }, index);
    }
    vector<ios_base*>* list = (vector<ios_base*>*)str.pword(index);
    list->push_back(new fstream_type{filename});
    str.rdbuf(dynamic_cast<fstream_type*>(list->back())->rdbuf())->~basic_streambuf();
}

int main()
{
    redirect(cout, "out.txt");
    cout << "Redirected text!";
    return 0;
}

The template and alias are not required if you explicitly use istream/ostream instead of Stream.


问:
Save the times an action has happend then do something Netlogo
I dont have code as I dont really know how to do it. i have some patches of colore brown and at random the turn green for one tick and then they become brown again, it loops. I want to know if there is a way to ask a turtle to know how many times that patch has changed to green.

Thanks in advance.

答:
A variable like you describe is often called a counter. In this case, you probably want it to be a patches-own variable so that each patch can individually track how many times a given event has occurred. In the example below, times-turned-green starts at zero (by default, that is the value for any variable declared in Netlogo) and the patches all update their own 'personal' times-turned-green whenever they change colour.

```<code>patches-own [ times-turned-green ]

to setup
  ca
  ask patches [ set pcolor brown]
  reset-ticks
end

to example
  repeat 100 [
    ask patches [
      set pcolor brown
      if random-float 1 < 0.05 [
        set pcolor green
        set times-turned-green times-turned-green + 1
      ]
    ]
  ]
  ask n-of 5 patches [
    show times-turned-green
  ]
end
</code>```

Output in the Command Center should look similar to:

```<code>(patch -6 14): 2
(patch -9 4): 6
(patch 2 1): 8
(patch -3 3): 4
(patch -5 12): 5
</code>```

Body:
A variable like you describe is often called a counter. In this case, you probably want it to be a patches-own variable so that each patch can individually track how many times a given event has occurred. In the example below, times-turned-green starts at zero (by default, that is the value for any variable declared in Netlogo) and the patches all update their own 'personal' times-turned-green whenever they change colour.

patches-own [ times-turned-green ]

to setup
  ca
  ask patches [ set pcolor brown]
  reset-ticks
end

to example
  repeat 100 [
    ask patches [
      set pcolor brown
      if random-float 1 < 0.05 [
        set pcolor green
        set times-turned-green times-turned-green + 1
      ]
    ]
  ]
  ask n-of 5 patches [
    show times-turned-green
  ]
end

Output in the Command Center should look similar to:

(patch -6 14): 2
(patch -9 4): 6
(patch 2 1): 8
(patch -3 3): 4
(patch -5 12): 5