问:
getting data async from Firebase
I am trying to fetch some data from a firebase collection, however I cannot seem to get it to work properly.

My code is as follows:-

component:-

```<code>import React, { Component } from 'react'
import { connect } from 'react-redux';
import { fetchPlayers } from '../../redux/players/players.actions';

class Players extends Component {

    componentDidMount() {
        this.props.fetchPlayers();
    }

    render() {
        const { players } = this.props;

        // const playerItems = players.map(player => (
        //     <div key={player.id}>
        //         <h3>{player.name}</h3>
        //     </div>
        // ));

        return (
            <div>
                <h1>PLAYERS</h1>
                {/* {playerItems} */}
            </div>
        )
    }
}

const mapStateToProps = state => ({
    players: state.players.items,
    newPlayer: state.players.item
});

export default connect(mapStateToProps, {fetchPlayers})(Players);
</code>```

My actions file looks like this :-

```<code>import { FETCH_PLAYERS, NEW_PLAYER } from "./players.types";
import { getPlayers, addPlayer } from '../../db/firebase/players.firebase';

// this syntax below will return the dispatch (to the reducer)
export const fetchPlayers = () => dispatch => {
  const players = getPlayers();
  dispatch({
    type: FETCH_PLAYERS,
    payload: players
  });
};

export const createPlayer = playerToAdd => dispatch => {
    addPlayer(playerToAdd);
    dispatch({
        type: NEW_PLAYER,
        payload: playerToAdd
  });
};
</code>```

And my db function is as follows :-

```<code>import firebase from "../../config/firebase";

const db = firebase.firestore();

export const getPlayers = () => {
    const players = fetchData();
    return players;
}

export const addPlayer = (playerToAdd) => {
    db.collection("players").add({ ...playerToAdd });
}

const fetchData = async () => {
    let playerArr = [];
    await db.collection("players")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            playerArr = playerArr.concat(doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

    return playerArr;

}
</code>```

My problem is that in my component, the players remains as a promise, and the fetchData() db call is being returned after.

How can I await the array to be populate first (in the fetchData()) and then pass this to my component through the actions?

Thanks for your help, very much appreciated!

答:
I have managed to fix it in this way, not sure if this is the correct way though, still fairly new to Redux:-

component:-

```<code>import React, { Component } from 'react'
import { connect } from 'react-redux';
import { fetchPlayers } from '../../redux/players/players.actions';

class Players extends Component {

    componentDidMount() {
        this.props.fetchPlayers();
    }

    render() {

        const {players} = this.props;
        let playerItems = ''

        if (players) {
            playerItems = players.map(player => (
                <div key={player.id}>
                    <h3>{player.name}</h3>
                </div>
            ));
        }

        return (
            <div>
                <h1>PLAYERS</h1>
                    {playerItems}
            </div>
        )
    }
}

const mapStateToProps = state => ({
    players: state.players.items,
    newPlayer: state.players.item
});
</code>```

export default connect(mapStateToProps, {fetchPlayers})(Players);

actions:-

```<code>import { FETCH_PLAYERS, NEW_PLAYER } from "./players.types";
import { getPlayers, addPlayer } from '../../db/firebase/players.firebase';

// this syntax below will return the dispatch (to the reducer)
export const fetchPlayers = () => async dispatch => {
  const players = await getPlayers();
  dispatch({
    type: FETCH_PLAYERS,
    payload: players
  });
};

export const createPlayer = playerToAdd => dispatch => {
    addPlayer(playerToAdd);
    dispatch({
        type: NEW_PLAYER,
        payload: playerToAdd
  });
};
</code>```

firebase:-

```<code>import firebase from "../../config/firebase";

const db = firebase.firestore();

export const getPlayers = async () => {
    const players = await fetchData();
    return players;
}

export const addPlayer = (playerToAdd) => {
    db.collection("players").add({ ...playerToAdd });
}

const fetchData = async () => {
    let playerArr = [];
    await db.collection("players")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            playerArr = playerArr.concat(doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

    return playerArr;

}
</code>```

In this way its working however if you have any suggestions, more than welcome to listen to.

Thanks

Title: getting data async from Firebase

Body:
I am trying to fetch some data from a firebase collection, however I cannot seem to get it to work properly.

My code is as follows:-

component:-

import React, { Component } from 'react'
import { connect } from 'react-redux';
import { fetchPlayers } from '../../redux/players/players.actions';

class Players extends Component {

    componentDidMount() {
        this.props.fetchPlayers();
    }

    render() {
        const { players } = this.props;

        // const playerItems = players.map(player => (
        //

        //
{player.name}

        //

        // ));

        return (

PLAYERS

                {/* {playerItems} */}

        )
    }
}

const mapStateToProps = state => ({
    players: state.players.items,
    newPlayer: state.players.item
});

export default connect(mapStateToProps, {fetchPlayers})(Players);

My actions file looks like this :-

import { FETCH_PLAYERS, NEW_PLAYER } from "./players.types";
import { getPlayers, addPlayer } from '../../db/firebase/players.firebase';

// this syntax below will return the dispatch (to the reducer)
export const fetchPlayers = () => dispatch => {
  const players = getPlayers();
  dispatch({
    type: FETCH_PLAYERS,
    payload: players
  });
};

export const createPlayer = playerToAdd => dispatch => {
    addPlayer(playerToAdd);
    dispatch({
        type: NEW_PLAYER,
        payload: playerToAdd
  });
};

And my db function is as follows :-

import firebase from "../../config/firebase";

const db = firebase.firestore();

export const getPlayers = () => {
    const players = fetchData();
    return players;
}

export const addPlayer = (playerToAdd) => {
    db.collection("players").add({ ...playerToAdd });
}

const fetchData = async () => {
    let playerArr = [];
    await db.collection("players")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            playerArr = playerArr.concat(doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

    return playerArr;

}

My problem is that in my component, the players remains as a promise, and the fetchData() db call is being returned after.

How can I await the array to be populate first (in the fetchData()) and then pass this to my component through the actions?

Thanks for your help, very much appreciated!

Body:
I have managed to fix it in this way, not sure if this is the correct way though, still fairly new to Redux:-

component:-

import React, { Component } from 'react'
import { connect } from 'react-redux';
import { fetchPlayers } from '../../redux/players/players.actions';

class Players extends Component {

    componentDidMount() {
        this.props.fetchPlayers();
    }

    render() {

        const {players} = this.props;
        let playerItems = ''

        if (players) {
            playerItems = players.map(player => (
                <div key={player.id}>
                    <h3>{player.name}</h3>
                </div>
            ));
        }

        return (
            <div>
                <h1>PLAYERS</h1>
                    {playerItems}
            </div>
        )
    }
}

const mapStateToProps = state => ({
    players: state.players.items,
    newPlayer: state.players.item
});

export default connect(mapStateToProps, {fetchPlayers})(Players);

actions:-

import { FETCH_PLAYERS, NEW_PLAYER } from "./players.types";
import { getPlayers, addPlayer } from '../../db/firebase/players.firebase';

// this syntax below will return the dispatch (to the reducer)
export const fetchPlayers = () => async dispatch => {
  const players = await getPlayers();
  dispatch({
    type: FETCH_PLAYERS,
    payload: players
  });
};

export const createPlayer = playerToAdd => dispatch => {
    addPlayer(playerToAdd);
    dispatch({
        type: NEW_PLAYER,
        payload: playerToAdd
  });
};

firebase:-

import firebase from "../../config/firebase";

const db = firebase.firestore();

export const getPlayers = async () => {
    const players = await fetchData();
    return players;
}

export const addPlayer = (playerToAdd) => {
    db.collection("players").add({ ...playerToAdd });
}

const fetchData = async () => {
    let playerArr = [];
    await db.collection("players")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            playerArr = playerArr.concat(doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

    return playerArr;

}

In this way its working however if you have any suggestions, more than welcome to listen to.

Thanks


来源: stackexchange

问:
findByName() method returns null for gradle plugin task
I am using maven-publish plugin. I have a publication called myMedia. When I try executing
tasks.findByName("publishMyMediaPublicationToSnapshotRepository"), it returns null. Why does it return null if there is a task by that name that maven-publish plugin created.

I'm not able to get around this issue. Any help is greatly appreciated.

EDIT 1 : START

I tried Francisco Mateo's suggestion to use the afterEvaluate method, but this too didn't seem to work for me.

However, while trying to figure out the actual cause I came across one interesting observation. I found that the when I call  tasks.findByName("publishMyMediaPublicationToSnapshotRepository") from within a task, then it works perfectly fine and prints out the task, i.e. printTaskName runs as expected :

```<code>task printTaskName{
   doLast{
println "task name found is :--- "+tasks.findByName("publishMyMediaPublicationToSnapshotRepository")
   }
}
</code>```

Now originally in my project's build.gradle I have a publishSnapshot task followed by ordering logic using mustRunAfter method:

```<code>task publishSnapshot (dependsOn: ['createMyMediaArchive','publishMyMediaPublicationToSnapshotRepository'])
tasks.findByName("publishMyMediaPublicationToSnapshotRepository").mustRunAfter tasks.findByName("createMyMediaArchive")
publishSnapshot.mustRunAfter tasks.findByName("publishMyMediaPublicationToSnapshotRepository")
</code>```

executing the publishSnapshot task gives below error:

```<code>Cannot invoke method mustRunAfter() on null object
</code>```

tasks.findByName method doesn't seem to work here as it returns null.

Am I missing out on some basics?

EDIT 1 : END

EDIT 2 : START

The below build.gradle is an edited version of what I actually have. I am not allowed to share the script. But the script is identical in structure to what I have. The rest of build script is as it is as far as the structure and syntax is concerned, just the names changed. Gradle version is 3.5.1

build.gradle

```<code>import java.time.LocalDate;
import java.time.format.DateTimeFormatter
import java.text.SimpleDateFormat
import Tasks.PublishArtifacts
import org.gradle.api.GradleException

buildscript {
       repositories {
          abcRelease()
       }
       dependencies {
           classpath "org.codehaus.groovy.modules.http-builder:http-builder:0.7"
           classpath "commons-collections:commons-collections:3.2.1"
           classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.9.10"
       }
}

 repositories {
    mavenCentral()
    abcSnapshot()
    xyzRelease()
 }

apply plugin: 'maven-publish'
apply plugin: 'base'
apply plugin:'java'

apply from: "$rootDir/repositories.gradle"

def getMediaVersion(){
   project.mediaVersion
}

configurations{
    releaseMedia
}

 publishing{
      publications {
        myMedia(MavenPublication) {
            artifactId project.artifactId
            artifact "$project.artifactId"+"-"+getMediaVersion()+".tgz"
            version getMediaVersion()
        }
 }
         repositories project.artifactoryRepositories
 }

task publishSnapshot (dependsOn: ['createMyMediaArchive','publishMyMediaPublicationToSnapshotRepository'])

tasks.findByName("publishMyMediaPublicationToSnapshotRepository").mustRunAfter tasks.findByName("createMyMediaArchive")
publishSnapshot.mustRunAfter tasks.findByName("publishMyMediaPublicationToSnapshotRepository")

afterEvaluate { evaluated ->
    evaluated.tasks.findByName("publishMyMediaPublicationToSnapshotRepository").configure {
        println "My Media name  ---------   "+it.name
    }
}

task printTaskName{
   doLast{
println "task name found is :--- "+tasks.findByName("publishMyMediaPublicationToSnapshotRepository") // This returns task name as exected
   }
}

task createMyMediaArchive{
   doLast{
      //code for creating media
   }
}
</code>```

EDIT 2 : END

EDIT 3: START

If I run the tasks individually, i.e. first running task createMyMediaArchive and then running task publishSnapshot ,where the taskpublishSnapshot depends on
task publishHelmMediaPublicationToSnapshotRepository, ie.

```<code>task publishSnapshot (dependsOn: ['publishHelmMediaPublicationToSnapshotRepository'])
</code>```

then both the tasks run successfully. This proves that gradle does have the task publishHelmMediaPublicationToSnapshotRepository pre-configured.
Also gradlew tasks --all prints out this task.

This behavior is making things look more confusing to me.

EDIT 3 : END

答:
A lot of the configuration performed by the maven-publish plugin is done lazily.

Wrapping in afterEvaluate should work.

```<code>afterEvaluate { evaluated ->
    evaluated.tasks.findByName("publishMyMediaPublicationToSnapshotRepository").configure {
        println it.name
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using maven-publish plugin. I have a publication called myMedia. When I try executing
tasks.findByName("publishMyMediaPublicationToSnapshotRepository"), it returns null. Why does it return null if there is a task by that name that maven-publish plugin created.

I'm not able to get around this issue. Any help is greatly appreciated.

EDIT 1 : START

I tried Francisco Mateo's suggestion to use the afterEvaluate method, but this too didn't seem to work for me.

However, while trying to figure out the actual cause I came across one interesting observation. I found that the when I call  tasks.findByName("publishMyMediaPublicationToSnapshotRepository") from within a task, then it works perfectly fine and prints out the task, i.e. printTaskName runs as expected :

task printTaskName{
   doLast{
println "task name found is :--- "+tasks.findByName("publishMyMediaPublicationToSnapshotRepository")
   }
}

Now originally in my project's build.gradle I have a publishSnapshot task followed by ordering logic using mustRunAfter method:

task publishSnapshot (dependsOn: ['createMyMediaArchive','publishMyMediaPublicationToSnapshotRepository'])
tasks.findByName("publishMyMediaPublicationToSnapshotRepository").mustRunAfter tasks.findByName("createMyMediaArchive")
publishSnapshot.mustRunAfter tasks.findByName("publishMyMediaPublicationToSnapshotRepository")

executing the publishSnapshot task gives below error:

Cannot invoke method mustRunAfter() on null object

tasks.findByName method doesn't seem to work here as it returns null.

Am I missing out on some basics?

EDIT 1 : END

EDIT 2 : START

The below build.gradle is an edited version of what I actually have. I am not allowed to share the script. But the script is identical in structure to what I have. The rest of build script is as it is as far as the structure and syntax is concerned, just the names changed. Gradle version is 3.5.1

build.gradle

import java.time.LocalDate;
import java.time.format.DateTimeFormatter
import java.text.SimpleDateFormat
import Tasks.PublishArtifacts
import org.gradle.api.GradleException

buildscript {
       repositories {
          abcRelease()
       }
       dependencies {
           classpath "org.codehaus.groovy.modules.http-builder:http-builder:0.7"
           classpath "commons-collections:commons-collections:3.2.1"
           classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.9.10"
       }
}

 repositories {
    mavenCentral()
    abcSnapshot()
    xyzRelease()
 }

apply plugin: 'maven-publish'
apply plugin: 'base'
apply plugin:'java'

apply from: "$rootDir/repositories.gradle"

def getMediaVersion(){
   project.mediaVersion
}

configurations{
    releaseMedia
}

 publishing{
      publications {
        myMedia(MavenPublication) {
            artifactId project.artifactId
            artifact "$project.artifactId"+"-"+getMediaVersion()+".tgz"
            version getMediaVersion()
        }
 }
         repositories project.artifactoryRepositories
 }

task publishSnapshot (dependsOn: ['createMyMediaArchive','publishMyMediaPublicationToSnapshotRepository'])

tasks.findByName("publishMyMediaPublicationToSnapshotRepository").mustRunAfter tasks.findByName("createMyMediaArchive")
publishSnapshot.mustRunAfter tasks.findByName("publishMyMediaPublicationToSnapshotRepository")

afterEvaluate { evaluated ->
    evaluated.tasks.findByName("publishMyMediaPublicationToSnapshotRepository").configure {
        println "My Media name  ---------   "+it.name
    }
}

task printTaskName{
   doLast{
println "task name found is :--- "+tasks.findByName("publishMyMediaPublicationToSnapshotRepository") // This returns task name as exected
   }
}

task createMyMediaArchive{
   doLast{
      //code for creating media
   }
}

EDIT 2 : END

EDIT 3: START

If I run the tasks individually, i.e. first running task createMyMediaArchive and then running task publishSnapshot ,where the taskpublishSnapshot depends on
task publishHelmMediaPublicationToSnapshotRepository, ie.

task publishSnapshot (dependsOn: ['publishHelmMediaPublicationToSnapshotRepository'])

then both the tasks run successfully. This proves that gradle does have the task publishHelmMediaPublicationToSnapshotRepository pre-configured.
Also gradlew tasks --all prints out this task.

This behavior is making things look more confusing to me.

EDIT 3 : END

Body:
A lot of the configuration performed by the maven-publish plugin is done lazily.

Wrapping in afterEvaluate should work.

afterEvaluate { evaluated ->
    evaluated.tasks.findByName("publishMyMediaPublicationToSnapshotRepository").configure {
        println it.name
    }
}


问:
C++ templated return value with pure virtual function
I have an abstract Handle<T> class that contains references an objects of type T. I want to be able to have that class be able to be converted to Handle, where U is a superclass of T. I would use inheritance, but that doesn't work here. How would I go about doing this? What are good alternatives?

Example psuedo code:

```<code>template<class T>
class Handle {
public:
    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;
    virtual template<class U> operator Handle<U>* () const = 0; // being lazy with dumb pointer
};

template<class T>
class ConcreteHandle : public Handle<T> {
public:
    explicit template<class U> ConcreteHandle (U * obj) : obj(obj) {}
    virtual ~ConcreteHandle () {}
    virtual T & operator* () const {
        return *obj;
    }
    virtual T * operator-> () const {
        return obj;
    }
    virtual template<class U> operator Handle<U>* () {
        return new ConcreteHandle<U>(obj);
    }
private:
    T * obj;
};
</code>```

As requested, this is what I'm doing

```<code>class GcPool {
public:
    virtual void gc () = 0;
    virtual Handle<GcObject> * construct (GcClass clazz) = 0;
};

class CompactingPool : public GcPool {
public:
    virtual void gc () { ... }
    virtual Handle<GcObject> * construct (GcClass clazz) { ... }
private:
    Handle<GcList<Handle<GcObject> > > rootSet; // this will grow in the CompactingPool's own pool
    Handle<GcList<Handle<GcObject> > > knownHandles; // this will grow in the CompactingPool's own pool.
};
</code>```

knownHandles needs to be compatable with Handle so it can be in the CompatingPool's rootSet. Same goes for rootSet. I will bootstrap these special handles so a chicken and egg problem does not occur.

答:
```<code>virtual template<class U> operator Handle<U>* () const  =0;
</code>```

Template virtual function is not allowed by the language specification.

Consider this code at ideone, and then see the compilation error:

error: templates may not be ‘virtual’

Now what can you do? One solution is this:

```<code>template<class T>
class Handle {
public:

    typedef typename T::super super; //U = super, which is a superclass of T.

    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;

    //not a template now, but still virtual
    virtual super operator Handle<super> () const = 0;
};
</code>```

That is, define a typedef of the base class in the derived class, and use it in the Handle. Something like this:

```<code>struct Base {//...};

struct Derived : Base { typedef Base super; //...};

Handle<Derived>  handle;
</code>```

Or you can define traits, as:

```<code>struct Base {//... };

struct Derived : Base { //... };

template<typename T> struct super_traits;

struct super_traits<Derived>
{
   typedef Base super;
};

template<class T>
class Handle {
public:

    typedef typename super_traits<T>::super super; //note this now!

    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;

    //not a template now, but still virtual
    virtual super operator Handle<super> () const = 0;
};
</code>```

In my opinion, super_traits is a superior solution, as you're defining the traits of derived classes without editing them. Also, you can define as many typedefs as you want; say your derived class has more than one base, you may want to define many typedefs, or preferably a typelist.

ContentLicense: CC BY-SA 3.0

Body:
I have an abstract Handle<T> class that contains references an objects of type T. I want to be able to have that class be able to be converted to Handle, where U is a superclass of T. I would use inheritance, but that doesn't work here. How would I go about doing this? What are good alternatives?

Example psuedo code:

template<class T>
class Handle {
public:
    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;
    virtual template<class U> operator Handle* () const = 0; // being lazy with dumb pointer
};

template<class T>
class ConcreteHandle : public Handle<T> {
public:
    explicit template<class U> ConcreteHandle (U * obj) : obj(obj) {}
    virtual ~ConcreteHandle () {}
    virtual T & operator* () const {
        return *obj;
    }
    virtual T * operator-> () const {
        return obj;
    }
    virtual template<class U> operator Handle* () {
        return new ConcreteHandle(obj);
    }
private:
    T * obj;
};

As requested, this is what I'm doing

class GcPool {
public:
    virtual void gc () = 0;
    virtual Handle<GcObject> * construct (GcClass clazz) = 0;
};

class CompactingPool : public GcPool {
public:
    virtual void gc () { ... }
    virtual Handle<GcObject> * construct (GcClass clazz) { ... }
private:
    Handle<GcList<Handle<GcObject> > > rootSet; // this will grow in the CompactingPool's own pool
    Handle<GcList<Handle<GcObject> > > knownHandles; // this will grow in the CompactingPool's own pool.
};

knownHandles needs to be compatable with Handle so it can be in the CompatingPool's rootSet. Same goes for rootSet. I will bootstrap these special handles so a chicken and egg problem does not occur.

Body:
virtual template<class U> operator Handle<U>* () const  =0;

Template virtual function is not allowed by the language specification.

Consider this code at ideone, and then see the compilation error:

error: templates may not be ‘virtual’

Now what can you do? One solution is this:

template<class T>
class Handle {
public:

    typedef typename T::super super; //U = super, which is a superclass of T.

    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;

    //not a template now, but still virtual
    virtual super operator Handle<super> () const = 0;
};

That is, define a typedef of the base class in the derived class, and use it in the Handle. Something like this:

struct Base {//...};

struct Derived : Base { typedef Base super; //...};

Handle<Derived>  handle;

Or you can define traits, as:

struct Base {//... };

struct Derived : Base { //... };

template<typename T> struct super_traits;

struct super_traits<Derived>
{
   typedef Base super;
};

template<class T>
class Handle {
public:

    typedef typename super_traits<T>::super super; //note this now!

    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;

    //not a template now, but still virtual
    virtual super operator Handle<super> () const = 0;
};

In my opinion, super_traits is a superior solution, as you're defining the traits of derived classes without editing them. Also, you can define as many typedefs as you want; say your derived class has more than one base, you may want to define many typedefs, or preferably a typelist.


问:
How to restrict user to type 10 digit numbers in input element?
I want to create a input field for phone number.  I am creating input field using JavaScript dynamically.

```<code><input type="text" id="phone" name="phone">
</code>```

How to restrict users to type only 10 digit numbers in order to get a phone number.

答:
Please find below code if you want user to restrict with entering 10 digit in input control

```<code><input class="form-control  input-md text-box single-line" id="ContactNumber" max="9999999999" min="1000000000" name="ContactNumber" required="required" type="number"  value="9876658688">
</code>```

Benefits -

It will not allow to type any alphabets in input box because type of input box is 'number'

it will allow max 10 digits because max property is set to maximum possible value in 10 digits

it will not allow user to enter anything less than 10 digits as we want to restrict user in 10 digit phone number. min property in code is having minimum possible value in 10 digits so it will tell user to enter valid 10 digit value not less than that.

Body:
I want to create a input field for phone number.  I am creating input field using JavaScript dynamically.

<input type="text" id="phone" name="phone">

How to restrict users to type only 10 digit numbers in order to get a phone number.

Body:
Please find below code if you want user to restrict with entering 10 digit in input control

<input class="form-control  input-md text-box single-line" id="ContactNumber" max="9999999999" min="1000000000" name="ContactNumber" required="required" type="number"  value="9876658688">

Benefits -

It will not allow to type any alphabets in input box because type of input box is 'number'

it will allow max 10 digits because max property is set to maximum possible value in 10 digits

it will not allow user to enter anything less than 10 digits as we want to restrict user in 10 digit phone number. min property in code is having minimum possible value in 10 digits so it will tell user to enter valid 10 digit value not less than that.


问:
How to call API in R with a token
i am experimenting with R and i wonder how could i GET some data from API using library httr or rcurl..

for example with curl in terminal i can do this and it gets me the data i want:

```<code>curl -X GET "https://some.webpage.com/api/v1/accounts/self/profile" -H "accept: application/json" -H "token-auth: 72124asfin393483feifefi92835w345"
</code>```

note: token key is random set of chars

Unfortunately when i try to reproduce this in R i fail, i tried using something like:

```<code>> library(httr)
> c <- GET("https://some.webpage.com/api/v1/accounts/self/profile?token- auth=72124asfin393483feifefi92835w345"
</code>```

or this:

```<code>> url = "https://some.webpage.com/api/v1/accounts/self/profile"
> key = "{72124asfin393483feifefi92835w345}"
> a <- GET(url, add_headers(Authorization = paste("Bearer", key, sep = " ")))
</code>```

Unfortunately when i try this in Rstudio i always get this error:

```<code>[1] "'token-auth' has to be provided for authentication."
</code>```

More info about this particular API call:

This is the documentation

So i guess i obviously do something wrong with the url composition, how would i get this to work with R? I am baffled, i found some documentation on API in R, but nothing to explain how to work with a token. Thanks

答:
Correct solution is what MrFlick said:

Then try a <- GET(url, add_headers("token-auth" = key)). And make sure you don't have the braces in your key string.

Title: How to call API in R with a token

Body:
i am experimenting with R and i wonder how could i GET some data from API using library httr or rcurl..

for example with curl in terminal i can do this and it gets me the data i want:

curl -X GET "https://some.webpage.com/api/v1/accounts/self/profile" -H "accept: application/json" -H "token-auth: 72124asfin393483feifefi92835w345"

note: token key is random set of chars

Unfortunately when i try to reproduce this in R i fail, i tried using something like:

> library(httr)
> c <- GET("https://some.webpage.com/api/v1/accounts/self/profile?token- auth=72124asfin393483feifefi92835w345"

or this:

> url = "https://some.webpage.com/api/v1/accounts/self/profile"
> key = "{72124asfin393483feifefi92835w345}"
> a <- GET(url, add_headers(Authorization = paste("Bearer", key, sep = " ")))

Unfortunately when i try this in Rstudio i always get this error:

[1] "'token-auth' has to be provided for authentication."

More info about this particular API call:

This is the documentation

So i guess i obviously do something wrong with the url composition, how would i get this to work with R? I am baffled, i found some documentation on API in R, but nothing to explain how to work with a token. Thanks


问:
How do you test a mouseover for desktop in webdriverio?
It is possible to test a mobile tap event with:

browser.element('.someSelector').touch(selector,longClick);

There are other methods:

performMultiAction

performTouchAction

touchClick

touchDown

touchFlick

touchLongClick

touchMove

touchScroll

touchUp

None of these work with desktop.

答:
moveTo Command can be used for mouse hover. Please refer below link
https://webdriver.io/docs/api/element/moveTo.html

Usage:

```<code>let btn = $('#myBtn');
btn.moveTo();
</code>```

Body:
moveTo Command can be used for mouse hover. Please refer below link
https://webdriver.io/docs/api/element/moveTo.html

Usage:

let btn = $('#myBtn');
btn.moveTo();


问:
Wordpress Pemalinks not working with Varnish
I installed Varnish in a Docker image using Plesk CPanel on a WordPress website with pretty permalinks enabled. I used this guide:

https://www.plesk.com/blog/product-technology/varnish-wordpress-docker-container/

When I click on any link to an article or category, I am redirected back to the homepage with a question mark inserted and the rest of the URL. ie

https://example.com/?news/world-leaders-to-meet/

instead of

https://example.com/news/world-leaders-to-meet/

Everything works fine when I disable Varnish. I even tried cloning the website to a subdomain and permalinks work on the subdomain with Varnish enabled. I have disabled plugins and it makes no difference.

What should I do to fix the problem?

Contents of default.vcl (with fake IP address for host)

```

    vcl 4.0;
    import std;

    # MAIN CONFIGURATION
    backend default {
        .host = "123.123.123.123";
        .port = "7080";
    }

    # ALLOWED IP OF PURGE REQUESTS
    acl purge {
      "localhost";
      "127.0.0.1";
      "172.17.0.1";
      "172.17.0.2";
      "123.123.123.123";
    }

    #THE RECV FUNCTION
    # Happens before we check if we have this in cache already
    sub vcl_recv {

        # SET REALIP BY TRIMMING CLOUDFLARE IP WHICH WILL BE USED FOR VARIOUS CHECKS
        set req.http.X-Actual-IP = regsub(req.http.X-Forwarded-For, "[, ].*$", "");

        # FORWARD THE IP OF THE REQUEST
        if (req.restarts == 0) {
            if (req.http.x-forwarded-for) {
            set req.http.X-Forwarded-For =
            req.http.X-Forwarded-For + ", " + client.ip;
            } else {
            set req.http.X-Forwarded-For = client.ip;
            }
        }

        # Purge request check sections for hash_always_miss, purge and ban
        # BLOCK IF NOT IP is not in purge acl
        # Enable smart refreshing using hash_always_miss
        if (req.http.Cache-Control ~ "no-cache") {
            if (client.ip ~ purge || !std.ip(req.http.X-Actual-IP, "1.2.3.4") ~ purge) {
                set req.hash_always_miss = true;
            }
        }

        if (req.method == "PURGE") {
            if (!client.ip ~ purge || !std.ip(req.http.X-Actual-IP, "1.2.3.4") ~ purge) {
                return(synth(405,"Not allowed."));
                }
            return (purge);
        }

        if (req.method == "BAN") {
                # Same ACL check as above:
                if (!client.ip ~ purge || !std.ip(req.http.X-Actual-IP, "1.2.3.4") ~ purge) {
                                return(synth(403, "Not allowed."));
                }
                ban("req.http.host == " + req.http.host +
                        " && req.url == " + req.url);

                # Throw a synthetic page so the
                # request won't go to the backend.
                return(synth(200, "Ban added"));
        }

        # UNSET CLOUDFLARE COOKIES
        # Remove has_js and CloudFlare/Google Analytics __* cookies.
            set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(_[_a-z]+|has_js)=[^;]*", "");
            # Remove a ";" prefix, if present.
            set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");

        # For Testing: If you want to test with Varnish passing (not caching) uncomment
        # return( pass );

        # DO NOT CACHE RSS FEED
        if (req.url ~ "/feed(/)?") {
        return ( pass );
        }

        # PASS WP-CRON
        if (req.url ~ "wp-cron\.php.*") {
        return ( pass );
        }

        # DO NOT CACHE POST AND EDIT PAGES
        if (req.url ~ "(wp-admin|post\.php|edit\.php|wp-login)") {
            return(pass);
        }

        # DO NOT CACHE SEARCH RESULTS
        if (req.url ~ "/\?s\=") {
        return ( pass );
        }

        # CLEAN UP THE ENCODING HEADER.
        # SET TO GZIP, DEFLATE, OR REMOVE ENTIRELY.  WITH VARY ACCEPT-ENCODING
        # VARNISH WILL CREATE SEPARATE CACHES FOR EACH
        # DO NOT ACCEPT-ENCODING IMAGES, ZIPPED FILES, AUDIO, ETC.
        if (req.http.Accept-Encoding) {
            if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
            # No point in compressing these
            unset req.http.Accept-Encoding;
            } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
            } elsif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
            } else {
            # unknown algorithm
            unset req.http.Accept-Encoding;
            }
        }

        # PIPE ALL NON-STANDARD REQUESTS
        if (req.method != "GET" &&
            req.method != "HEAD" &&
            req.method != "PUT" &&
            req.method != "POST" &&
            req.method != "TRACE" &&
            req.method != "OPTIONS" &&
            req.method != "DELETE") {
            return (pipe);
        }

        # ONLY CACHE GET AND HEAD REQUESTS
        if (req.method != "GET" && req.method != "HEAD") {
            return (pass);
        }

        # DO NOT CACHE LOGGED IN USERS (THIS OCCURS IN FETCH TOO)
        if ( req.http.cookie ~ "wordpress_logged_in|resetpass" ) {
            return (pass);
        }

        # FIX CLOUDFLARE MIXED CONTENT WITH FLEXIBLE SSL
        if (req.http.X-Forwarded-Proto) {
            return (hash);
        }

        # IF THE REQUEST IS NOT FOR A PREVIEW, WP-ADMIN OR WP-LOGIN THEN UNSET THE COOKIES
        if (!(req.url ~ "wp-(login|admin)") && !(req.url ~ "&preview=true" )) {
            unset req.http.cookie;
        }

        # IF BASIC AUTH IS ON THEN DO NOT CACHE
        if (req.http.Authorization || req.http.Cookie) {
            return (pass);
        }

        # IF YOU GET HERE THEN THIS REQUEST SHOULD BE CACHED
        return (hash);
        # This is for phpmyadmin
        if (req.http.Host == "pmadomain.com") {
        return (pass);
        }

        # STRIP OUT URL PARAMETERS THAT LEAD TO MULTIPLE REDUNDANT CACHING
        if (req.url ~ "(\?|&)(gclid|utm_[a-z]+)=") {
        set req.url = regsuball(req.url, "(gclid|utm_[a-z]+)=[-_A-z0-9+()%.]+&?", "");
        set req.url = regsub(req.url, "[?|&]+$", "");
        }
    }

    sub vcl_hash {
        if (req.http.X-Forwarded-Proto) {
            hash_data(req.http.X-Forwarded-Proto);
            }
        }

    # HIT FUNCTION
    sub vcl_hit {
      return (deliver);
    }

    # MISS FUNCTION
    sub vcl_miss {
      return (fetch);
    }

    # FETCH FUNCTION
    sub vcl_backend_response {
        # IF NOT WP-ADMIN THEN UNSET COOKIES AND SET THE AMOUNT OF TIME THIS PAGE WILL STAY CACHED (TTL)
        if (!(bereq.url ~ "wp-(login|admin)") && !bereq.http.cookie ~ "wordpress_logged_in|resetpass" ) {
            unset beresp.http.set-cookie;
            set beresp.ttl = 1w;
            set beresp.grace = 3d;
        }

        if (beresp.ttl  0) {
             # IF THIS PAGE IS ALREADY CACHED THEN RETURN A 'HIT' TEXT
            set resp.http.X-Cache = "HIT";
        } else {
            # IF THIS IS A MISS RETURN THAT IN THE HEADER
            set resp.http.X-Cache = "MISS";
        }
    }

```

答:
Your VCL code looks pretty legit. My guess is that it might be the URL rewriting logic in your webserver (Apache or Nginx), or maybe even WordPress that does this redirection.

Varnishlog output

The easiest way to find out is by running varnishlog while the issue is occurring. Feel free to post a redacted record of the varnishlog output.

If you need help operating Varnishlog, have look at the following blog post I wrote a couple of years ago: https://feryn.eu/blog/varnishlog-measure-varnish-cache-performance/.

Lack of SSL awareness

Another possibility is that WordPress is not aware of the fact that an HTTP-base reverse caching proxy sits in front if it.

Varnish currently doesn't offer native SSL/TLS support, so SSL needs to be terminated and interactions between Varnish & WordPress happen over plain HTTP.

If WordPress is set up to automatically redirect plain HTTP requests into HTTPS request, you might end up in a loop.

If that is the case, please have a look at the following blog post I wrote about this: https://feryn.eu/blog/mixed-content-and-err-too-many-redirects-in-wordpress/

Body:
I installed Varnish in a Docker image using Plesk CPanel on a WordPress website with pretty permalinks enabled. I used this guide:

https://www.plesk.com/blog/product-technology/varnish-wordpress-docker-container/

When I click on any link to an article or category, I am redirected back to the homepage with a question mark inserted and the rest of the URL. ie

https://example.com/?news/world-leaders-to-meet/

instead of

https://example.com/news/world-leaders-to-meet/

Everything works fine when I disable Varnish. I even tried cloning the website to a subdomain and permalinks work on the subdomain with Varnish enabled. I have disabled plugins and it makes no difference.

What should I do to fix the problem?

Contents of default.vcl (with fake IP address for host)

    vcl 4.0;
    import std;

    # MAIN CONFIGURATION
    backend default {
        .host = "123.123.123.123";
        .port = "7080";
    }

    # ALLOWED IP OF PURGE REQUESTS
    acl purge {
      "localhost";
      "127.0.0.1";
      "172.17.0.1";
      "172.17.0.2";
      "123.123.123.123";
    }

    #THE RECV FUNCTION
    # Happens before we check if we have this in cache already
    sub vcl_recv {

        # SET REALIP BY TRIMMING CLOUDFLARE IP WHICH WILL BE USED FOR VARIOUS CHECKS
        set req.http.X-Actual-IP = regsub(req.http.X-Forwarded-For, "[, ].*$", "");

        # FORWARD THE IP OF THE REQUEST
        if (req.restarts == 0) {
            if (req.http.x-forwarded-for) {
            set req.http.X-Forwarded-For =
            req.http.X-Forwarded-For + ", " + client.ip;
            } else {
            set req.http.X-Forwarded-For = client.ip;
            }
        }

        # Purge request check sections for hash_always_miss, purge and ban
        # BLOCK IF NOT IP is not in purge acl
        # Enable smart refreshing using hash_always_miss
        if (req.http.Cache-Control ~ "no-cache") {
            if (client.ip ~ purge || !std.ip(req.http.X-Actual-IP, "1.2.3.4") ~ purge) {
                set req.hash_always_miss = true;
            }
        }

        if (req.method == "PURGE") {
            if (!client.ip ~ purge || !std.ip(req.http.X-Actual-IP, "1.2.3.4") ~ purge) {
                return(synth(405,"Not allowed."));
                }
            return (purge);
        }

        if (req.method == "BAN") {
                # Same ACL check as above:
                if (!client.ip ~ purge || !std.ip(req.http.X-Actual-IP, "1.2.3.4") ~ purge) {
                                return(synth(403, "Not allowed."));
                }
                ban("req.http.host == " + req.http.host +
                        " && req.url == " + req.url);

                # Throw a synthetic page so the
                # request won't go to the backend.
                return(synth(200, "Ban added"));
        }

        # UNSET CLOUDFLARE COOKIES
        # Remove has_js and CloudFlare/Google Analytics __* cookies.
            set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(_[_a-z]+|has_js)=[^;]*", "");
            # Remove a ";" prefix, if present.
            set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");

        # For Testing: If you want to test with Varnish passing (not caching) uncomment
        # return( pass );

        # DO NOT CACHE RSS FEED
        if (req.url ~ "/feed(/)?") {
        return ( pass );
        }

        # PASS WP-CRON
        if (req.url ~ "wp-cron\.php.*") {
        return ( pass );
        }

        # DO NOT CACHE POST AND EDIT PAGES
        if (req.url ~ "(wp-admin|post\.php|edit\.php|wp-login)") {
            return(pass);
        }

        # DO NOT CACHE SEARCH RESULTS
        if (req.url ~ "/\?s\=") {
        return ( pass );
        }

        # CLEAN UP THE ENCODING HEADER.
        # SET TO GZIP, DEFLATE, OR REMOVE ENTIRELY.  WITH VARY ACCEPT-ENCODING
        # VARNISH WILL CREATE SEPARATE CACHES FOR EACH
        # DO NOT ACCEPT-ENCODING IMAGES, ZIPPED FILES, AUDIO, ETC.
        if (req.http.Accept-Encoding) {
            if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
            # No point in compressing these
            unset req.http.Accept-Encoding;
            } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
            } elsif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
            } else {
            # unknown algorithm
            unset req.http.Accept-Encoding;
            }
        }

        # PIPE ALL NON-STANDARD REQUESTS
        if (req.method != "GET" &&
            req.method != "HEAD" &&
            req.method != "PUT" &&
            req.method != "POST" &&
            req.method != "TRACE" &&
            req.method != "OPTIONS" &&
            req.method != "DELETE") {
            return (pipe);
        }

        # ONLY CACHE GET AND HEAD REQUESTS
        if (req.method != "GET" && req.method != "HEAD") {
            return (pass);
        }

        # DO NOT CACHE LOGGED IN USERS (THIS OCCURS IN FETCH TOO)
        if ( req.http.cookie ~ "wordpress_logged_in|resetpass" ) {
            return (pass);
        }

        # FIX CLOUDFLARE MIXED CONTENT WITH FLEXIBLE SSL
        if (req.http.X-Forwarded-Proto) {
            return (hash);
        }

        # IF THE REQUEST IS NOT FOR A PREVIEW, WP-ADMIN OR WP-LOGIN THEN UNSET THE COOKIES
        if (!(req.url ~ "wp-(login|admin)") && !(req.url ~ "&preview=true" )) {
            unset req.http.cookie;
        }

        # IF BASIC AUTH IS ON THEN DO NOT CACHE
        if (req.http.Authorization || req.http.Cookie) {
            return (pass);
        }

        # IF YOU GET HERE THEN THIS REQUEST SHOULD BE CACHED
        return (hash);
        # This is for phpmyadmin
        if (req.http.Host == "pmadomain.com") {
        return (pass);
        }

        # STRIP OUT URL PARAMETERS THAT LEAD TO MULTIPLE REDUNDANT CACHING
        if (req.url ~ "(\?|&)(gclid|utm_[a-z]+)=") {
        set req.url = regsuball(req.url, "(gclid|utm_[a-z]+)=[-_A-z0-9+()%.]+&?", "");
        set req.url = regsub(req.url, "[?|&]+$", "");
        }
    }

    sub vcl_hash {
        if (req.http.X-Forwarded-Proto) {
            hash_data(req.http.X-Forwarded-Proto);
            }
        }

    # HIT FUNCTION
    sub vcl_hit {
      return (deliver);
    }

    # MISS FUNCTION
    sub vcl_miss {
      return (fetch);
    }

    # FETCH FUNCTION
    sub vcl_backend_response {
        # IF NOT WP-ADMIN THEN UNSET COOKIES AND SET THE AMOUNT OF TIME THIS PAGE WILL STAY CACHED (TTL)
        if (!(bereq.url ~ "wp-(login|admin)") && !bereq.http.cookie ~ "wordpress_logged_in|resetpass" ) {
            unset beresp.http.set-cookie;
            set beresp.ttl = 1w;
            set beresp.grace = 3d;
        }

        if (beresp.ttl  0) {
             # IF THIS PAGE IS ALREADY CACHED THEN RETURN A 'HIT' TEXT
            set resp.http.X-Cache = "HIT";
        } else {
            # IF THIS IS A MISS RETURN THAT IN THE HEADER
            set resp.http.X-Cache = "MISS";
        }
    }


问:
In Slate.js editor.apply(operation) is not applying "split_node" operations correctly
I am designing a google-doc like collaborative tool with latest React + Slate as Frontend and Flask in Backend. I am using socket-io in React and flask_socketio in Python to emit and listen content from other collaborators.
React app code:

```<code>const RichTextExample = props => {
  const [value, setValue] = useState(props.currentEditor);
  const editor = useMemo(() => withHistory(withReact(createEditor())), []);
  const id = useRef(`${Date.now()}`);
  const remote = useRef(false);
  const socketchange = useRef(false);

  useEffect(() => {
    socket.on("new-remote-operations", ({ editorId, ops, doc_id }) => {
      if (id.current !== editorId && doc_id === props.document.doc_id) {
        remote.current = true;
        JSON.parse(ops).forEach(op => {
          console.log("LISTEN: applying op", op);
          editor.apply(op);
        });
        remote.current = false;
        console.log('value is ', value);
        socketchange.current = true; //variable to track socket changes in editor via operations
      }
    });}, [])
    return(
    <Slate
        editor={editor}
        value={value}
        onChange={value => {
          setValue(value);
          const ops = editor.operations
          .filter(o => {
            if (o) {
              return o.type !== "set_selection" && o.type !== "set_value";
            }
            return false;
          });
          if (ops.length && !remote.current && !socketchange.current) {
            console.log("EMIT: Editor operations are ", ops);
            socket.emit("new-operations", {
              editorId: id.current,
              ops: JSON.stringify(ops),
              doc_id: props.document.doc_id
            });
          }
          socketchange.current = false;
        }}
      >
</code>```

Python code for socket is simple:

```<code>app = Flask(__name__)
db_name = 'userdoc.db'
app.config['SECRET_KEY'] = 'secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+db_name
socketio = SocketIO(app, cors_allowed_origins="*")
@socketio.on('new-operations', namespace='/')
def operations(data):
    print('operations listened...1/2/3..')
    emit('new-remote-operations', data, broadcast=True, include_self=False)
</code>```

Issue:

When split_node is passed as an type of operation in socket.on(),
editor.apply(op) doesn't apply it as it suppose to. Please help me on this.

Because of this, I get following two cases:

答:
I think the issue you are facing is because you send a batch of operations that should not be applied one by one.

A split_node operation like the one you are generating by hitting enter will actually split all the nested nodes till it reaches the leaves, and move some nodes around.

Concretely, a split_node is actually 2-3 operations following each others, that can't be applied solely. If you apply the first one for example, that would split the text node, and end up with two Text sharing the same attributes. Slate will normalize them and re-merge them as soon as it can, which in your case, happen between each editor.apply(op).

I think the solution here, is simply to wrap your whole loop inside the withoutNormalizing method. It will prevent Slate to normalize the document in-between the operations.

For Slate <= 0.47

editor.withoutNormalizing(() => {
  JSON.parse(ops).forEach(op => {
    editor.apply(op);
  });
})
```

<h3>For Slate >= 0.5</h3>

<pre class="lang-js prettyprint-override"><code>Editor.withoutNormalizing(editor, () => {
  JSON.parse(ops).forEach(op => {
    editor.apply(op);
  });
})
</code>```

Body:
I am designing a google-doc like collaborative tool with latest React + Slate as Frontend and Flask in Backend. I am using socket-io in React and flask_socketio in Python to emit and listen content from other collaborators.
React app code:

const RichTextExample = props => {
  const [value, setValue] = useState(props.currentEditor);
  const editor = useMemo(() => withHistory(withReact(createEditor())), []);
  const id = useRef(`${Date.now()}`);
  const remote = useRef(false);
  const socketchange = useRef(false);

  useEffect(() => {
    socket.on("new-remote-operations", ({ editorId, ops, doc_id }) => {
      if (id.current !== editorId && doc_id === props.document.doc_id) {
        remote.current = true;
        JSON.parse(ops).forEach(op => {
          console.log("LISTEN: applying op", op);
          editor.apply(op);
        });
        remote.current = false;
        console.log('value is ', value);
        socketchange.current = true; //variable to track socket changes in editor via operations
      }
    });}, [])
    return(
    <Slate
        editor={editor}
        value={value}
        onChange={value => {
          setValue(value);
          const ops = editor.operations
          .filter(o => {
            if (o) {
              return o.type !== "set_selection" && o.type !== "set_value";
            }
            return false;
          });
          if (ops.length && !remote.current && !socketchange.current) {
            console.log("EMIT: Editor operations are ", ops);
            socket.emit("new-operations", {
              editorId: id.current,
              ops: JSON.stringify(ops),
              doc_id: props.document.doc_id
            });
          }
          socketchange.current = false;
        }}
      >

Python code for socket is simple:

app = Flask(__name__)
db_name = 'userdoc.db'
app.config['SECRET_KEY'] = 'secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+db_name
socketio = SocketIO(app, cors_allowed_origins="*")
@socketio.on('new-operations', namespace='/')
def operations(data):
    print('operations listened...1/2/3..')
    emit('new-remote-operations', data, broadcast=True, include_self=False)

Issue:

When split_node is passed as an type of operation in socket.on(),
editor.apply(op) doesn't apply it as it suppose to. Please help me on this.

Because of this, I get following two cases:

Body:
I think the issue you are facing is because you send a batch of operations that should not be applied one by one.

A split_node operation like the one you are generating by hitting enter will actually split all the nested nodes till it reaches the leaves, and move some nodes around.

Concretely, a split_node is actually 2-3 operations following each others, that can't be applied solely. If you apply the first one for example, that would split the text node, and end up with two Text sharing the same attributes. Slate will normalize them and re-merge them as soon as it can, which in your case, happen between each editor.apply(op).

I think the solution here, is simply to wrap your whole loop inside the withoutNormalizing method. It will prevent Slate to normalize the document in-between the operations.

For Slate <= 0.47

editor.withoutNormalizing(() => {
  JSON.parse(ops).forEach(op => {
    editor.apply(op);
  });
})

For Slate >= 0.5

Editor.withoutNormalizing(editor, () => {
  JSON.parse(ops).forEach(op => {
    editor.apply(op);
  });
})


问:
Removing duplicate values without using distinct
I have written the below query using BigQuery and it gives me duplicate article values. I have tried using distinct but it doesn't seem to work somehow so now I'm looking into removing the duplicates with other methods.     </p>

```<code>select
      replace(article, ' - paper', '') as p,
      pageviews,
      login_clicks,
      paywall_clicks
    from analytics.article_action_week
</code>```

答:
You can use aggregation in BigQuery to remove duplicates:

```<code>select replace(article, ' - paper', '') as p,
       any_value(struct(pageviews, login_clicks, paywall_clicks)
                ).*
from analytics.article_action_week aaw
group by p;
</code>```

Note:  This returns an arbitrary row.  I might suggest from the context, that you actually want aggregation:

```<code>select replace(article, ' - paper', '') as p,
       sum(pageviews) as pageviews,
       sum(login_clicks) as login_clicks,
       sum(paywall_clicks) as paywall_clicks
from analytics.article_action_week aaw
group by p;
</code>```

This will add up the measures across the different rows.

Body:
I have written the below query using BigQuery and it gives me duplicate article values. I have tried using distinct but it doesn't seem to work somehow so now I'm looking into removing the duplicates with other methods.

select
      replace(article, ' - paper', '') as p,
      pageviews,
      login_clicks,
      paywall_clicks
    from analytics.article_action_week

Body:
You can use aggregation in BigQuery to remove duplicates:

select replace(article, ' - paper', '') as p,
       any_value(struct(pageviews, login_clicks, paywall_clicks)
                ).*
from analytics.article_action_week aaw
group by p;

Note:  This returns an arbitrary row.  I might suggest from the context, that you actually want aggregation:

select replace(article, ' - paper', '') as p,
       sum(pageviews) as pageviews,
       sum(login_clicks) as login_clicks,
       sum(paywall_clicks) as paywall_clicks
from analytics.article_action_week aaw
group by p;

This will add up the measures across the different rows.


问:
Powershell- How to identify via variable, the matched string index on a array
```<code>$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}
</code>```

how to get the index of the match string?

答:
This is a practical example that uses BinarySearch and relies on your look-up array being sorted by the property of "interest".

Uses IComparer to force case insensitivity

```<code># BinarySearch needs a sorted array
$mySortedArray = Get-ChildItem $env:TEMP | Sort-Object -Property Name
# Provide files available on your machine
$anotherArray = @(
  'mat-debug-23484.log'
  'MSIaa547.LOG'.ToLower()
)
foreach ($item in $anotherArray) {
  $index = $null
  # BinarySearch defaults to being case sensitive
  $index = [array]::BinarySearch($mySortedArray.Name, $item,[Collections.CaseInsensitiveComparer]::Default)
  # If no matches found index will be negative
  if ($index -ge 0) {
    Write-Host ('Index {0} filename {1} found!' -f $index, $mySortedArray[$index].Name) -ForegroundColor Green
  }
}

# Adjusted to meet your example code
$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow') | Sort-Object

$array | ForEach-Object {
$currentObject = $_
$index = $null
$index = [array]::BinarySearch($array2, $currentObject, [System.Collections.CaseInsensitiveComparer]::Default)
if ($index -ge 0) {
    Write-Host ('Index={0} array2 value="{1}" found!' -f $index, $array2[$index]) -ForegroundColor Green
}
}
</code>```

Body:
$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}

how to get the index of the match string?

Body:
This is a practical example that uses BinarySearch and relies on your look-up array being sorted by the property of "interest".

Uses IComparer to force case insensitivity

# BinarySearch needs a sorted array
$mySortedArray = Get-ChildItem $env:TEMP | Sort-Object -Property Name
# Provide files available on your machine
$anotherArray = @(
  'mat-debug-23484.log'
  'MSIaa547.LOG'.ToLower()
)
foreach ($item in $anotherArray) {
  $index = $null
  # BinarySearch defaults to being case sensitive
  $index = [array]::BinarySearch($mySortedArray.Name, $item,[Collections.CaseInsensitiveComparer]::Default)
  # If no matches found index will be negative
  if ($index -ge 0) {
    Write-Host ('Index {0} filename {1} found!' -f $index, $mySortedArray[$index].Name) -ForegroundColor Green
  }
}

# Adjusted to meet your example code
$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow') | Sort-Object

$array | ForEach-Object {
$currentObject = $_
$index = $null
$index = [array]::BinarySearch($array2, $currentObject, [System.Collections.CaseInsensitiveComparer]::Default)
if ($index -ge 0) {
    Write-Host ('Index={0} array2 value="{1}" found!' -f $index, $array2[$index]) -ForegroundColor Green
}
}


问:
2 foreign keys one create blade
I think its an easy one but my brain is not trying to comprehend it. So the issue is I have a series table, a seasons table and an episode table.
I create a series, then I create a season by selecting a series, and then I create episodes by first selecting a series and then the season.
I am stuck in the episodes part. What I wanted was that when I select a seasons, only the series related to that series are in the drop down table. Can I get some assistance on how to tackle this issue.
Also, in my episodes table, I do have season_id and episode_id.
Here is my create blade for Episode:

@extends('layouts.admin')

@section('content')

                Create Episode

            <form action="{{route('episodes.store')}}" method="post" enctype="multipart/form-data">
                @csrf

                    Series
                    <select class="form-control" name="series_id">
                        @foreach ($series as $series)
                            <option value="{{$series->id}}">{{$series->name}}</option>
                        @endforeach
                    </select>

                    Seasons
                    <select class="form-control" name="season_id">
                        @foreach ($seasons as $seasons)
                            <option value="{{$seasons->id}}">{{$seasons->name}}</option>
                        @endforeach
                    </select>

                    Name
                    <input type="text" class="form-control" name="name" id="name">

                    About
                    <textarea name="about" id="" class="form-control" cols="30" rows="10">About</textarea>

                    Subtitle
                    <input type="text" class="form-control" name="subtitle">

                    Serial Number
                    <input type="text" class="form-control" name="serno">

                            URL 1
                            <input type="text" class="form-control" name="subtitle">

                            URL 2
                            <input type="text" class="form-control" name="subtitle">

                            URL 3
                            <input type="text" class="form-control" name="subtitle">

                    Image
                    <input type="file" name="image" class="form-control">

                <button type="submit" class="btn btn-primary">Save</button>
            </form>

@endsection```
</div>
</div>
</p>

<p>Here is the function for create:</p>

```public function create()
    {
        $seasons = Season::all();
        $series = Series::all();
        return view('admin.episodes.create', compact('seasons', 'series'));
    }
```

<p>Now I want to do something with the series, where I select seasons from Season::all and then show series from the season I have selected.
<br>EDIT:
Here is how my migrations look:
<br>Series:</p>

```Schema::create('series', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->string('about');
            $table->string('image');
            $table->timestamps();
        });
```

<p>Seasons:</p>

```Schema::create('seasons', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('series_id');
            $table->string('name');
            $table->string('slug');
            $table->string('subtitle');
            $table->string('about');
            $table->string('image');
            $table->integer('serno');
            $table->timestamps();
        });
```

<p>Episodes:</p>

```Schema::create('episodes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('series_id');
            $table->integer('season_id');
            $table->string('name');
            $table->string('slug');
            $table->string('subtitle');
            $table->string('about');
            $table->string('image');
            $table->integer('serno');
            $table->string('url');
            $table->string('url2');
            $table->string('url3');
            $table->string('medium');
            $table->string('medium2');
            $table->string('medium3');
            $table->timestamps();
        });
```

答:
a series has multiple seasons. so you need a dependent drop-down for seasons while creating a new episode. you can use ajax request for loading dependent drop-down select data. when a series will be selected, a request will pass and seasons for that series will be returned.

so starting with the form

```<code><div class="form-group">
    <label for="series_id">Series</label>
    <select class="form-control" name="series_id" id="series_id">
        @foreach ($series as $series)
            <option value="{{$series->id}}">{{$series->name}}</option>
        @endforeach
    </select>
</div>
<div class="form-group">
    <label for="season_id">Seasons</label>
    <select class="form-control" name="season_id" id="season_id">
        <option value="">Select</option>
    </select>
</div>
</code>```

the script section

```<code><script src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script>
    $('#series_id').change(function(){
        var id = $(this).val();
        var url = '{{ route("getSeasons", ":id") }}';
        url = url.replace(':id', id);

        $('#season_id').find('option').not(':first').remove();
        $.ajax({
           url: url,
           type: 'get',
           dataType: 'json',
           success: function(response){
               var len = 0;
               if(response != null){
                   len = response.length;
               }
               else {
                   alert('sorry, no seasons were found for this series');
               }
               if(len > 0){
                   for(var i=0; i<len; i++){
                       var id = response[i].id;
                       var name = response[i].name;
                       var option = "<option value='"+id+"'>"+name+"</option>";
                       $("#season_id").append(option);
                   }
               }
            }
        });
    });
</script>
</code>```

the route in the web.php file

```<code>Route::get('getseasons/{id}', 'YourController@getSeasons')->name('getSeasons');
</code>```

and the controller code

```<code>public function getSeasons($id=0){
    $data = Season::where('series_id',$id)->get();
    return response()->json($data);
}
</code>```

feel free to ask anything you don't understand :)

Title: 2 foreign keys one create blade

Body:
I think its an easy one but my brain is not trying to comprehend it. So the issue is I have a series table, a seasons table and an episode table.
I create a series, then I create a season by selecting a series, and then I create episodes by first selecting a series and then the season.
I am stuck in the episodes part. What I wanted was that when I select a seasons, only the series related to that series are in the drop down table. Can I get some assistance on how to tackle this issue.
Also, in my episodes table, I do have season_id and episode_id.
Here is my create blade for Episode:

@extends('layouts.admin')

@section('content')

                Create Episode

            <form action="{{route('episodes.store')}}" method="post" enctype="multipart/form-data">
                @csrf

                    Series
                    <select class="form-control" name="series_id">
                        @foreach ($series as $series)
                            <option value="{{$series->id}}">{{$series->name}}</option>
                        @endforeach
                    </select>

                    Seasons
                    <select class="form-control" name="season_id">
                        @foreach ($seasons as $seasons)
                            <option value="{{$seasons->id}}">{{$seasons->name}}</option>
                        @endforeach
                    </select>

                    Name
                    <input type="text" class="form-control" name="name" id="name">

                    About
                    <textarea name="about" id="" class="form-control" cols="30" rows="10">About</textarea>

                    Subtitle
                    <input type="text" class="form-control" name="subtitle">

                    Serial Number
                    <input type="text" class="form-control" name="serno">

                            URL 1
                            <input type="text" class="form-control" name="subtitle">

                            URL 2
                            <input type="text" class="form-control" name="subtitle">

                            URL 3
                            <input type="text" class="form-control" name="subtitle">

                    Image
                    <input type="file" name="image" class="form-control">

                <button type="submit" class="btn btn-primary">Save</button>
            </form>

@endsection

Here is the function for create:

public function create()
    {
        $seasons = Season::all();
        $series = Series::all();
        return view('admin.episodes.create', compact('seasons', 'series'));
    }

Now I want to do something with the series, where I select seasons from Season::all and then show series from the season I have selected.

EDIT:
Here is how my migrations look:

Series:

Schema::create('series', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->string('about');
            $table->string('image');
            $table->timestamps();
        });

Seasons:

Schema::create('seasons', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('series_id');
            $table->string('name');
            $table->string('slug');
            $table->string('subtitle');
            $table->string('about');
            $table->string('image');
            $table->integer('serno');
            $table->timestamps();
        });

Episodes:

Schema::create('episodes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('series_id');
            $table->integer('season_id');
            $table->string('name');
            $table->string('slug');
            $table->string('subtitle');
            $table->string('about');
            $table->string('image');
            $table->integer('serno');
            $table->string('url');
            $table->string('url2');
            $table->string('url3');
            $table->string('medium');
            $table->string('medium2');
            $table->string('medium3');
            $table->timestamps();
        });

Body:
a series has multiple seasons. so you need a dependent drop-down for seasons while creating a new episode. you can use ajax request for loading dependent drop-down select data. when a series will be selected, a request will pass and seasons for that series will be returned.

so starting with the form

<div class="form-group">
    <label for="series_id">Series</label>
    <select class="form-control" name="series_id" id="series_id">
        @foreach ($series as $series)
            <option value="{{$series->id}}">{{$series->name}}</option>
        @endforeach
    </select>
</div>
<div class="form-group">
    <label for="season_id">Seasons</label>
    <select class="form-control" name="season_id" id="season_id">
        <option value="">Select</option>
    </select>
</div>

the script section

<script src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script>
    $('#series_id').change(function(){
        var id = $(this).val();
        var url = '{{ route("getSeasons", ":id") }}';
        url = url.replace(':id', id);

        $('#season_id').find('option').not(':first').remove();
        $.ajax({
           url: url,
           type: 'get',
           dataType: 'json',
           success: function(response){
               var len = 0;
               if(response != null){
                   len = response.length;
               }
               else {
                   alert('sorry, no seasons were found for this series');
               }
               if(len > 0){
                   for(var i=0; i<len; i++){
                       var id = response[i].id;
                       var name = response[i].name;
                       var option = "<option value='"+id+"'>"+name+"</option>";
                       $("#season_id").append(option);
                   }
               }
            }
        });
    });
</script>

the route in the web.php file

Route::get('getseasons/{id}', 'YourController@getSeasons')->name('getSeasons');

and the controller code

public function getSeasons($id=0){
    $data = Season::where('series_id',$id)->get();
    return response()->json($data);
}

feel free to ask anything you don't understand :)


问:
What are logits? What is the difference between softmax and softmax_cross_entropy_with_logits?
In the tensorflow API docs they use a keyword called logits. What is it? A lot of methods are written like:

```<code>tf.nn.softmax(logits, name=None)
</code>```

If logits is just a generic Tensor input, why is it named logits?

Secondly, what is the difference between the following two methods?

```<code>tf.nn.softmax(logits, name=None)
tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)
</code>```

I know what tf.nn.softmax does, but not the other. An example would be really helpful.

答:
Tensorflow 2.0 Compatible Answer: The explanations of dga and stackoverflowuser2010 are very detailed about Logits and the related Functions.

All those functions, when used in Tensorflow 1.x will work fine, but if you migrate your code from 1.x (1.14, 1.15, etc) to 2.x (2.0, 2.1, etc..), using those functions result in error.

Hence, specifying the 2.0 Compatible Calls for all the functions, we discussed above, if we migrate from 1.x to 2.x, for the benefit of the community.

Functions in 1.x:

tf.nn.softmax

tf.nn.softmax_cross_entropy_with_logits

tf.nn.sparse_softmax_cross_entropy_with_logits

Respective Functions when Migrated from 1.x  to 2.x:

tf.compat.v2.nn.softmax

tf.compat.v2.nn.softmax_cross_entropy_with_logits

tf.compat.v2.nn.sparse_softmax_cross_entropy_with_logits

For more information about migration from 1.x to 2.x, please refer this Migration Guide.

Body:
In the tensorflow API docs they use a keyword called logits. What is it? A lot of methods are written like:

tf.nn.softmax(logits, name=None)

If logits is just a generic Tensor input, why is it named logits?

Secondly, what is the difference between the following two methods?

tf.nn.softmax(logits, name=None)
tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)

I know what tf.nn.softmax does, but not the other. An example would be really helpful.


问:
using generic createapiview and updateapiview in the same view in django restframework
Iam trying to find out if it is possible to post and patch in the same view using the generic api method in Django rest framework. I dont think there is any generic class that allows create and update altogether, can anyone tell me if the below configuration would allow me to use post and patch method in the same view. </p>

```<code>class QuestionList(generics.updateAPIView, generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
</code>```

答:
I'm not sure if that is possible but, You can create two views like this

```<code>class CreateSomeView(AuthenticatedView, CreateAPIView):

    queryset = Some.objects.all()
    serializer_class = SomeSerializer

    def create(self, request):
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

 class SomeView(AuthenticatedView, UpdateAPIView):

    queryset = Some.objects.all()
    serializer_class = SomeSerializer

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
</code>```

and two urls something like that

```<code>path('some/', CreateSomeView.as_view(), name="create-some-details"),
path('some/<int:pk>/', SomeView.as_view(), name="some-details"),
</code>```

Now, from front-end you can send request with  if you want to update or without id if you wish to create new. You don't have to create two serializers.

Body:
Iam trying to find out if it is possible to post and patch in the same view using the generic api method in Django rest framework. I dont think there is any generic class that allows create and update altogether, can anyone tell me if the below configuration would allow me to use post and patch method in the same view.

class QuestionList(generics.updateAPIView, generics.CreateAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

Body:
I'm not sure if that is possible but, You can create two views like this

class CreateSomeView(AuthenticatedView, CreateAPIView):

    queryset = Some.objects.all()
    serializer_class = SomeSerializer

    def create(self, request):
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

 class SomeView(AuthenticatedView, UpdateAPIView):

    queryset = Some.objects.all()
    serializer_class = SomeSerializer

    def update(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

and two urls something like that

path('some/', CreateSomeView.as_view(), name="create-some-details"),
path('some/<int:pk>/', SomeView.as_view(), name="some-details"),

Now, from front-end you can send request with  if you want to update or without id if you wish to create new. You don't have to create two serializers.


问:
React making axios get, returns error: CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am trying to make an axios get request, but i am getting corse policy error. I am kinda new to axios, this is what i tried:

```<code>useEffect(() => {
    let url =
      'http://18.189.49.66:3000/api/calculate/' +
      props.type +
      '/' +
      height +
      '/' +
      width;

    var config = {
      headers: { 'Access-Control-Allow-Origin': '*' }
    };

    axios.get(url, config).then(_result => {
      console.log('Duomenys: ' + JSON.stringify(_result));
    });

}, [length, width, height]);
</code>```

In my app.js on node.js express i have these lines:

```<code>var cors = require('cors');
app.use(cors());
</code>```

And here is the error:

Access to XMLHttpRequest at 'http://18.189.49.66:3000/api/calculate/LF/80/200'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:172 GET http://18.189.49.66:3000/api/calculate/LF/80/200 net::ERR_FAILED dispatchXhrRequest
@ xhr.js:172 xhrAdapter
@ xhr.js:11 dispatchRequest
@ dispatchRequest.js:59 Promise.then (async) request
@ Axios.js:53 Axios.<computed>
@ Axios.js:68 wrap
@ bind.js:9 (anonymous)
@ Calculator.js:113 commitHookEffectList
@ react-dom.development.js:22030 commitPassiveHookEffects
@ react-dom.development.js:22064 callCallback
@ react-dom.development.js:336 invokeGuardedCallbackDev
@ react-dom.development.js:385 invokeGuardedCallback
@ react-dom.development.js:440 flushPassiveEffectsImpl
@ react-dom.development.js:25392 unstable_runWithPriority
@ scheduler.development.js:697 runWithPriority$2
@ react-dom.development.js:12149 flushPassiveEffects
@ react-dom.development.js:25361 flushDiscreteUpdates
@ react-dom.development.js:24359 finishEventHandler
@ react-dom.development.js:1384 batchedEventUpdates
@ react-dom.development.js:1418 dispatchEventForPluginEventSystem
@ react-dom.development.js:5894 attemptToDispatchEvent
@ react-dom.development.js:6010 dispatchEvent
@ react-dom.development.js:5914 ListPicker._handleMouseUp createError.js:16

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)
```

<p>My backend:</p>

<p>...
    var cors = require('cors');
    ...</p>

```app.use(cors());
```

...

How should i edit my request?

答:
You need to add cors in the backend - Basically you will have to tell the backend the url from which you will be requesting through

I have used "cors" but I found "Access to XMLHttpRequest has been blocked". Why?

OR use

https://cors-anywhere.herokuapp.com/

Body:
I am trying to make an axios get request, but i am getting corse policy error. I am kinda new to axios, this is what i tried:

useEffect(() => {
    let url =
      'http://18.189.49.66:3000/api/calculate/' +
      props.type +
      '/' +
      height +
      '/' +
      width;

    var config = {
      headers: { 'Access-Control-Allow-Origin': '*' }
    };

    axios.get(url, config).then(_result => {
      console.log('Duomenys: ' + JSON.stringify(_result));
    });

}, [length, width, height]);

In my app.js on node.js express i have these lines:

var cors = require('cors');
app.use(cors());

And here is the error:

Access to XMLHttpRequest at 'http://18.189.49.66:3000/api/calculate/LF/80/200'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:172 GET http://18.189.49.66:3000/api/calculate/LF/80/200 net::ERR_FAILED dispatchXhrRequest
@ xhr.js:172 xhrAdapter
@ xhr.js:11 dispatchRequest
@ dispatchRequest.js:59 Promise.then (async) request
@ Axios.js:53 Axios.<computed>
@ Axios.js:68 wrap
@ bind.js:9 (anonymous)
@ Calculator.js:113 commitHookEffectList
@ react-dom.development.js:22030 commitPassiveHookEffects
@ react-dom.development.js:22064 callCallback
@ react-dom.development.js:336 invokeGuardedCallbackDev
@ react-dom.development.js:385 invokeGuardedCallback
@ react-dom.development.js:440 flushPassiveEffectsImpl
@ react-dom.development.js:25392 unstable_runWithPriority
@ scheduler.development.js:697 runWithPriority$2
@ react-dom.development.js:12149 flushPassiveEffects
@ react-dom.development.js:25361 flushDiscreteUpdates
@ react-dom.development.js:24359 finishEventHandler
@ react-dom.development.js:1384 batchedEventUpdates
@ react-dom.development.js:1418 dispatchEventForPluginEventSystem
@ react-dom.development.js:5894 attemptToDispatchEvent
@ react-dom.development.js:6010 dispatchEvent
@ react-dom.development.js:5914 ListPicker._handleMouseUp createError.js:16

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)

My backend:

...
    var cors = require('cors');
    ...

app.use(cors());

...

How should i edit my request?


问:
It possible to add to wix site Google AdMob app-add.text file?
I need to upload the new AdMob demand for iOS app,
is its possible to upload tex file to free wix site ?</p>

答:
I solved this with GitHub pages and upload the app-add.text.

https://pages.github.com


问:
How to limit content block in octobercms
I have a content block {% content 'filename.htm' %} that I display on different pages of the website, however in some parts I want to display only a limited part of the content block.

How do I limit the content block? Is there a way to use str_words() or html_limit() with it {% content 'filename.htm' %}

答:
Assign the results of the content block to a variable and then use an appropriate filter / function.

```<code>{% set content %}
    {% content 'filename.htm' %}
{% endset %}

{{ html_limit(content, 100) }}
</code>```

See also https://octobercms.com/docs/markup/function-html

Body:
Assign the results of the content block to a variable and then use an appropriate filter / function.

{% set content %}
    {% content 'filename.htm' %}
{% endset %}

{{ html_limit(content, 100) }}

See also https://octobercms.com/docs/markup/function-html


答:
I think what you're asking is how to how to fit a polynomial regression line to your data while still using the ggpubr functions to annotate it.

This is possible, but it seems that the in-built regression line can only be either a straight line or a loess model, neither of which is appropriate. However, you can fit a polynomial curve and get the equation and adjusted R-squared on the plot using the method below. In your case I have used a cubic formula, but you should choose your polynomial based on a known model or whatever makes most sense based on what you already know about the relationship between your variables.

You can use ggplot to add the actual line as suggested by @Roland, as long as this uses the same formula as the one you supply to stat_regline_equation

ggscatter(dftest, x = "percent_power", y = "PETCO2") +
  stat_regline_equation(label.x = 20, label.y = 0.5,
                        formula = y ~ poly(x, 3),
                        aes(label =  paste(..eq.label.., ..adj.rr.label.., sep = "~~~~")),) +
  geom_smooth(method = "lm", formula = y ~ poly(x, 3)) +
  xlab("Percentage of power (%)") +
  ylab(expression(paste("PETC", O[2]," (mmHg)")))
```

Which gives this result:

Title: How to perform a polynomial equation and curve?

Body:
I have this dataframe:

            id power     hr    fr    VE     VO2    VCO2  PETCO2 percent_VO2 percent_power
1  BM06-PRD-S1    25 119.25 18.25 19.00 0.61675 0.58225 37.6425    48.87084      25.00000
2  BM06-PRD-S1    40 126.00 18.00 20.75 0.71700 0.65950 39.2175    56.81458      40.00000
3  BM06-PRD-S1    55 133.50 20.75 25.00 0.86275 0.82750 41.2150    68.36371      55.00000
4  BM06-PRD-S1    70 147.25 18.25 29.00 0.98575 1.04550 41.7050    78.11014      70.00000
5  BM06-PRD-S1    85 158.50 22.25 39.25 1.13000 1.30525 41.1425    89.54041      85.00000
6  BM06-PRD-S1   100 168.75 27.75 51.00 1.26200 1.61150 38.8925   100.00000     100.00000
7  CB19-PRD-S1    25  98.75 18.50 25.00 0.88350 0.80475 40.7550    36.15715      13.15789
8  CB19-PRD-S1    40  98.25 20.00 25.50 0.94575 0.82900 41.4675    38.70473      21.05263
9  CB19-PRD-S1    55 102.00 19.75 28.50 1.08125 0.95800 42.2775    44.25005      28.94737
10 CB19-PRD-S1    70 107.50 20.50 34.25 1.24400 1.14275 42.6450    50.91058      36.84211
11 CB19-PRD-S1    85 111.00 21.25 35.50 1.30475 1.19925 43.3600    53.39677      44.73684
12 CB19-PRD-S1   100 117.25 21.50 40.25 1.47350 1.42225 44.2650    60.30284      52.63158
13 CB19-PRD-S1   115 123.00 22.75 47.00 1.67900 1.68475 44.6400    68.71291      60.52632
14 CB19-PRD-S1   130 129.50 24.50 52.50 1.79075 1.87950 44.3425    73.28627      68.42105
15 CB19-PRD-S1   145 135.50 25.25 59.50 1.96000 2.13525 44.7300    80.21281      76.31579
16 CB19-PRD-S1   160 145.25 26.75 64.50 2.04050 2.28350 43.8825    83.50726      84.21053
17 CB19-PRD-S1   175 151.25 30.50 83.00 2.34425 2.76050 41.6025    95.93820      92.10526
18 CB19-PRD-S1   190 161.75 33.75 92.25 2.44350 2.96850 40.0400   100.00000     100.00000
19 CC14-PRD-S1    20 102.50 19.00 18.25 0.59250 0.54825 37.7175    49.26211      22.22222
20 CC14-PRD-S1    30 110.25 18.75 19.75 0.66100 0.60325 38.5800    54.95739      33.33333
21 CC14-PRD-S1    40 113.25 18.50 20.75 0.74350 0.66025 39.2950    61.81667      44.44444
22 CC14-PRD-S1    50 122.50 20.00 23.50 0.87875 0.77325 40.5650    73.06173      55.55556
23 CC14-PRD-S1    60 126.25 17.50 26.25 0.94350 0.89375 41.3525    78.44523      66.66667
24 CC14-PRD-S1    70 132.00 16.50 28.00 0.99675 0.98525 42.7575    82.87258      77.77778
25 CC14-PRD-S1    80 145.00 18.50 32.75 1.11425 1.16275 42.5025    92.64186      88.88889
26 CC14-PRD-S1    90 153.50 19.50 37.25 1.20275 1.32700 42.0975   100.00000     100.00000
27 DA24-PRD-S1    25  88.00 18.50 15.75 0.53500 0.45075 37.2200    40.33170      21.73913
28 DA24-PRD-S1    40  93.25 18.50 16.25 0.58450 0.47775 38.3375    44.06332      34.78261
29 DA24-PRD-S1    55 103.75 19.00 20.25 0.76875 0.65450 40.1875    57.95326      47.82609
30 DA24-PRD-S1    70 119.00 20.75 28.00 0.98200 0.95525 41.5175    74.02940      60.86957
31 DA24-PRD-S1    85 133.25 22.75 34.75 1.09975 1.18325 41.4125    82.90614      73.91304
32 DA24-PRD-S1   100 145.00 27.50 45.75 1.25900 1.49700 39.1475    94.91142      86.95652
33 DA24-PRD-S1   115 155.25 36.50 64.75 1.32650 1.72500 33.0275   100.00000     100.00000

I am running a plot using ggplot and ggscatter:

ggplot(dftest, aes(percent_power, PETCO2)) +
  geom_point()

ggscatter(dftest, x = "percent_power", y = "PETCO2", add = "reg.line") +
  stat_cor(label.x = 20, label.y = 3.8) +
  stat_regline_equation(label.x = 20, label.y = 0.5) +
  xlab("Percentage of power (%)") +
  geom_smooth(method = "lm", colour = "red") +
  ylab(expression(paste("PETC", O[2]," (mmHg)")))

I would like to perform a polynomial equation and curve because I am just able to run a linear regression.

Thank you!

Body:
I think what you're asking is how to how to fit a polynomial regression line to your data while still using the ggpubr functions to annotate it.

This is possible, but it seems that the in-built regression line can only be either a straight line or a loess model, neither of which is appropriate. However, you can fit a polynomial curve and get the equation and adjusted R-squared on the plot using the method below. In your case I have used a cubic formula, but you should choose your polynomial based on a known model or whatever makes most sense based on what you already know about the relationship between your variables.

You can use ggplot to add the actual line as suggested by @Roland, as long as this uses the same formula as the one you supply to stat_regline_equation

ggscatter(dftest, x = "percent_power", y = "PETCO2") +
  stat_regline_equation(label.x = 20, label.y = 0.5,
                        formula = y ~ poly(x, 3),
                        aes(label =  paste(..eq.label.., ..adj.rr.label.., sep = "~~~~")),) +
  geom_smooth(method = "lm", formula = y ~ poly(x, 3)) +
  xlab("Percentage of power (%)") +
  ylab(expression(paste("PETC", O[2]," (mmHg)")))

Which gives this result:


问:
PL/SQL select from a table between 2 dates using variables
I am trying to select from a table using in the where clause 2 vaiables to filter records between date ranges; the two variables have the following values:

```<code>START DATE: 31-MAR-2019 00:00:00 and END DATE: 17-FEB-2020 05:00:00
</code>```

however, if I use the variables in the where clause as

```<code>value_dtime BETWEEN TO_DATE(Start_Date) AND TO_DATE(End_Date);
</code>```

I get a wrong dataset, whereas if I change the where clause as follow

```<code>value_dtime BETWEEN TO_DATE('31-MAR-2019 00:00:00') AND TO_DATE('17-FEB-2020 05:00:00');
</code>```

I get the correct dataset; below the query i am using.

```<code>DECLARE
Start_Date VARCHAR(20):='31-MAR-2019 00:00:00';
End_Date VARCHAR(20):= TO_CHAR(sysdate,'DD-MON-YYYY') || ' 05:00:00' ;

BEGIN

DBMS_OUTPUT.PUT_LINE('START DATE: ' || Start_Date || ' and END DATE: ' || End_Date);

delete from inputs;

INSERT INTO inputs(dataset_id,asset_id,asset_name,value_numeric,added_by,value_date)
SELECT
   1,                   --value from LOOK_DATASETS table
  v.meas_ass_id ,
   a.meas_id ,
  v.numeric_value ,
   v.mod_user,
   v.value_dtime

FROM
   halo.t_meas_value@LNKHALO v
    JOIN halo.t_meas_ass@LNKHALO a ON a.ass_id = v.meas_ass_id
   WHERE
     value_dtime BETWEEN TO_DATE(Start_Date) AND TO_DATE(End_Date);
END:
</code>```

can someone please tell me how to get my correct dataset using the 2 variables and not hard coded date strings?

I am using an oracle 12C databae and SQL developer 19 as IDE

答:
If VALUE_DTIME column is DATE datatpye, then you should work with dates, not with strings (i.e. varchar2 values). I'd suggest you to do it as follows:

use date literal is always in DATE 'YYYY-MM-DD' format

truncating sysdate sets date to today's midnight; adding 5/24 adds 5 hours so it is "today at 05:00 in the morning"

where clause is then WHERE value_dtime BETWEEN l_start_date AND l_end_date

it is usually a good idea to use prefix for locally declared variables, such as l_ or v_ because it more than often happens that people use the same name for columns and variables (or parameters) which causes confusion and errors

If VALUE_DTIME is a string, then you'll hit another problems if values stored within aren't uniform and/or have valid date format.

OK, here you go:

```<code>DECLARE
   l_start_date  DATE := DATE '2019-03-31';
   l_end_date    DATE := TRUNC (SYSDATE) + 5 / 24;
BEGIN
   DBMS_OUTPUT.put_line (
      'START DATE: ' || start_date || ' and END DATE: ' || end_date);

   DELETE FROM inputs;

   INSERT INTO inputs (dataset_id,
                       asset_id,
                       asset_name,
                       value_numeric,
                       added_by,
                       value_date)
      SELECT 1,                               --value from LOOK_DATASETS table
             v.meas_ass_id,
             a.meas_id,
             v.numeric_value,
             v.mod_user,
             v.value_dtime
        FROM halo.t_meas_value@lnkhalo v
             JOIN halo.t_meas_ass@lnkhalo a ON a.ass_id = v.meas_ass_id
       WHERE value_dtime BETWEEN l_start_date AND l_end_date;
END;
</code>```

Body:
I am trying to select from a table using in the where clause 2 vaiables to filter records between date ranges; the two variables have the following values:

START DATE: 31-MAR-2019 00:00:00 and END DATE: 17-FEB-2020 05:00:00

however, if I use the variables in the where clause as

value_dtime BETWEEN TO_DATE(Start_Date) AND TO_DATE(End_Date);

I get a wrong dataset, whereas if I change the where clause as follow

value_dtime BETWEEN TO_DATE('31-MAR-2019 00:00:00') AND TO_DATE('17-FEB-2020 05:00:00');

I get the correct dataset; below the query i am using.

DECLARE
Start_Date VARCHAR(20):='31-MAR-2019 00:00:00';
End_Date VARCHAR(20):= TO_CHAR(sysdate,'DD-MON-YYYY') || ' 05:00:00' ;

BEGIN

DBMS_OUTPUT.PUT_LINE('START DATE: ' || Start_Date || ' and END DATE: ' || End_Date);

delete from inputs;

INSERT INTO inputs(dataset_id,asset_id,asset_name,value_numeric,added_by,value_date)
SELECT
   1,                   --value from LOOK_DATASETS table
  v.meas_ass_id ,
   a.meas_id ,
  v.numeric_value ,
   v.mod_user,
   v.value_dtime

FROM
   halo.t_meas_value@LNKHALO v
    JOIN halo.t_meas_ass@LNKHALO a ON a.ass_id = v.meas_ass_id
   WHERE
     value_dtime BETWEEN TO_DATE(Start_Date) AND TO_DATE(End_Date);
END:

can someone please tell me how to get my correct dataset using the 2 variables and not hard coded date strings?

I am using an oracle 12C databae and SQL developer 19 as IDE

Body:
If VALUE_DTIME column is DATE datatpye, then you should work with dates, not with strings (i.e. varchar2 values). I'd suggest you to do it as follows:

use date literal is always in DATE 'YYYY-MM-DD' format

truncating sysdate sets date to today's midnight; adding 5/24 adds 5 hours so it is "today at 05:00 in the morning"

where clause is then WHERE value_dtime BETWEEN l_start_date AND l_end_date

it is usually a good idea to use prefix for locally declared variables, such as l_ or v_ because it more than often happens that people use the same name for columns and variables (or parameters) which causes confusion and errors

If VALUE_DTIME is a string, then you'll hit another problems if values stored within aren't uniform and/or have valid date format.

OK, here you go:

DECLARE
   l_start_date  DATE := DATE '2019-03-31';
   l_end_date    DATE := TRUNC (SYSDATE) + 5 / 24;
BEGIN
   DBMS_OUTPUT.put_line (
      'START DATE: ' || start_date || ' and END DATE: ' || end_date);

   DELETE FROM inputs;

   INSERT INTO inputs (dataset_id,
                       asset_id,
                       asset_name,
                       value_numeric,
                       added_by,
                       value_date)
      SELECT 1,                               --value from LOOK_DATASETS table
             v.meas_ass_id,
             a.meas_id,
             v.numeric_value,
             v.mod_user,
             v.value_dtime
        FROM halo.t_meas_value@lnkhalo v
             JOIN halo.t_meas_ass@lnkhalo a ON a.ass_id = v.meas_ass_id
       WHERE value_dtime BETWEEN l_start_date AND l_end_date;
END;