问:
Vaadin14 fullcalendar applyChangesOnEntry return wrong resource
I'm having some problem with fullcalendar and I can't figure out how to solve the problem. My code was previously working on vaadin 13 with fullcalendar 1.9.2.

My code:

```<code>calendar.addEntryDroppedListener((EntryDroppedEvent e) -> {
ExtendedResourceEntry entry = (ExtendedResourceEntry) e.applyChangesOnEntry();
ScheduleEvent event = entry.getEvent();
event.setEventStart(entry.getStart().toLocalDate());
event.setEventEnd(entry.getEnd().toLocalDate());
for (ScheduleResource scheduleResource : resourceMap.keySet()) {
    final Resource r = resourceMap.get(scheduleResource);
    if (r.equals(entry.getResource().get())) {
        //Do my stuff
    }
}
</code>```

});

pom.xml

```<code><dependency>
    <groupId>org.vaadin.stefan</groupId>
    <artifactId>fullcalendar2-scheduler</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>org.vaadin.stefan</groupId>
    <artifactId>fullcalendar2</artifactId>
    <version>2.0.0</version>
</dependency>

<repository>
   <id>vaadin-addons</id>
   <url>https://maven.vaadin.com/vaadin-addons</url>
</repository>
</code>```

This is how the code was working with Vaadin 13:

Drag the event from "Resource 1"

Drop the event on "Resource 2"

Display popup with three option (Copy, Move, Abort) (The user select one)

Copy or Move the dragged (Resource 1) event to the selected (Resource 2) resource (row)

This is how the code is working now with Vaadin 14:

Drag the event from "Resource 1"

Drop the event on "Resource 2"

Display popup with three option (Copy, Move, Abort) (The user select one)

Copy or Move the dragged (Resource 1) event to the the same resource, so it duplicate the event on the same resource (row)

Here the problem is that applyChangesOnEntry does not apply the right resource. How do I get the right resource?

答:
Solved the problem reading the pull request on github. It is accessible here.
This user made the working code, maybe the developer will merge it in future</p>

Body:
I'm having some problem with fullcalendar and I can't figure out how to solve the problem. My code was previously working on vaadin 13 with fullcalendar 1.9.2.

My code:

calendar.addEntryDroppedListener((EntryDroppedEvent e) -> {
ExtendedResourceEntry entry = (ExtendedResourceEntry) e.applyChangesOnEntry();
ScheduleEvent event = entry.getEvent();
event.setEventStart(entry.getStart().toLocalDate());
event.setEventEnd(entry.getEnd().toLocalDate());
for (ScheduleResource scheduleResource : resourceMap.keySet()) {
    final Resource r = resourceMap.get(scheduleResource);
    if (r.equals(entry.getResource().get())) {
        //Do my stuff
    }
}

});

pom.xml

<dependency>
    <groupId>org.vaadin.stefan</groupId>
    <artifactId>fullcalendar2-scheduler</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>org.vaadin.stefan</groupId>
    <artifactId>fullcalendar2</artifactId>
    <version>2.0.0</version>
</dependency>

<repository>
   <id>vaadin-addons</id>
   <url>https://maven.vaadin.com/vaadin-addons</url>
</repository>

This is how the code was working with Vaadin 13:

Drag the event from "Resource 1"

Drop the event on "Resource 2"

Display popup with three option (Copy, Move, Abort) (The user select one)

Copy or Move the dragged (Resource 1) event to the selected (Resource 2) resource (row)

This is how the code is working now with Vaadin 14:

Drag the event from "Resource 1"

Drop the event on "Resource 2"

Display popup with three option (Copy, Move, Abort) (The user select one)

Copy or Move the dragged (Resource 1) event to the the same resource, so it duplicate the event on the same resource (row)

Here the problem is that applyChangesOnEntry does not apply the right resource. How do I get the right resource?


来源: stackexchange

问:
How to select value inside array
This the code in the var named available_dates

var available_dates = ["08-11-2018","09-11-2018"]

I wonder how can I choose the second date of the var and selected, to my second code

document.getElementById('app_date').value = available_dates

答:
Simply access array by its key available_dates[1]

function getDate() {
  var available_dates = ["08-11-2018","09-11-2018"]
  document.getElementById("myText").value = available_dates[1];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myText" value="">

<button onclick="getDate()">Get Date</button></code>```

Link for javascript array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

ContentLicense: CC BY-SA 4.0

Title: How to select value inside array

Body:
Simply access array by its key available_dates[1]

function getDate() {
  var available_dates = ["08-11-2018","09-11-2018"]
  document.getElementById("myText").value = available_dates[1];
}

<input type="text" id="myText" value="">

<button onclick="getDate()">Get Date</button>

Link for javascript array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array


问:
Why does using an arrow function give the updated version of the state in React in comparison to calling the function normally?
Take the following react code

```<code>class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {state1: true, state2: false, state3: "hello"}
        this.onClick = this.onClick.bind(this)

    }

    onClick() {
        this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
    }

    render() {
        return(
            <button onClick = {this.onClick}></button>
        )
    }
}

ReactDOM.render(<Foo />, document.getElementById('root'));
</code>```

When I use console.log in the callback for setState, I have to click the button twice in React in order for the console to display the correct version of state.

However, if write this.setState({state1: false, state2: true, state3: "goodbye"}, () => console.log(this.state)) instead, adding an arrow function, clicking the button once outputs the correct version of the state in the console. Why is that? Why does an arrow function output different behaviour in this scenario?

答:
The expression console.log(this.state) is first evaluated, and the resulting value is passed into setState.

In other words, this

```<code>this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
</code>```

can be re-written to the following without changing its behavior:

```<code>let consoleLogResult = console.log(this.state)
this.setState({state1: false, state2: true, state3: "goodbye"}, consoleLogResult)
</code>```

You log the current state before you set it.

Now, console.log always returns undefined, so consoleLogResult above will always be undefined. It behaves like you never passed a callback 'function' at all.

If you instead pass () => console.log(this.state), it evaluates to a function, which is called by React after the state transition was executed.

Body:
Take the following react code

class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {state1: true, state2: false, state3: "hello"}
        this.onClick = this.onClick.bind(this)

    }

    onClick() {
        this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
    }

    render() {
        return(
            <button onClick = {this.onClick}></button>
        )
    }
}

ReactDOM.render(<Foo />, document.getElementById('root'));

When I use console.log in the callback for setState, I have to click the button twice in React in order for the console to display the correct version of state.

However, if write this.setState({state1: false, state2: true, state3: "goodbye"}, () => console.log(this.state)) instead, adding an arrow function, clicking the button once outputs the correct version of the state in the console. Why is that? Why does an arrow function output different behaviour in this scenario?

Body:
The expression console.log(this.state) is first evaluated, and the resulting value is passed into setState.

In other words, this

this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))

can be re-written to the following without changing its behavior:

let consoleLogResult = console.log(this.state)
this.setState({state1: false, state2: true, state3: "goodbye"}, consoleLogResult)

You log the current state before you set it.

Now, console.log always returns undefined, so consoleLogResult above will always be undefined. It behaves like you never passed a callback 'function' at all.

If you instead pass () => console.log(this.state), it evaluates to a function, which is called by React after the state transition was executed.


问:
Send data from Phoenix to Javascript in Slim template
I have figured out a way to do this, defining a variable inside a HTML attribute like this:

```<code>div data-name=some_var id="component"
</code>```

Then from Javascript I can retrieve it:

```<code>alert($("#component").data("name"));
</code>```

However, it looks very ugly to me. Is there another way to achieve this?

答:
I usualy do it like this:

```<code>div id="component"
javascript:
  var templateData = {
    name: '<%= @name %>',
    product_str: '<%= Poison.encode!(@product) %>',
  };
</code>```

You'll probably need to install Poison to encode data to JSON.

ContentLicense: CC BY-SA 3.0

Body:
I have figured out a way to do this, defining a variable inside a HTML attribute like this:

div data-name=some_var id="component"

Then from Javascript I can retrieve it:

alert($("#component").data("name"));

However, it looks very ugly to me. Is there another way to achieve this?

Body:
I usualy do it like this:

div id="component"
javascript:
  var templateData = {
    name: '<%= @name %>',
    product_str: '<%= Poison.encode!(@product) %>',
  };

You'll probably need to install Poison to encode data to JSON.


问:
WPF/WinForms DragDrop IDataObject
I was wondering why WPF defines a new and apparently identical version of IDataObject for its drag/drop system?

I have application code which uses the winforms IDataObject which I now need to interoperate with WPF drag/drop events.  Would it be safe to simply write an adapter class which implements System.Windows.Forms.IDataObject but passes calls into the actual System.Windows.IDataObject provided by WPF?

Thanks
Dan

答:
Scenario

I found this question when I was trying to debug this problem:

I was dropping into a WinForms application, where inside the Drop event handler, the object I received was a System.Windows.Forms.IDataObject

However, I was using a library to do the heavy lifting of the Drop event, and it expected a object of type System.Windows.IDataObject. I was not able to edit the library source code.

Problem

If I tried to simply cast between the types ...

```<code>// data is of type System.Windows.Forms.IDataObject
var newData = (System.Windows.IDataObject)data; // debugger exits function after this line of code
</code>```

... the debugger would just exit the function at that line of code without error. None of the code after that line would execute.

Solution

I created a proxy method that I called inside my WinForms event handler. The constructor for System.Windows.DataObject will accept a System.Windows.Forms.DataObject.

```<code>public void DropEventProxy(System.Windows.Forms.IDataObject data)
{
    System.Windows.IDataObject newData = new System.Windows.DataObject(data);
    LibraryDropEventHandler(newData);
}

public string LibraryDropEventHandler(System.Windows.IDataObject data);
</code>```

ContentLicense: CC BY-SA 2.5

Title: WPF/WinForms DragDrop IDataObject

Body:
Scenario

I found this question when I was trying to debug this problem:

I was dropping into a WinForms application, where inside the Drop event handler, the object I received was a System.Windows.Forms.IDataObject

However, I was using a library to do the heavy lifting of the Drop event, and it expected a object of type System.Windows.IDataObject. I was not able to edit the library source code.

Problem

If I tried to simply cast between the types ...

// data is of type System.Windows.Forms.IDataObject
var newData = (System.Windows.IDataObject)data; // debugger exits function after this line of code

... the debugger would just exit the function at that line of code without error. None of the code after that line would execute.

Solution

I created a proxy method that I called inside my WinForms event handler. The constructor for System.Windows.DataObject will accept a System.Windows.Forms.DataObject.

public void DropEventProxy(System.Windows.Forms.IDataObject data)
{
    System.Windows.IDataObject newData = new System.Windows.DataObject(data);
    LibraryDropEventHandler(newData);
}

public string LibraryDropEventHandler(System.Windows.IDataObject data);


问:
Connecting PostgreSQL installed in docker inside Hyper-V Ubuntu from Windows 10 PgAdmin
I need help in connecting PostgreSQL which is installed in Docker inside HyperV ubuntu 18.4 from Windows 10 PgAdmin. So far I tried the following

Step 1: Install Postgres in Docker (Ubuntu running on Hyper-V)

```<code>sudo docker run -p 5432:5432 --name pg_test -e POSTGRES_PASSWORD=admin -d postgres
</code>```

Step 2: Create a database

```<code>docker exec -it pg_test bash
psql -U postgres
create database mytestdb
</code>```

Step 3: Get the ip address

```<code>sudo docker inspect pg_test | grep IPAddress
//returned with 172.17.0.2
</code>```

Step 4: pg_hba.conf

```<code>host    all             all             0.0.0.0/0               md5
</code>```

Step 5: When I try to connect from Windows PgAdmin 4, I get this below error -
Note: I have also tried using UBUNTU VM IP address, but no luck

答:
Your's is a case where you are trying to connect to postgres from another subnet, i.e windows subnet to hyper visor subnet if you are not using bridged protocol.

So case 1:

If this is on NAT\HOST and not on bridge then you need to make sure you are able to ping the ubuntu server from windows server.

next is make sure that port is open from ubuntu's end. How do you check that, do a telnet on the port number from windows cmd prompt.

telnet 192.168.0.10 5432

if you are bridged and you can ping ping the server as well, checked that port is opened which is telnet works. You need to make sure that in the postgres.conf file
"listen address" is to "*". which is all.

Again from OS level in ubuntu run the command systemctl stop firewalld to stop firewall and then try to connect. IF this works then you need to open the port in the firewall using this command:

```<code>firewall-cmd --permanent --add-port 5432/tcp
</code>```

I can see from you docker image that 5432 is already opened. This is more of port mapping and firewalld stuff.

Body:
I need help in connecting PostgreSQL which is installed in Docker inside HyperV ubuntu 18.4 from Windows 10 PgAdmin. So far I tried the following

Step 1: Install Postgres in Docker (Ubuntu running on Hyper-V)

sudo docker run -p 5432:5432 --name pg_test -e POSTGRES_PASSWORD=admin -d postgres

Step 2: Create a database

docker exec -it pg_test bash
psql -U postgres
create database mytestdb

Step 3: Get the ip address

sudo docker inspect pg_test | grep IPAddress
//returned with 172.17.0.2

Step 4: pg_hba.conf

host    all             all             0.0.0.0/0               md5

Step 5: When I try to connect from Windows PgAdmin 4, I get this below error -
Note: I have also tried using UBUNTU VM IP address, but no luck

Body:
Your's is a case where you are trying to connect to postgres from another subnet, i.e windows subnet to hyper visor subnet if you are not using bridged protocol.

So case 1:

If this is on NAT\HOST and not on bridge then you need to make sure you are able to ping the ubuntu server from windows server.

next is make sure that port is open from ubuntu's end. How do you check that, do a telnet on the port number from windows cmd prompt.

telnet 192.168.0.10 5432

if you are bridged and you can ping ping the server as well, checked that port is opened which is telnet works. You need to make sure that in the postgres.conf file
"listen address" is to "*". which is all.

Again from OS level in ubuntu run the command systemctl stop firewalld to stop firewall and then try to connect. IF this works then you need to open the port in the firewall using this command:

firewall-cmd --permanent --add-port 5432/tcp

I can see from you docker image that 5432 is already opened. This is more of port mapping and firewalld stuff.


问:
Access the http response headers in a WebView?
Is there a way to view the http response headers in an Activity once a web page has been loaded in a WebView? Seems like this should be possible, but I can't find any methods that expose the headers.</p>

答:
you can use OkHttp:

```<code>private fun handleRequestViaOkHttp(url: String) {

            var httpClient = OkHttpClient()

            thread {
                try {
                    val request = Request.Builder().url(url).build()
                    print("Request: $request")
                    val response = httpClient.newCall(request).execute()
                    println("Response: " + response.headers().toString())
                } catch (e: Exception) {}
            }
        }
</code>```

you should call it inside this method:

```<code>override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {

                handleRequestViaOkHttp(webViewUrl.value.toString())
                return super.shouldInterceptRequest(view, request)
        }
</code>```

Body:
you can use OkHttp:

private fun handleRequestViaOkHttp(url: String) {

            var httpClient = OkHttpClient()

            thread {
                try {
                    val request = Request.Builder().url(url).build()
                    print("Request: $request")
                    val response = httpClient.newCall(request).execute()
                    println("Response: " + response.headers().toString())
                } catch (e: Exception) {}
            }
        }

you should call it inside this method:

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {

                handleRequestViaOkHttp(webViewUrl.value.toString())
                return super.shouldInterceptRequest(view, request)
        }


问:
How to search inside nested list object in spring boot data elastic-search
My contract model class

```<code>@Data
@Document(indexName = "contract",type = "contract")
public class Contract implements Serializable
{
    @JsonProperty("contract_number")
    @Id
    @Parent(type = "p")
    @Field(type = FieldType.Text,index =true)
    private String contract_number;

    private String startDate;

    private String endDate;

    private String supportTypeCode;

    @Field(type = FieldType.Nested,searchAnalyzer = "true")
        private List<Product> products;
</code>```

My product class

```<code>@Data
public class Product implements Serializable
{

    @Field(type = FieldType.Keyword)
    private String baseNumber;
    @Field(type = FieldType.Keyword)
    private String rowId;
    @Field(type = FieldType.Keyword)
    private String effectiveDate;
}
</code>```

Using spring data I,m trying to fetch data based on baseNumber which is present in product class.
But not able to get data.

I tried using below JPA Method but it is not working.

```<code>Optional<Contract>  findByProducts_BaseNumber(String s)
</code>```

I am quite confused about how to maintain a mapping between Contract and Product class.

答:
For me below solution worked I'm using elastic 7.6 version java API.</p>

```<code>SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("products.baseNumber", baseNumber);
    searchSourceBuilder.query(matchQueryBuilder);
    searchSourceBuilder.from(0);
    searchSourceBuilder.size(5);
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices(INDEX);
    searchRequest.source(searchSourceBuilder);
    SearchHits hits = null;
    try
    {
        hits = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT).getHits();
        final List<Contract> collect = Arrays.stream(hits.getHits()).map(
                sourceAsMap -> objectMapper.convertValue(sourceAsMap.getSourceAsMap(), Contract.class)).collect(
                Collectors.toList());
        return  collect.get(0);
    }
    catch (IOException e)
    {
        e.printStackTrace();

    }
</code>```

Body:
My contract model class

@Data
@Document(indexName = "contract",type = "contract")
public class Contract implements Serializable
{
    @JsonProperty("contract_number")
    @Id
    @Parent(type = "p")
    @Field(type = FieldType.Text,index =true)
    private String contract_number;

    private String startDate;

    private String endDate;

    private String supportTypeCode;

    @Field(type = FieldType.Nested,searchAnalyzer = "true")
        private List<Product> products;

My product class

@Data
public class Product implements Serializable
{

    @Field(type = FieldType.Keyword)
    private String baseNumber;
    @Field(type = FieldType.Keyword)
    private String rowId;
    @Field(type = FieldType.Keyword)
    private String effectiveDate;
}

Using spring data I,m trying to fetch data based on baseNumber which is present in product class.
But not able to get data.

I tried using below JPA Method but it is not working.

Optional<Contract>  findByProducts_BaseNumber(String s)

I am quite confused about how to maintain a mapping between Contract and Product class.

Body:
For me below solution worked I'm using elastic 7.6 version java API.

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("products.baseNumber", baseNumber);
    searchSourceBuilder.query(matchQueryBuilder);
    searchSourceBuilder.from(0);
    searchSourceBuilder.size(5);
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices(INDEX);
    searchRequest.source(searchSourceBuilder);
    SearchHits hits = null;
    try
    {
        hits = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT).getHits();
        final List<Contract> collect = Arrays.stream(hits.getHits()).map(
                sourceAsMap -> objectMapper.convertValue(sourceAsMap.getSourceAsMap(), Contract.class)).collect(
                Collectors.toList());
        return  collect.get(0);
    }
    catch (IOException e)
    {
        e.printStackTrace();

    }


问:
Implementing Unique if not Null Constraint with SQLAlchemy and MS SQL Server
I want to enforce a unique constraint on a column but only if it is not null. This is the default behavior in SQLite, but not in MS SQL Server.

It seems the way to accomplish this in SQL Server is to use an index with a where clause, as described in this post. My question is how do I do that in SQLAlchemy and have it still work with SQLite.

I think this is approximately what I want:

```<code>class MyClass(Base):
    __tablename__ = 'myclass'
    __table_args__ = (Index('unique_index', <where clause?>, unique=True)
    my_column = Column(Integer) # The column I want unique if not null
</code>```

where <where clause?> is some expression that puts the index on my_column where it is not NULL. It seems this is possible by reading the documentation for index, but I do not know what expression I would need. Help with this or a different approach would be much appreciated.

答:
For anyone else that finds this later. SQL Alchemy does now support this index documentation.

import sqlalchemy as sa

sa.Table(
    sa.Column('column', sa.String(50), nullable=True),
    sa.Index('uq_column_allows_nulls', mssql_where=sa.text('column IS NOT NULL'),
)
```

<p>If you are planning on using alembic like I was use this code.</p>

<pre class="lang-py prettyprint-override"><code>import sqlalchemy as sa
import alembic as op

op.create_index(
    name='uq_column_name',
    table_name='table',
    columns=['column'],
    mssql_where=sa.text('column IS NOT NULL'),
)
</code>```

This uses the sql expression text for sqlalchemy and create_index's dialect_expression key word arguments mssql_where=

Body:
I want to enforce a unique constraint on a column but only if it is not null. This is the default behavior in SQLite, but not in MS SQL Server.

It seems the way to accomplish this in SQL Server is to use an index with a where clause, as described in this post. My question is how do I do that in SQLAlchemy and have it still work with SQLite.

I think this is approximately what I want:

class MyClass(Base):
    __tablename__ = 'myclass'
    __table_args__ = (Index('unique_index', <where clause?>, unique=True)
    my_column = Column(Integer) # The column I want unique if not null

where <where clause?> is some expression that puts the index on my_column where it is not NULL. It seems this is possible by reading the documentation for index, but I do not know what expression I would need. Help with this or a different approach would be much appreciated.

Body:
For anyone else that finds this later. SQL Alchemy does now support this index documentation.

import sqlalchemy as sa

sa.Table(
    sa.Column('column', sa.String(50), nullable=True),
    sa.Index('uq_column_allows_nulls', mssql_where=sa.text('column IS NOT NULL'),
)

If you are planning on using alembic like I was use this code.

import sqlalchemy as sa
import alembic as op

op.create_index(
    name='uq_column_name',
    table_name='table',
    columns=['column'],
    mssql_where=sa.text('column IS NOT NULL'),
)

This uses the sql expression text for sqlalchemy and create_index's dialect_expression key word arguments mssql_where=


问:
Set dynamic style for Checkbox in Ant Design
Is it possible to set tick container's style backgroundColor and borderColor in Checkbox dynamically from JSX?

I can do it with CSS/LESS, but I need to set specific color based on data from API.

Example:

.

答:
If the colors from API are completely unknown to you until the time of running, then there is no way to accomplish the task with Antd library. Because the class you need to update colors for (.ant-checkbox-checked .ant-checkbox-inner) is nested inside the parent component , and can be changed only in your .less file.
As you can see in Rafael's example, you can only control the colors of the parent (.ant-checkbox-wrapper) from .js file.

On the other hand, if you know there will always be, let's say "#1890FF", "#FA8072", and "#008100" colors, you just don't know in what order, you can easily change the colors dynamically, by creating your logic around CSS classes. Which means you can map through all your checkboxes and give the classNames based on the color you get from API (getColor function). In order to do so, in your .js file import the data from API and define getColor function:

```<code>import React, { PureComponent } from "react";
import { Checkbox  } from "antd";

export default class ColoredCheckboxes extends PureComponent {
    getColor = color => {
        let checkboxClassName = "checkbox-green";
        if (color === "#FA8072") {
            checkboxClassName = "checkbox-orange"
        }
        if (color === "#1890FF") {
            checkboxClassName = "checkbox-blue"
        }
        return checkboxClassName;
    };

    render() {
        const dataFromAPI = [
            {
                key: "first",
                name: "First",
                color: "#008100",
            },
            {
                key: "second",
                name: "Second",
                color: "#FA8072",
            },
            {
                key: "third",
                name: "Third",
                color: "#1890FF",
            },
        ]
        return (
            <div>
                {dataFromAPI.map(item => (
                    <div key={item.key}>
                        <Checkbox className={this.getColor(item.color)}>
                            {item.name}
                        </Checkbox>
                    </div>
                ))}
            </div>
        );
    }
}
</code>```

Then in your .less file reassign the colors for ".ant-checkbox-checked .ant-checkbox-inner" class originally coming from Antd Library:

```<code>.checkbox-green {
    .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #008100;
        border-color: #008100;
    }
}
.checkbox-orange {
    .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #FA8072;
        border-color: #FA8072;
    }
}
.checkbox-blue {
    .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #1890FF;
        border-color: #1890FF;
    }
}
</code>```

Body:
If the colors from API are completely unknown to you until the time of running, then there is no way to accomplish the task with Antd library. Because the class you need to update colors for (.ant-checkbox-checked .ant-checkbox-inner) is nested inside the parent component , and can be changed only in your .less file.
As you can see in Rafael's example, you can only control the colors of the parent (.ant-checkbox-wrapper) from .js file.

On the other hand, if you know there will always be, let's say "#1890FF", "#FA8072", and "#008100" colors, you just don't know in what order, you can easily change the colors dynamically, by creating your logic around CSS classes. Which means you can map through all your checkboxes and give the classNames based on the color you get from API (getColor function). In order to do so, in your .js file import the data from API and define getColor function:

import React, { PureComponent } from "react";
import { Checkbox  } from "antd";

export default class ColoredCheckboxes extends PureComponent {
    getColor = color => {
        let checkboxClassName = "checkbox-green";
        if (color === "#FA8072") {
            checkboxClassName = "checkbox-orange"
        }
        if (color === "#1890FF") {
            checkboxClassName = "checkbox-blue"
        }
        return checkboxClassName;
    };

    render() {
        const dataFromAPI = [
            {
                key: "first",
                name: "First",
                color: "#008100",
            },
            {
                key: "second",
                name: "Second",
                color: "#FA8072",
            },
            {
                key: "third",
                name: "Third",
                color: "#1890FF",
            },
        ]
        return (
            <div>
                {dataFromAPI.map(item => (
                    <div key={item.key}>
                        <Checkbox className={this.getColor(item.color)}>
                            {item.name}
                        </Checkbox>
                    </div>
                ))}
            </div>
        );
    }
}

Then in your .less file reassign the colors for ".ant-checkbox-checked .ant-checkbox-inner" class originally coming from Antd Library:

.checkbox-green {
    .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #008100;
        border-color: #008100;
    }
}
.checkbox-orange {
    .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #FA8072;
        border-color: #FA8072;
    }
}
.checkbox-blue {
    .ant-checkbox-checked .ant-checkbox-inner {
        background-color: #1890FF;
        border-color: #1890FF;
    }
}


问:
Emgu CV bitmap to image no longer working
I am working with emguCV pretty often. But now, I downloaded latest CV3 libs for .Net and never had problem with converting bitmap to image. Now my code is no longer working and constructor Image no longer takes bitmap as paramter.

```<code>        Bitmap bitmap = Sources.GetBitmap();
        Image<Bgr, byte> source = new Image<Bgr, byte>(bitmap);
</code>```

Is there any workaround?

答:
Since Emgu version 4.2.0 there is no Image constructor with bitmap as parameter.

Now, according to changelog ( http://www.emgu.com/wiki/index.php/Version_History ) there is Extension method for bitmap. So now, you have to convert bitmap to Image like this:

```<code>    Bitmap bitmap = Sources.GetBitmap();
    var Image = bitmap.ToImage<Bgr, byte>();
</code>```

Body:
I am working with emguCV pretty often. But now, I downloaded latest CV3 libs for .Net and never had problem with converting bitmap to image. Now my code is no longer working and constructor Image no longer takes bitmap as paramter.

        Bitmap bitmap = Sources.GetBitmap();
        Image<Bgr, byte> source = new Image<Bgr, byte>(bitmap);

Is there any workaround?

Body:
Since Emgu version 4.2.0 there is no Image constructor with bitmap as parameter.

Now, according to changelog ( http://www.emgu.com/wiki/index.php/Version_History ) there is Extension method for bitmap. So now, you have to convert bitmap to Image like this:

    Bitmap bitmap = Sources.GetBitmap();
    var Image = bitmap.ToImage<Bgr, byte>();


问:
Javascript removeClass/toggleClass works on desktop but not responsive page
I bought this theme a while back and have been chopping it up and modifying it to add/remove functionality.  There is this slidein menu that appears on the page once a link is clicked from the navbar menu.  The issue is that there is an X button to close the menu that is supposed to toggle/remove a class from the #btn-offcanvas-menu element when it is clicked (#btn-close-canvasmenu is clickable element); it works on the desktop but not the responsive mobile site.  The only way it is toggled/removed on mobile is if the original link is clicked again.  I have looked at the below questions here, and several others, including trying to use the closest/find options but nothing seems to work.  What am I missing?

Desired behavior: the isLeft class should toggle/be removed when the #btn-close-canvasmenu link is clicked.  It is on desktop but not mobile.

Javascript not working on mobile but works on desktop.

JavaScript - removeClass not working?

ToggleClass and RemoveClass not working

JQuery - ToggleClass/AddClass/RemoveClass

How to toggle class of closest element jquery toggle class on closest span

This is relevant portion of the index page...

```<code>    <li id="recent-mobile"><!-- this is hidden by CSS on desktop -->
            <a id="btn-offcanvas-menu" href="#">Recent Results</a>
    </li>
    <li id="recent-results"><!-- this is hidden by CSS on mobile -->
        <div class="header-buttons pull-right hidden-xs hidden-sm">
            <div class="navright-button">
                <a href="#" id="btn-offcanvas-menu"><i class="fa fa-bars">  Recent Results</i></a>
            </div>
        </div>
    </li>

    <!-- Menu OffCanvas right begin -->
    <div class="navright-button">
        <div class="compact-menu-canvas" id="offcanvas-menu">
            <h3>menu</h3><a id="btn-close-canvasmenu"><i class="fa fa-close"></i></a>
            <nav>
                <ul class="clearfix">
                    <li><a href="index.html">Home</a></li>
                    <li><a href="features.html">Features</a></li>
                    <li><a href="pages.html">Pages</a></li>
                    <li><a href="portfolio.html">Portfolios</a></li>
                    <li><a href="shop.html">Shop</a></li>
                    <li><a href="blog.html">Blog</a></li>
                    <li><a href="contact.html">Contact Us</a></li>
                </ul>
            </nav>
        </div>
    </div>
    <!-- Menu OffCanvas right close -->
</code>```

This is the relevant portion of the javascript compact.js file...

```<code>$("#btn-close-canvasmenu").on("click", function() {
    $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300), $("a#btn-offcanvas-menu").removeClass("isLeft")
});

$(document).on("click", "#btn-offcanvas-menu, #btn-offcanvas-menu-mobile", {} , function(a){
    var id = $(this).attr('id');
    if (id === "btn-offcanvas-menu-mobile") {
        $("#btn-close-canvasmenu").toggleClass("mobile");
    }

    return a.preventDefault(), $(this).hasClass("isLeft") ? $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300) : $("#offcanvas-menu").stop().animate({
        right: "0px"
    }, 300), $(this).toggleClass("isLeft"), false
});
</code>```

EDIT (fixed 2/16/20): I edited the js file file to reflect this updated function: $("#btn-close-canvasmenu").on("click", function()

Essentially, what fixed it was changing the selector from #btn-offcanvas-menu to a#btn-offcanvas-menu.  Not sure why that worked as opposed to using closest/find method but once I did, it toggled/removed the class on both desktop and mobile correctly.  If anyone has anything thoughts on why the a made the difference with the selector, I'd appreciate the feedback as I am not an expert on js/jQuery.  Otherwise, this can be considered closed.

答:
Changing the selector in the compact.js file from #btn-offcanvas-menu to a#btn-offcanvas-menu fixed the issue and while this worked, it was the wrong way to correct the issue as connexo pointed out due to the duplicate ids.

The correct way to resolve this was to change the mobile navbar itself so I could use an id specifically for the mobile that only appeared there.

```<code><nav id="mobile-menu" class="site-mobile-menu hidden-lg hidden-md">
    <ul>
        <li id="recent-mobile">
            <a href="#" id="btn-offcanvas-menu-mobile">Recent Results</a>
        </li>
    </ul>
</nav>
</code>```

Next I changed the js function that populated the html for the mobile menu to use prepend instead of append so it populated everything above the Recent Results link...

```<code>$("#desktop-menu > ul").children().clone().prependTo($("#mobile-menu > ul")), $("#show-mobile-menu").on("click", function() {
    $(this).toggleClass("clicked"), $("#mobile-menu > ul").stop(true, true).slideToggle()
});
</code>```

Then I tweaked the js function to toggle the class to mobile for the #btn-close-canvasmenu if the selector was #btn-offcanvas-menu-mobile to be used later...

```<code>$(document).on("click","#btn-offcanvas-menu,#btn-offcanvas-menu-mobile", {} , function(a){
    var id = $(this).attr('id');

    if (id === "btn-offcanvas-menu-mobile") {
        $("#btn-close-canvasmenu").toggleClass("mobile");
    }

    return a.preventDefault(), $(this).hasClass("isLeft") ? $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300) : $("#offcanvas-menu").stop().animate({
        right: "0px"
    }, 300), $(this).toggleClass("isLeft"), false
});
</code>```

Finally, I tweaked the js function that closed the menu to check the class to determine which id to toggle the isLeft class for...

```<code>$(document).on("click","#btn-close-canvasmenu", {} , function(a){
    var id = $(this).attr('id');

    if ($(this).hasClass("mobile")) {
        var container = $("#btn-offcanvas-menu-mobile");
        $("#btn-close-canvasmenu").toggleClass("mobile");
    } else {
        var container = $("#btn-offcanvas-menu");
    }

    $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300), container.removeClass("isLeft")
});
</code>```

Body:
I bought this theme a while back and have been chopping it up and modifying it to add/remove functionality.  There is this slidein menu that appears on the page once a link is clicked from the navbar menu.  The issue is that there is an X button to close the menu that is supposed to toggle/remove a class from the #btn-offcanvas-menu element when it is clicked (#btn-close-canvasmenu is clickable element); it works on the desktop but not the responsive mobile site.  The only way it is toggled/removed on mobile is if the original link is clicked again.  I have looked at the below questions here, and several others, including trying to use the closest/find options but nothing seems to work.  What am I missing?

Desired behavior: the isLeft class should toggle/be removed when the #btn-close-canvasmenu link is clicked.  It is on desktop but not mobile.

Javascript not working on mobile but works on desktop.

JavaScript - removeClass not working?

ToggleClass and RemoveClass not working

JQuery - ToggleClass/AddClass/RemoveClass

How to toggle class of closest element jquery toggle class on closest span

This is relevant portion of the index page...

            Recent Results

                  Recent Results

menu

Home

Features

Pages

Portfolios

Shop

Blog

Contact Us

This is the relevant portion of the javascript compact.js file...

$("#btn-close-canvasmenu").on("click", function() {
    $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300), $("a#btn-offcanvas-menu").removeClass("isLeft")
});

$(document).on("click", "#btn-offcanvas-menu, #btn-offcanvas-menu-mobile", {} , function(a){
    var id = $(this).attr('id');
    if (id === "btn-offcanvas-menu-mobile") {
        $("#btn-close-canvasmenu").toggleClass("mobile");
    }

    return a.preventDefault(), $(this).hasClass("isLeft") ? $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300) : $("#offcanvas-menu").stop().animate({
        right: "0px"
    }, 300), $(this).toggleClass("isLeft"), false
});

EDIT (fixed 2/16/20): I edited the js file file to reflect this updated function: $("#btn-close-canvasmenu").on("click", function()

Essentially, what fixed it was changing the selector from #btn-offcanvas-menu to a#btn-offcanvas-menu.  Not sure why that worked as opposed to using closest/find method but once I did, it toggled/removed the class on both desktop and mobile correctly.  If anyone has anything thoughts on why the a made the difference with the selector, I'd appreciate the feedback as I am not an expert on js/jQuery.  Otherwise, this can be considered closed.

Body:
Changing the selector in the compact.js file from #btn-offcanvas-menu to a#btn-offcanvas-menu fixed the issue and while this worked, it was the wrong way to correct the issue as connexo pointed out due to the duplicate ids.

The correct way to resolve this was to change the mobile navbar itself so I could use an id specifically for the mobile that only appeared there.

<nav id="mobile-menu" class="site-mobile-menu hidden-lg hidden-md">
    <ul>
        <li id="recent-mobile">
            <a href="#" id="btn-offcanvas-menu-mobile">Recent Results</a>
        </li>
    </ul>
</nav>

Next I changed the js function that populated the html for the mobile menu to use prepend instead of append so it populated everything above the Recent Results link...

$("#desktop-menu > ul").children().clone().prependTo($("#mobile-menu > ul")), $("#show-mobile-menu").on("click", function() {
    $(this).toggleClass("clicked"), $("#mobile-menu > ul").stop(true, true).slideToggle()
});

Then I tweaked the js function to toggle the class to mobile for the #btn-close-canvasmenu if the selector was #btn-offcanvas-menu-mobile to be used later...

$(document).on("click","#btn-offcanvas-menu,#btn-offcanvas-menu-mobile", {} , function(a){
    var id = $(this).attr('id');

    if (id === "btn-offcanvas-menu-mobile") {
        $("#btn-close-canvasmenu").toggleClass("mobile");
    }

    return a.preventDefault(), $(this).hasClass("isLeft") ? $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300) : $("#offcanvas-menu").stop().animate({
        right: "0px"
    }, 300), $(this).toggleClass("isLeft"), false
});

Finally, I tweaked the js function that closed the menu to check the class to determine which id to toggle the isLeft class for...

$(document).on("click","#btn-close-canvasmenu", {} , function(a){
    var id = $(this).attr('id');

    if ($(this).hasClass("mobile")) {
        var container = $("#btn-offcanvas-menu-mobile");
        $("#btn-close-canvasmenu").toggleClass("mobile");
    } else {
        var container = $("#btn-offcanvas-menu");
    }

    $("#offcanvas-menu").stop().animate({
        right: "-260px"
    }, 300), container.removeClass("isLeft")
});


问:
list with lots of data in laravel
I have a bank with more than 10000 registered users.
It turns out that my method is listing everything and it causes a very slow return of data.

```<code>$users = \App\User::all();
</code>```

it is taking almost 40 seconds to show the list with the paginations.

How can I solve this? Filters?

答:
Why you don't try laravel paginate()</p>

```<code>$users = \App\User::paginate(25);
</code>```

Title: list with lots of data in laravel

Body:
I have a bank with more than 10000 registered users.
It turns out that my method is listing everything and it causes a very slow return of data.

$users = \App\User::all();

it is taking almost 40 seconds to show the list with the paginations.

How can I solve this? Filters?

Body:
Why you don't try laravel paginate()

$users = \App\User::paginate(25);


问:
calling a template function of a derived class
I'm having a problem in C++ with calling a function of a derived class while having a pointer to the base class.

EDIT:
Some answers referred me to CRTP

but my point is that I need to have a pointer to the "Base*" class not "Base*" because I'm unaware of the type currently being handled (The current instance is created from some sort of a factory).

Classes:

```<code>class Base
{
..
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};
</code>```

Usage:

```<code>int main()
{
   Base* BasePtr = new Derived1();

   // The expected function to be called is Derived1::func<int>()
   BasePtr->func<int>();

   return 0; // :)
}
</code>```

I can't make func virtual because the language does not support virtual template function.

It is only allowed if only the class is have template arguments but not if the function within it has template arguments.

I have seen a similar problem resolved within Boost.Serialization but couldn't understand the solution.

Thanks,

Koby Meir

答:
Implement Curiously recurring template pattern(CTRP).

Illustration:

```<code>template<typename D>
class Base
{
public:
    template<typename T>
    void func (T arg)
    {
         static_cast<D*>(this)->func(arg);
    }
};

class Derived1 : public Base<Derived1>
{
public:
    template<typename T>
    void func (T arg) { /*...*/ }
};

Base<Derived1> *basePtr = new Base<Derived1>();
basePtr->func(100);
</code>```

Body:
I'm having a problem in C++ with calling a function of a derived class while having a pointer to the base class.

EDIT:
Some answers referred me to CRTP

but my point is that I need to have a pointer to the "Base*" class not "Base*" because I'm unaware of the type currently being handled (The current instance is created from some sort of a factory).

Classes:

class Base
{
..
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

Usage:

int main()
{
   Base* BasePtr = new Derived1();

   // The expected function to be called is Derived1::func<int>()
   BasePtr->func<int>();

   return 0; // :)
}

I can't make func virtual because the language does not support virtual template function.

It is only allowed if only the class is have template arguments but not if the function within it has template arguments.

I have seen a similar problem resolved within Boost.Serialization but couldn't understand the solution.

Thanks,

Koby Meir

Body:
Implement Curiously recurring template pattern(CTRP).

Illustration:

template<typename D>
class Base
{
public:
    template<typename T>
    void func (T arg)
    {
         static_cast<D*>(this)->func(arg);
    }
};

class Derived1 : public Base<Derived1>
{
public:
    template<typename T>
    void func (T arg) { /*...*/ }
};

Base<Derived1> *basePtr = new Base<Derived1>();
basePtr->func(100);


问:
New column based on several YES/ NO columns in RStudio
I am fairly new to RStudio and have been able to learn and solve so many problems thanks to this and similar sites, thank you all very much!
However I have not been able to solve the following and have tried several types of searches and codes.

I have a dataset in RStudio with 1400 entries(patients) and 68 columns, no missing data.

For some of the data on medication I want to create some new columns, like "antithrombotic medication YES/NO" and "heart medication YES/NO".
These should be based on 5-10 columns that either give a YES or a NO. If any column gives a "YES", the new column should be "YES" otherwise "NO".
I have tried several versions of "mutate", "if else" etc where I also tried to use "|" to write "or" but no "luck" so far.

I have several examples, but none that I really believed in too much
.. trial and error! This one is based of a solution to a similar problem that I was able to solve

hipfx_master60 <- hipfx_master60 %>%
  mutate(cardiac_HBP_antithromb_med = case_when({Diuretika="YES"|Betablokkere="YES"|Cakanalblokkere="YES"|ACEhaemmere="YES"|ATIIinhibitorer="YES"|Antithrombotica="YES"|Thrombocythammere="YES"|Vitamin_K_antagonister="YES"|Digoxin="YES"|Organiske_nitrater="YES"} ~ "YES", TRUE ~ "NO"))
```

(image removed)

Any help greatly appreciated!

答:
I don't have your data so I cannot test, but one problem is that you are using the assignment operator = instead of the equality condition operator ==.

hipfx_master60 <- hipfx_master60 %>%
  mutate(
    cardiac_HBP_antithromb_med = case_when(
      Diuretika == "YES" | Betablokkere == "YES" | Cakanalblokkere == "YES" |
        ACEhaemmere == "YES" | ATIIinhibitorer == "YES" | Antithrombotica == "YES" |
          Thrombocythammere == "YES" | Vitamin_K_antagonister == "YES" |
            Digoxin == "YES" | Organiske_nitrater == "YES" ~ "YES",
      TRUE ~ "NO"
    )
  )
```

<p>In this case, <code>case_when</code> is going to be inefficient in the long run (large-ish data?). The reason is that it is doing all of its conditions row-by-row. You can vectorize it (a common R preference) with <code>if_else</code>:</p>

<pre class="lang-r prettyprint-override"><code>hipfx_master60 <- hipfx_master60 %>%
  mutate(
    cardiac_HBP_antithromb_med = if_else(
      Diuretika == "YES" | Betablokkere == "YES" | Cakanalblokkere == "YES" |
        ACEhaemmere == "YES" | ATIIinhibitorer == "YES" | Antithrombotica == "YES" |
          Thrombocythammere == "YES" | Vitamin_K_antagonister == "YES" |
          Digoxin == "YES" | Organiske_nitrater == "YES",
      "YES", "NO")
  )
</code>```

I recommend case_when when you have multiple such checks and would otherwise nest if_else statements. After one nesting, I find the code to be difficult to see and maintain and switch to case_when. (The performance penalty is mostly in my head for not-large datasets. But even if slower, the readability and maintainability are often preferred.) There might be other "elegant" ways to handling multiple related conditionals without resorting to nested-nested-nested if_else ... as always, it depends.

Body:
I am fairly new to RStudio and have been able to learn and solve so many problems thanks to this and similar sites, thank you all very much!
However I have not been able to solve the following and have tried several types of searches and codes.

I have a dataset in RStudio with 1400 entries(patients) and 68 columns, no missing data.

For some of the data on medication I want to create some new columns, like "antithrombotic medication YES/NO" and "heart medication YES/NO".
These should be based on 5-10 columns that either give a YES or a NO. If any column gives a "YES", the new column should be "YES" otherwise "NO".
I have tried several versions of "mutate", "if else" etc where I also tried to use "|" to write "or" but no "luck" so far.

I have several examples, but none that I really believed in too much
.. trial and error! This one is based of a solution to a similar problem that I was able to solve

hipfx_master60 <- hipfx_master60 %>%
  mutate(cardiac_HBP_antithromb_med = case_when({Diuretika="YES"|Betablokkere="YES"|Cakanalblokkere="YES"|ACEhaemmere="YES"|ATIIinhibitorer="YES"|Antithrombotica="YES"|Thrombocythammere="YES"|Vitamin_K_antagonister="YES"|Digoxin="YES"|Organiske_nitrater="YES"} ~ "YES", TRUE ~ "NO"))

(image removed)

Any help greatly appreciated!

Body:
I don't have your data so I cannot test, but one problem is that you are using the assignment operator = instead of the equality condition operator ==.

hipfx_master60 <- hipfx_master60 %>%
  mutate(
    cardiac_HBP_antithromb_med = case_when(
      Diuretika == "YES" | Betablokkere == "YES" | Cakanalblokkere == "YES" |
        ACEhaemmere == "YES" | ATIIinhibitorer == "YES" | Antithrombotica == "YES" |
          Thrombocythammere == "YES" | Vitamin_K_antagonister == "YES" |
            Digoxin == "YES" | Organiske_nitrater == "YES" ~ "YES",
      TRUE ~ "NO"
    )
  )

In this case, case_when is going to be inefficient in the long run (large-ish data?). The reason is that it is doing all of its conditions row-by-row. You can vectorize it (a common R preference) with if_else:

hipfx_master60 <- hipfx_master60 %>%
  mutate(
    cardiac_HBP_antithromb_med = if_else(
      Diuretika == "YES" | Betablokkere == "YES" | Cakanalblokkere == "YES" |
        ACEhaemmere == "YES" | ATIIinhibitorer == "YES" | Antithrombotica == "YES" |
          Thrombocythammere == "YES" | Vitamin_K_antagonister == "YES" |
          Digoxin == "YES" | Organiske_nitrater == "YES",
      "YES", "NO")
  )

I recommend case_when when you have multiple such checks and would otherwise nest if_else statements. After one nesting, I find the code to be difficult to see and maintain and switch to case_when. (The performance penalty is mostly in my head for not-large datasets. But even if slower, the readability and maintainability are often preferred.) There might be other "elegant" ways to handling multiple related conditionals without resorting to nested-nested-nested if_else ... as always, it depends.


问:
How to access video streaming objects via angularjs approach?
During HTML5 implementation regarding media capabilities
by referring to https://davidwalsh.name/demo/camera.php,
it points to

```<code>var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
   // Not adding `{ audio: true }` since we only want video now
   navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
       video.src = window.URL.createObjectURL(stream);
       video.play();
    });
}
</code>```

for video streaming the object.

Instead of that i want to use angular way to achieve this, so i applied these changes :

```<code>var video = angular.element($("video"));
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  // Not adding `{ audio: true }` since we only want video now
  navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
   });
}
</code>```

But from angularjs approach, I am unable to stream the video object,
any suggestions on this or any alternative approach?

答:
The most angular way I've seen is:

angular.element('#myVideo')[0].srcObject = stream

Body:
During HTML5 implementation regarding media capabilities
by referring to https://davidwalsh.name/demo/camera.php,
it points to

var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
   // Not adding `{ audio: true }` since we only want video now
   navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
       video.src = window.URL.createObjectURL(stream);
       video.play();
    });
}

for video streaming the object.

Instead of that i want to use angular way to achieve this, so i applied these changes :

var video = angular.element($("video"));
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  // Not adding `{ audio: true }` since we only want video now
  navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
      video.src = window.URL.createObjectURL(stream);
      video.play();
   });
}

But from angularjs approach, I am unable to stream the video object,
any suggestions on this or any alternative approach?


问:
Pass String to argument of Syscall in Go
I would like to use a C function compiled into a DLL.
Here is the C function that I would like to use:

```<code>int setProxy(const proxy_config* p_proxy);
</code>```

It takes a const pointer to a C structure defined like this:

```<code>typedef struct
{
    char *host_address;
    int port;
    char *username;
    char *password;
} proxy_config;
</code>```

To do so,
I transformed this C_structure into a Go equivalent as follows:

```<code>type proxy_configuration struct {
    host_address *uint16
    port int
    username *uint16
    password *uint16
}
</code>```

To convert the strings, I use the following function:

```<code>func StringToCString(s string) (*uint16, error) {
    for i := 0; i < len(s); i++ {
        if s[i] == 0 {
            return nil, errors.New("Problem with the string : "+s)
        }
    }
    p := utf16.Encode([]rune(s + "\x00"))

    return &p[0], nil
}
</code>```

Then I call it:

```<code>import (
    "syscall"
    "unsafe"
)

func SetProxy(host_address string, port int, username string, password string) error {

    [...Conversion code from Go string to Struct...]

    var nargs uintptr = 1
    ret, _, callErr := syscall.Syscall(
        uintptr(setProxy),
        nargs,
        uintptr(unsafe.Pointer(&proxy)),
        0,
        0,
    )
}
</code>```

where setProxy is the result of syscall.GetProcAddress(DLL,"setProxy")

The problem is that, when I have a look at the logs generated by the DLL, all the *uint16 contains only one character and not the whole string whereas port contains the good information.

Thus, my question is:

How can I pass the whole strings in the parameters of Syscall and not just the first character?

EDIT

If I change return &p[0], nil in the StringToCString by return &p[i], nil
I obtain the i-th character of the string... So the problem is definely there, I just do know how to fix it...

答:
Pass String to argument of Syscall in Go

How can I pass the whole strings in the parameters of [Windows] Syscall?

An obvious answer is to look at the Go standard libraries, which make many Windows syscalls.

package windows

```<code>golang.org/x/sys/windows
</code>```

func UTF16FromString

```<code>func UTF16FromString(s string) ([]uint16, error)
</code>```

UTF16FromString returns the UTF-16 encoding of the UTF-8 string s,
  with a terminating NUL added. If s contains a NUL byte at any
  location, it returns (nil, syscall.EINVAL).

func UTF16PtrFromString

```<code>func UTF16PtrFromString(s string) (*uint16, error)
</code>```

UTF16PtrFromString returns pointer to the UTF-16 encoding of the UTF-8
  string s, with a terminating NUL added. If s contains a NUL byte at
  any location, it returns (nil, syscall.EINVAL).

func UTF16ToString

```<code>func UTF16ToString(s []uint16) string
</code>```

UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
  with a terminating NUL removed.

Body:
I would like to use a C function compiled into a DLL.
Here is the C function that I would like to use:

int setProxy(const proxy_config* p_proxy);

It takes a const pointer to a C structure defined like this:

typedef struct
{
    char *host_address;
    int port;
    char *username;
    char *password;
} proxy_config;

To do so,
I transformed this C_structure into a Go equivalent as follows:

type proxy_configuration struct {
    host_address *uint16
    port int
    username *uint16
    password *uint16
}

To convert the strings, I use the following function:

func StringToCString(s string) (*uint16, error) {
    for i := 0; i < len(s); i++ {
        if s[i] == 0 {
            return nil, errors.New("Problem with the string : "+s)
        }
    }
    p := utf16.Encode([]rune(s + "\x00"))

    return &p[0], nil
}

Then I call it:

import (
    "syscall"
    "unsafe"
)

func SetProxy(host_address string, port int, username string, password string) error {

    [...Conversion code from Go string to Struct...]

    var nargs uintptr = 1
    ret, _, callErr := syscall.Syscall(
        uintptr(setProxy),
        nargs,
        uintptr(unsafe.Pointer(&proxy)),
        0,
        0,
    )
}

where setProxy is the result of syscall.GetProcAddress(DLL,"setProxy")

The problem is that, when I have a look at the logs generated by the DLL, all the *uint16 contains only one character and not the whole string whereas port contains the good information.

Thus, my question is:

How can I pass the whole strings in the parameters of Syscall and not just the first character?

EDIT

If I change return &p[0], nil in the StringToCString by return &p[i], nil
I obtain the i-th character of the string... So the problem is definely there, I just do know how to fix it...

Body:
Pass String to argument of Syscall in Go

How can I pass the whole strings in the parameters of [Windows] Syscall?

An obvious answer is to look at the Go standard libraries, which make many Windows syscalls.

package windows

golang.org/x/sys/windows

func UTF16FromString

func UTF16FromString(s string) ([]uint16, error)

UTF16FromString returns the UTF-16 encoding of the UTF-8 string s,
  with a terminating NUL added. If s contains a NUL byte at any
  location, it returns (nil, syscall.EINVAL).

func UTF16PtrFromString

func UTF16PtrFromString(s string) (*uint16, error)

UTF16PtrFromString returns pointer to the UTF-16 encoding of the UTF-8
  string s, with a terminating NUL added. If s contains a NUL byte at
  any location, it returns (nil, syscall.EINVAL).

func UTF16ToString

func UTF16ToString(s []uint16) string

UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
  with a terminating NUL removed.


问:
Angular 8 Routing + Navigation: Locking a Component
I have built a Authentication system in Angular and was wondering how to lock a route that I have built. In order to get to the "members" route, you need to have an user account. How would you block getting to this route as you could just type the route into URL. I want to prevent this as you need to be a user of the system before being able to route to this page.

Please let me know if you need any chunks of code,
thanks.

答:
You can use a route guard. It`s a service that will check for you specific condition to enable or not a route. You use it on your routes file, like this one:

```<code>export const appRoutes: Routes = [
  {
    path: '',
    component: Component,
    canActivate: [AuthGuard],
  }
]
</code>```

'canActivate' receives an array of your guards, in this case one. And you make your AuthGuard like this:

```<code>@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    private router: Router
  ) {}

  canActivate(): boolean {
      return \\ your logic to check user logged in
  }
}
</code>```

Body:
You can use a route guard. It`s a service that will check for you specific condition to enable or not a route. You use it on your routes file, like this one:

export const appRoutes: Routes = [
  {
    path: '',
    component: Component,
    canActivate: [AuthGuard],
  }
]

'canActivate' receives an array of your guards, in this case one. And you make your AuthGuard like this:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    private router: Router
  ) {}

  canActivate(): boolean {
      return \\ your logic to check user logged in
  }
}


问:
Drake: A plant include Muti-body plant and LeafSystem plant
A part of a plant is easily modeled by MutibodyPlant Class, unfortunately, other parts of a plant look like to be modeled by leaf System. Can Drake do such things?
Plant A: muti-links arm --> Using SDF and MutibodyPlant class for modeling
Plant B: an inertial wheel is attached to the end of the arm --> Using Leaf system to define dynamic(time derivate) of an inertial wheel.   </p>

<p>An illustration for this question     </p>

答:
Wc. I'm not getting why you can't do the whole model in MultibodyPlant. The inertial wheel could be a link attached via a revolute joint. The controller that keeps it spinning at a desired rate would be a separate LeafSystem (like other controllers) that would use the revolute joint's rate as input and generate an actuator output (back to MBPlant).

Regards,
Sherm

Body:
A part of a plant is easily modeled by MutibodyPlant Class, unfortunately, other parts of a plant look like to be modeled by leaf System. Can Drake do such things?
Plant A: muti-links arm --> Using SDF and MutibodyPlant class for modeling
Plant B: an inertial wheel is attached to the end of the arm --> Using Leaf system to define dynamic(time derivate) of an inertial wheel.

An illustration for this question


问:
Use of computed column from count(*) over(...) statement in a SELECT
I have this select statement in SQL Server Management Studio 2014:

```<code>   SELECT main.car_descr
          ,vari.engineCode
          ,count(*) over(partition by vari.engineCode) as quant
    FROM dbspareparts.dbo.stock as stock

    inner join fiord.dbo.store as main on stock.[id_store]=main.[id_store]

    where quant>2

    order by quant desc
</code>```

when I execute, I get "invalid column name" on the istruction

```<code>where quant>2
</code>```

Why and how can I get this work?

I need to use the count(*) over(...) statement, cause this is only a piece of another longer query.

Thanks!

答:
```<code>select * from (SELECT main.car_descr
      ,vari.engineCode
      ,count(*) over(partition by vari.engineCode) as quant
FROM dbspareparts.dbo.stock as stock

inner join fiord.dbo.store as main on stock.[id_store]=main.[id_store]) as tbl

where quant>2

order by quant desc
</code>```

the quant isn't bound as a variable until after your query returns, and so you'll need to wrap it in an inner query before you can filter by it.

Body:
I have this select statement in SQL Server Management Studio 2014:

   SELECT main.car_descr
          ,vari.engineCode
          ,count(*) over(partition by vari.engineCode) as quant
    FROM dbspareparts.dbo.stock as stock

    inner join fiord.dbo.store as main on stock.[id_store]=main.[id_store]

    where quant>2

    order by quant desc

when I execute, I get "invalid column name" on the istruction

where quant>2

Why and how can I get this work?

I need to use the count(*) over(...) statement, cause this is only a piece of another longer query.

Thanks!

Body:
select * from (SELECT main.car_descr
      ,vari.engineCode
      ,count(*) over(partition by vari.engineCode) as quant
FROM dbspareparts.dbo.stock as stock

inner join fiord.dbo.store as main on stock.[id_store]=main.[id_store]) as tbl

where quant>2

order by quant desc

the quant isn't bound as a variable until after your query returns, and so you'll need to wrap it in an inner query before you can filter by it.


问:
What are the functions of an array of an arrayList?
I tried to do:

```<code>static boolean newTrait(ArrayList<Integer> population, int[] traits) {
        for(int i = 0; i < 25; i++) {
            for(int j = 0; j < 625; j++) {
                if(traits[j].equals(population[i].get(i))) {
                    return false;
                }
            }
        }
        return true;
    }
</code>```

The java compiler said that I had an "unresolved compiler issue."

Can anyone help?

答:
[X] operator is for arrays. You don't have an ArrayList array you just have an ArrayList<> which, although it has "Array" in the name, is not an array and so cannot be accessed with [X]. ArrayList is an object with regular methods.

It's perfectly valid to have an ArrayList array
e.g.

```<code>static boolean newTrait(ArrayList<Integer>[] population, int[] traits)
</code>```

where each element in the population array IS A ArrayList. In which case you would first need to access the element in the array (via [X]) and then access the elements IN the ArrayList using get()

e.g. get the first element of the array

```<code> ArrayList<Integer> firstList = population[0];
</code>```

then get the Xth item in the list
e.g.

```<code> firstList.get(x);
</code>```

Body:
I tried to do:

static boolean newTrait(ArrayList<Integer> population, int[] traits) {
        for(int i = 0; i < 25; i++) {
            for(int j = 0; j < 625; j++) {
                if(traits[j].equals(population[i].get(i))) {
                    return false;
                }
            }
        }
        return true;
    }

The java compiler said that I had an "unresolved compiler issue."

Can anyone help?

Body:
[X] operator is for arrays. You don't have an ArrayList array you just have an ArrayList<> which, although it has "Array" in the name, is not an array and so cannot be accessed with [X]. ArrayList is an object with regular methods.

It's perfectly valid to have an ArrayList array
e.g.

static boolean newTrait(ArrayList<Integer>[] population, int[] traits)

where each element in the population array IS A ArrayList. In which case you would first need to access the element in the array (via [X]) and then access the elements IN the ArrayList using get()

e.g. get the first element of the array

 ArrayList<Integer> firstList = population[0];

then get the Xth item in the list
e.g.

 firstList.get(x);


问:
TypeError: Cannot read property 'location' of undefined (jest)
I have a simple component that uses useLocation hook from React Router.

// App.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const pathName = location.pathname;
  useEffect(() => {
    // Use pathName here
  }, [pathName]);
}
```

<p>// App.test.js</p>

<pre class="lang-js prettyprint-override"><code>import App from './App';

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
</code>```

// Update App.test.js (with jest mock)

import App from './App';

describe('App component', () => {
  jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
```

Could you please tell me how I can fix this? Thanks.

答:
In case, anybody else faces a similar problem.

There were 2 issues with my approach. First, I used mock inside describe (thanks Johnny and MGarcia to help me figure that out).

However, I got another error after I moved mock code. Error: React.createElement: type is invalid — expected a string

That was my another Jest newbie mistake, and forgot that it's all JavaScript under the hood. With this approach, the side effect of mocking useLocation is rest of the methods from react-router-dom are made unavailable.

This is the approach that worked for me:

https://github.com/facebook/jest/issues/936#issuecomment-265074320

Final solution:

function mockFunction() {
  const original = require.requireActual('react-router-dom');
  return {
    ...original,
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  };
}

jest.mock('react-router-dom', () => mockFunction());
```

Body:
I have a simple component that uses useLocation hook from React Router.

// App.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const pathName = location.pathname;
  useEffect(() => {
    // Use pathName here
  }, [pathName]);
}

// App.test.js

import App from './App';

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

// Update App.test.js (with jest mock)

import App from './App';

describe('App component', () => {
  jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

Could you please tell me how I can fix this? Thanks.


问:
R plots with equal color mapping
The following code produces the shown plot.

```<code>library(ggplot2)
library(dendextend)
library(cowplot)
set.seed(1234)

N<-10

set1 <- mvrnorm(n = N, c(0,0), matrix(c(0.5,0,0,0.5),2))
df <- data.frame(set1,label=1:N)

# ?dist
# dist method options: "euclidean", "maximum", "manhattan", "canberra", "binary" or "minkowski"
set1.dist <- dist(x=df[1:2],method = "euclidean")

fit1 <- hclust(d=set1.dist, method = "complete")
df$cluster <- cutree(fit1,k = 3)

p1 <- ggplot(df) +
   geom_text(aes(x=X1,y=X2,label=label ,color=as.factor(cluster)))+
   theme(legend.position = "none")
# p1

# ?hclust
# hclust method options "ward.D", "ward.D2", "single", "complete", "average" (= UPGMA), "mcquitty" (= WPGMA), "median" (= WPGMC) or "centroid" (= UPGMC).
p2 <- hclust(d=set1.dist, method = "complete") %>%
   as.dendrogram() %>%
   color_labels(k=3) %>%
   set("branches_k_color", k = 3) %>%
   as.ggdend() %>%
   ggplot(horiz = T, theme = NULL) +
   theme(axis.title.y = element_blank(),
         axis.text.y = element_blank(),
         axis.ticks.y = element_blank())
#plot(fit1,hang = -1, labels = df$label, main="Test",xlab = "")

#?rect.hclust()
plot_grid(p1,p2)
</code>```

I want to have the same color assignment for the clusters in both plots (scatter and dendrogram), but none of my attempts seem to work out. I think there is a wrong ordering of the clusters in the dendrogramm or some thing else.

答:
The issue with your color pattern is that your vales are not sorted in the same order for each plot. On the right plot, hclust will order each id in function of their distance and on the left plot they are sorted by their label id.

To get the same order, you need to attribute the order of hclust to your dataframe. You can find this order in the variable order from your hclust object:

> fit1$order
 [1]  5  6  2  3 10  4  1  7  8  9
```
<p>So, you can now pass this order in your df by doing (after you defined their cluster id):</p>
<pre class="lang-r prettyprint-override"><code>fit1 <- hclust(d=set1.dist, method = "complete")
df$cluster <- cutree(fit1,k = 3)
df <- df[order(match(df$label, fit1$order)),]

            X1         X2 label cluster
5  -0.67846476  0.3034370     5       2
6   0.07798362  0.3578356     6       2
2   0.70596583  0.1961721     2       2
3   0.54889439  0.7668157     3       2
10 -1.70825344 -0.6293518    10       3
4  -0.04557927 -1.6586588     4       1
1   0.33742619 -0.8535244     1       1
7   0.36133829 -0.4064025     7       1
8   0.64431246 -0.3865271     8       1
9   0.59196977 -0.3991278     9       1
</code>```

Now for plotting the first graph, you need to set cluster as a factor and attribute levels based on this order:

p1 <- df %>% mutate(cluster = factor(cluster, unique(cluster))) %>%
  ggplot()+
  geom_text(aes(x=X1,y=X2,label=label ,color=cluster))+
  theme(legend.position = "none")
```

Then, the second plot does not change and you will finally get:

Does it answer your question ?

Title: R plots with equal color mapping

Body:
The following code produces the shown plot.

library(ggplot2)
library(dendextend)
library(cowplot)
set.seed(1234)

N<-10

set1 <- mvrnorm(n = N, c(0,0), matrix(c(0.5,0,0,0.5),2))
df <- data.frame(set1,label=1:N)

# ?dist
# dist method options: "euclidean", "maximum", "manhattan", "canberra", "binary" or "minkowski"
set1.dist <- dist(x=df[1:2],method = "euclidean")

fit1 <- hclust(d=set1.dist, method = "complete")
df$cluster <- cutree(fit1,k = 3)

p1 <- ggplot(df) +
   geom_text(aes(x=X1,y=X2,label=label ,color=as.factor(cluster)))+
   theme(legend.position = "none")
# p1

# ?hclust
# hclust method options "ward.D", "ward.D2", "single", "complete", "average" (= UPGMA), "mcquitty" (= WPGMA), "median" (= WPGMC) or "centroid" (= UPGMC).
p2 <- hclust(d=set1.dist, method = "complete") %>%
   as.dendrogram() %>%
   color_labels(k=3) %>%
   set("branches_k_color", k = 3) %>%
   as.ggdend() %>%
   ggplot(horiz = T, theme = NULL) +
   theme(axis.title.y = element_blank(),
         axis.text.y = element_blank(),
         axis.ticks.y = element_blank())
#plot(fit1,hang = -1, labels = df$label, main="Test",xlab = "")

#?rect.hclust()
plot_grid(p1,p2)

I want to have the same color assignment for the clusters in both plots (scatter and dendrogram), but none of my attempts seem to work out. I think there is a wrong ordering of the clusters in the dendrogramm or some thing else.

Body:
The issue with your color pattern is that your vales are not sorted in the same order for each plot. On the right plot, hclust will order each id in function of their distance and on the left plot they are sorted by their label id.

To get the same order, you need to attribute the order of hclust to your dataframe. You can find this order in the variable order from your hclust object:

> fit1$order
 [1]  5  6  2  3 10  4  1  7  8  9

So, you can now pass this order in your df by doing (after you defined their cluster id):

fit1 <- hclust(d=set1.dist, method = "complete")
df$cluster <- cutree(fit1,k = 3)
df <- df[order(match(df$label, fit1$order)),]

            X1         X2 label cluster
5  -0.67846476  0.3034370     5       2
6   0.07798362  0.3578356     6       2
2   0.70596583  0.1961721     2       2
3   0.54889439  0.7668157     3       2
10 -1.70825344 -0.6293518    10       3
4  -0.04557927 -1.6586588     4       1
1   0.33742619 -0.8535244     1       1
7   0.36133829 -0.4064025     7       1
8   0.64431246 -0.3865271     8       1
9   0.59196977 -0.3991278     9       1

Now for plotting the first graph, you need to set cluster as a factor and attribute levels based on this order:

p1 <- df %>% mutate(cluster = factor(cluster, unique(cluster))) %>%
  ggplot()+
  geom_text(aes(x=X1,y=X2,label=label ,color=cluster))+
  theme(legend.position = "none")

Then, the second plot does not change and you will finally get:

Does it answer your question ?


问:
How can i use sockets with Flutter web
I'm trying to make a connection between a socket server written in Python using socketio to a client made with Flutter Web.

I tested various socket packages like adhara_socket_io and flutter_socket_io and nothing worked. I tried the same code snippets on Android and they didn't work too.

I kept searching and i found this code snippet. It uses the Socket class from the dart.io package.

```<code>Socket socket = await Socket.connect('192.168.2.190', 7003);

    print('connected');

    // listen to the received data event stream
    socket.listen((List<int> event) {
      print(utf8.decode(event));
    });

    // send hello
    socket.add(utf8.encode('hello'));

    // wait 5 seconds
    await Future.delayed(Duration(seconds: 5));

    // .. and close the socket
    socket.close();
</code>```

This one connected to the Python server and sent the data from Android but when i tested it from Web i didn't connect.

Is there some things extra i need to add for it to work on Web?

Or in the worst case, is there another way to do what i want to do, my goal is to display a video feed in a website. The video is actually a bunch of images taken from Python, there is some machine learning that will be performed on them and i want to send them over socket and each image is displaying as soon as it is received so it looks like a video feed. (Similar thing was done using React)

答:
dart.io package is not compatible with flutter web. And I suppose  As pskink suggested websockets is the way to go. You can use HtmlWebSocketChannel from the web_socket_channel package as documented here. I have used this package and can confirm it works well in flutter web.

In your case should be using something as follows.

```<code>var channel = HtmlWebSocketChannel.connect("ws://192.168.2.190:7003");
</code>```

But do note that this is not inter operable with regular flutter app. If you aim to target both android and flutter web, then you should handle this channel creation conditionally depending on target you are building it for and decide between HtmlWebSocketChannel or IOWebSocketChannel to create the connection. If you are interested you can use a conditional stub based implementation as suggested in this post*.

* Note: its my post. :)

Title: How can i use sockets with Flutter web

Body:
I'm trying to make a connection between a socket server written in Python using socketio to a client made with Flutter Web.

I tested various socket packages like adhara_socket_io and flutter_socket_io and nothing worked. I tried the same code snippets on Android and they didn't work too.

I kept searching and i found this code snippet. It uses the Socket class from the dart.io package.

Socket socket = await Socket.connect('192.168.2.190', 7003);

    print('connected');

    // listen to the received data event stream
    socket.listen((List<int> event) {
      print(utf8.decode(event));
    });

    // send hello
    socket.add(utf8.encode('hello'));

    // wait 5 seconds
    await Future.delayed(Duration(seconds: 5));

    // .. and close the socket
    socket.close();

This one connected to the Python server and sent the data from Android but when i tested it from Web i didn't connect.

Is there some things extra i need to add for it to work on Web?

Or in the worst case, is there another way to do what i want to do, my goal is to display a video feed in a website. The video is actually a bunch of images taken from Python, there is some machine learning that will be performed on them and i want to send them over socket and each image is displaying as soon as it is received so it looks like a video feed. (Similar thing was done using React)

Body:
dart.io package is not compatible with flutter web. And I suppose  As pskink suggested websockets is the way to go. You can use HtmlWebSocketChannel from the web_socket_channel package as documented here. I have used this package and can confirm it works well in flutter web.

In your case should be using something as follows.

var channel = HtmlWebSocketChannel.connect("ws://192.168.2.190:7003");

But do note that this is not inter operable with regular flutter app. If you aim to target both android and flutter web, then you should handle this channel creation conditionally depending on target you are building it for and decide between HtmlWebSocketChannel or IOWebSocketChannel to create the connection. If you are interested you can use a conditional stub based implementation as suggested in this post*.

* Note: its my post. :)


问:
Why does using an arrow function give the updated version of the state in React in comparison to calling the function normally?
Take the following react code

```<code>class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {state1: true, state2: false, state3: "hello"}
        this.onClick = this.onClick.bind(this)

    }

    onClick() {
        this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
    }

    render() {
        return(
            <button onClick = {this.onClick}></button>
        )
    }
}

ReactDOM.render(<Foo />, document.getElementById('root'));
</code>```

When I use console.log in the callback for setState, I have to click the button twice in React in order for the console to display the correct version of state.

However, if write this.setState({state1: false, state2: true, state3: "goodbye"}, () => console.log(this.state)) instead, adding an arrow function, clicking the button once outputs the correct version of the state in the console. Why is that? Why does an arrow function output different behaviour in this scenario?

答:
In your first example, you're doing this:

```<code>this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
</code>```

That is not passing a function as the second parameter, it is evaluating the function console.log with the current value of this.state and passing its returned result (which for console.log is always undefined) as the second parameter. But if you use the second parameter of setState, React expects it to be a function, not undefined, so it won't actually have any callback to run when the state updates.

In your second example, you are actually passing a new function as the parameter, and once that function is called (as a callback, by React, when the new state has been set), that function calls console.log; by then, the state is set and so it logs the new value.

Body:
Take the following react code

class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {state1: true, state2: false, state3: "hello"}
        this.onClick = this.onClick.bind(this)

    }

    onClick() {
        this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
    }

    render() {
        return(
            <button onClick = {this.onClick}></button>
        )
    }
}

ReactDOM.render(<Foo />, document.getElementById('root'));

When I use console.log in the callback for setState, I have to click the button twice in React in order for the console to display the correct version of state.

However, if write this.setState({state1: false, state2: true, state3: "goodbye"}, () => console.log(this.state)) instead, adding an arrow function, clicking the button once outputs the correct version of the state in the console. Why is that? Why does an arrow function output different behaviour in this scenario?

Body:
In your first example, you're doing this:

this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))

That is not passing a function as the second parameter, it is evaluating the function console.log with the current value of this.state and passing its returned result (which for console.log is always undefined) as the second parameter. But if you use the second parameter of setState, React expects it to be a function, not undefined, so it won't actually have any callback to run when the state updates.

In your second example, you are actually passing a new function as the parameter, and once that function is called (as a callback, by React, when the new state has been set), that function calls console.log; by then, the state is set and so it logs the new value.