问:
ORB/BFMatcher - why norm_hamming distance?
I'm using the OpenCV implementation of ORB along with the BFMatcher. The OpenCV states that NORM_HAMMING should be used with ORB.

Why is this? What advantages does norm_hamming offer over other methods such as euclidean distance, norm_l1, etc.

答:
When comparing descriptors in computer vision, the Euclidian distance is usually understood as the square root of the sum of the squared differences between the two vectors' elements.

The ORB descriptors are vectors of binary values. If applying Euclidian distance to binary vectors, the squared result of a single comparison would always be 1 or 0, which is not informative when it comes to estimating the difference between the elements. The overall Euclidian distance would be the square root of the sum of those ones and zeroes, again not a good estimator of the difference between the vectors.

That's why the Hamming distance is used. Here the distance is the number of elements that are not the same. As noted by Catree, you can calculate it by a simple boolean operation on the vectors, as shown in the figure below. Here D1 is a single 4-bit descriptor that we are comparing with 4 descriptors shown in D2. Matrix H is the hamming distances for each row.


来源: stackexchange

问:
%PARSER_ERROR[wex] in spring boot logging
I am getting the following error string occasionally in my log file.  I am running a spring cloud application using spring boot. I use a log back configuration file that includes another config file.
The spring boot version is v1.2.3 (Spring cloud 1.0.1).

%PARSER_ERROR[wex]2015-06-01 12:30:22.180 DEBUG 6833 --- [http-nio-9000-exec-1] ... rest of log message

I saw this entry (Spring Boot - logback PARSER_ERROR), but ti does not seem applicable.

The logback.xml file is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOG_FILE" value="logs/myservice.log"/>

    <!-- the rollover settings with mean a max size per log of 100Mb and 7 days -->
    <property name="MAX_HISTORY" value="7"/>
    <property name="MAX_FILE_SIZE" value="100MB"/>

    <!-- the specific loggers -->
    <logger name="com.companyx" level="DEBUG"/>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="org.springframework.security.oauth2" level="INFO"/>
    <logger name="org.springframework.integration" level="OFF"/>
    <logger name="org.springframework.oxm" level="OFF"/>
    <logger name="org.springframework.http" level="ERROR"/>

    <logger name="com.netflix.discovery" level="OFF"/>
    <logger name="com.netflix.eureka.util.AwsAsgUtil" level="OFF"/>

    <logger name="com.mangofactory.swagger.scanners" level="OFF"/>

    <include resource="com/companyx/services/common/logging/baselog.xml"/>

</configuration>
</code>```

The included baselog.xml file is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<included>

    <!-- turn on JMX configuration -->
    <jmxConfigurator />

    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
    <conversionRule conversionWord="wex"
                    converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>

    <property name="CONSOLE_LOG_PATTERN"
              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS, Zulu}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex"/>
    <property name="FILE_LOG_PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS, Zulu} %5p ${PID:- } --- [%t] %-40.40logger{39} : %m%n%wex"/>

    <appender name="DEBUG_LEVEL_REMAPPER" class="org.springframework.boot.logging.logback.LevelRemappingAppender">
        <destinationLogger>org.springframework.boot</destinationLogger>
    </appender>

    <logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/>
    <logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/>
    <logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/>
    <logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/>
    <logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/>
    <logger name="org.crsh.plugin" level="WARN"/>
    <logger name="org.crsh.ssh" level="WARN"/>
    <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/>
    <logger name="org.hibernate.validator.internal.util.Version" level="WARN"/>
    <logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="WARN"/>
    <logger name="org.springframework.boot.actuate.endpoint.jmx" additivity="false">
        <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
    </logger>
    <logger name="org.thymeleaf" additivity="false">
        <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
    </logger>

    <!-- declare the different appenders -->

    <!-- declare the appender that writes to the console -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <!-- declare the appender that writes to the log file -->
    <appender name="FILE"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.log.gz</fileNamePattern>
            <!-- keep 30 days' worth of history -->
            <maxHistory>${MAX_HISTORY}</maxHistory>
        </rollingPolicy>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>${MAX_HISTORY}</maxHistory>
        </rollingPolicy>

    </appender>

    <!-- default logging levels, unless we overwrite then use INFO-->
    <root>
        <level value="INFO"/>
        <appender-ref ref="FILE"/>
        <appender-ref ref="CONSOLE"/>
    </root>

    <!-- application overrides will be added in files that include this one -->

</included>
</code>```

答:
Please include the default.xml provided by Spring in your Logback.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
</code>```

If you have a look at org/springframework/boot/logging/logback/defaults.xml line 9 you'll see that wex is a custom conversionRule defined by Spring Boot, using a Spring Boot class, so it won't work without that conversionRule being defined in your logback.xml and that class on your classpath.

Anyone not on Spring Boot can use one of the out of the box exception conversion rules like %ex: https://logback.qos.ch/manual/layouts.html#conversionWord

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following error string occasionally in my log file.  I am running a spring cloud application using spring boot. I use a log back configuration file that includes another config file.
The spring boot version is v1.2.3 (Spring cloud 1.0.1).

%PARSER_ERROR[wex]2015-06-01 12:30:22.180 DEBUG 6833 --- [http-nio-9000-exec-1] ... rest of log message

I saw this entry (Spring Boot - logback PARSER_ERROR), but ti does not seem applicable.

The logback.xml file is:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <property name="LOG_FILE" value="logs/myservice.log"/>

    <property name="MAX_HISTORY" value="7"/>
    <property name="MAX_FILE_SIZE" value="100MB"/>

    <logger name="com.companyx" level="DEBUG"/>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="org.springframework.security.oauth2" level="INFO"/>
    <logger name="org.springframework.integration" level="OFF"/>
    <logger name="org.springframework.oxm" level="OFF"/>
    <logger name="org.springframework.http" level="ERROR"/>

    <logger name="com.netflix.discovery" level="OFF"/>
    <logger name="com.netflix.eureka.util.AwsAsgUtil" level="OFF"/>

    <logger name="com.mangofactory.swagger.scanners" level="OFF"/>

    <include resource="com/companyx/services/common/logging/baselog.xml"/>

</configuration>

The included baselog.xml file is:

<?xml version="1.0" encoding="UTF-8"?>
<included>

    <jmxConfigurator />

    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
    <conversionRule conversionWord="wex"
                    converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>

    <property name="CONSOLE_LOG_PATTERN"
              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS, Zulu}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex"/>
    <property name="FILE_LOG_PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS, Zulu} %5p ${PID:- } --- [%t] %-40.40logger{39} : %m%n%wex"/>

    <appender name="DEBUG_LEVEL_REMAPPER" class="org.springframework.boot.logging.logback.LevelRemappingAppender">
        <destinationLogger>org.springframework.boot</destinationLogger>
    </appender>

    <logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/>
    <logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/>
    <logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/>
    <logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/>
    <logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/>
    <logger name="org.crsh.plugin" level="WARN"/>
    <logger name="org.crsh.ssh" level="WARN"/>
    <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/>
    <logger name="org.hibernate.validator.internal.util.Version" level="WARN"/>
    <logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="WARN"/>
    <logger name="org.springframework.boot.actuate.endpoint.jmx" additivity="false">
        <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
    </logger>
    <logger name="org.thymeleaf" additivity="false">
        <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
    </logger>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <appender name="FILE"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.log.gz</fileNamePattern>

            <maxHistory>${MAX_HISTORY}</maxHistory>
        </rollingPolicy>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${MAX_FILE_SIZE}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>${MAX_HISTORY}</maxHistory>
        </rollingPolicy>

    </appender>

    <root>
        <level value="INFO"/>
        <appender-ref ref="FILE"/>
        <appender-ref ref="CONSOLE"/>
    </root>

</included>

Body:
Please include the default.xml provided by Spring in your Logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />

If you have a look at org/springframework/boot/logging/logback/defaults.xml line 9 you'll see that wex is a custom conversionRule defined by Spring Boot, using a Spring Boot class, so it won't work without that conversionRule being defined in your logback.xml and that class on your classpath.

Anyone not on Spring Boot can use one of the out of the box exception conversion rules like %ex: https://logback.qos.ch/manual/layouts.html#conversionWord

ContentLicense: CC BY-SA 4.0


问:
Visualize any size of image without distortions flutter
I hope the title is clear.
I need to visualize an image as background picture but it's dynamic, the user can change it when he/she wants.

The problem is that I would like to fit it in some box (Container, SizedBox....) without distorsions, compressions...The picture must be clear and good to look.

Do you know how I can do this?

I tried with :

```<code>SizedBox(
      width : _screenWidth,
      height: _customLabelsHeight,
      child : SizedBox.expand(
        child : ClipRRect (
          borderRadius: BorderRadius.circular(20.0),
          child : _backGroundPicture==null
            ? new Image.asset('assets/images/io.png'
             )
             : _backGroundPicture,
        ),
      ),
    ),
</code>```

But this isn't what I'm looking for because some pictures are cut, bigger, smaller...The size changes and sometimes pictures are weird...

"_backGroundPicture" comes from "ImagePicker" :

```<code>var _backGroundPicture;

Future changeBackgroundPicture() async {
      var newImage2 = await ImagePicker.pickImage(source:
      ImageSource.gallery);

      setState(() {
        _backGroundPicture=newImage2;
      });
  }
</code>```

Update : the line with the error

```<code>image : _backGroundPicture==null
                    ? new AssetImage('assets/images/io.png')
                    : _backGroundPicture,
</code>```

Where _backGroundPicture is :
    var _backGroundPicture;
And all is child of gestureDetector that onTap has :
    GestureDetector(
              onTap : changeBackgroundPicture,
    .
    .
    .
    Future changeBackgroundPicture() async {
     var newImage2 = await ImagePicker.pickImage(source:
     ImageSource.gallery);

```<code> setState(() {
   _backGroundPicture = newImage2;
 });
}
</code>```

答:
Modify your setState((){}) to have

```<code>setState(() {
      _backGroundPicture = Image.file(File(pickedFile.path));
    });
</code>```

Body:
I hope the title is clear.
I need to visualize an image as background picture but it's dynamic, the user can change it when he/she wants.

The problem is that I would like to fit it in some box (Container, SizedBox....) without distorsions, compressions...The picture must be clear and good to look.

Do you know how I can do this?

I tried with :

SizedBox(
      width : _screenWidth,
      height: _customLabelsHeight,
      child : SizedBox.expand(
        child : ClipRRect (
          borderRadius: BorderRadius.circular(20.0),
          child : _backGroundPicture==null
            ? new Image.asset('assets/images/io.png'
             )
             : _backGroundPicture,
        ),
      ),
    ),

But this isn't what I'm looking for because some pictures are cut, bigger, smaller...The size changes and sometimes pictures are weird...

"_backGroundPicture" comes from "ImagePicker" :

var _backGroundPicture;

Future changeBackgroundPicture() async {
      var newImage2 = await ImagePicker.pickImage(source:
      ImageSource.gallery);

      setState(() {
        _backGroundPicture=newImage2;
      });
  }

Update : the line with the error

image : _backGroundPicture==null
                    ? new AssetImage('assets/images/io.png')
                    : _backGroundPicture,

Where _backGroundPicture is :
    var _backGroundPicture;
And all is child of gestureDetector that onTap has :
    GestureDetector(
              onTap : changeBackgroundPicture,
    .
    .
    .
    Future changeBackgroundPicture() async {
     var newImage2 = await ImagePicker.pickImage(source:
     ImageSource.gallery);

 setState(() {
   _backGroundPicture = newImage2;
 });
}

Body:
Modify your setState((){}) to have

setState(() {
      _backGroundPicture = Image.file(File(pickedFile.path));
    });


问:
PWA stored in Azure - The script has an unsupported MIME type ('text/plain')
I'm building my first custom service-worker.js and I encountered this error.

I'm using Vue + PWA (workbox)
registerServiceWorker.js :

```<code>import { register } from "register-service-worker";

if (process.env.NODE_ENV === "production") {
  console.log("service worker won't be registerd for now");
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready() {
      console.log("App is being served from cache by a service worker.");
    },
    registered() {
      console.log("Service worker has been registered.");
    },
    cached() {
      console.log("Content has been cached for offline use.");
    },
    updatefound() {
      console.log("New content is downloading.");
    },
    updated() {
      console.log("New content is available; please refresh.");
    },
    offline() {
      console.log(
        "No internet connection found. App is running in offline mode."
      );
    },
    error(error) {
      console.error("Error during service worker registration:", error);
    }
  });
}
</code>```

service-worker.js :

```<code>console.log("Hello from service-worker.js");
</code>```

答:
In order to get rid of this error I just changed the Content Type of the service-worker.js file (using Microsoft Azure Storage Explorer -> right click -> properties -> ContentType)

PS: let me know if you know how to automate this.

Body:
I'm building my first custom service-worker.js and I encountered this error.

I'm using Vue + PWA (workbox)
registerServiceWorker.js :

import { register } from "register-service-worker";

if (process.env.NODE_ENV === "production") {
  console.log("service worker won't be registerd for now");
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready() {
      console.log("App is being served from cache by a service worker.");
    },
    registered() {
      console.log("Service worker has been registered.");
    },
    cached() {
      console.log("Content has been cached for offline use.");
    },
    updatefound() {
      console.log("New content is downloading.");
    },
    updated() {
      console.log("New content is available; please refresh.");
    },
    offline() {
      console.log(
        "No internet connection found. App is running in offline mode."
      );
    },
    error(error) {
      console.error("Error during service worker registration:", error);
    }
  });
}

service-worker.js :

console.log("Hello from service-worker.js");


问:
What do i need to add and where to send the JWT token to the browser header?
I'm a new to backend and I was trying to create an authentication and authorization API. The app is working fine in Postman but I have to manually send the token. I want to send it to the header.

This is my auth.js middleware.

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {

  const token = req.header("token");
  console.log(token)
  if (!token) return res.status(401).json({
    message: "Auth Error"
  });

  try {
    const decoded = jwt.verify(token, "randomString");
    req.user = decoded.user;
    next();
  } catch (e) {
    console.error(e);
    res.status(500).send({
      message: "Invalid Token"
    });
  }
};
```

<p>And this is my authentication index.js file</p>

<pre class="lang-js prettyprint-override"><code>// Filename : user.js

const express = require("express");
const {
  check,
  validationResult
} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const auth = require('../middleware/auth')
const router = express.Router();

const User = require("../model/User");

//Signup
router.get('/signup', (req, res) => {
  res.render("signup.pug")
})

router.post(
  "/signup", [
    check("username", "Please Enter a Valid Username").isLength({
      min: 5
    }),
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 7
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    try {
      let user = await User.findOne({
        email
      });
      if (user) {
        return res.status(400).json({
          msg: "User Already Exists"
        });
      }

      user = new User({
        username,
        email,
        password
      });

      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);

      await user.save();

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 10000
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (err) {
      console.log(err.message);
      res.status(500).send("Error in Saving");
    }
  }
);

//Login

router.get('/login', (req, res) => {
  res.render("login.pug")
})

router.post(
  "/login", [
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 6
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const {
      email,
      password
    } = req.body;
    try {
      let user = await User.findOne({
        email
      });
      if (!user)
        return res.status(400).json({
          message: "User Not Exist"
        });

      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch)
        return res.status(400).json({
          message: "Incorrect Password !"
        });

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 3600
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (e) {
      console.error(e);
      res.status(500).json({
        message: "Server Error"
      });
    }
  }
);

router.get("/me", auth, async(req, res) => {

  try {
    // request.user is getting fetched from Middleware after token authentication
    const user = await User.findById(req.user.id);
    res.json(user);
  } catch (e) {
    res.send({
      message: "Error in Fetching user"
    });
  }
});

module.exports = router;
</code>```

Please also tell where to put in the code. Thanks in advance!!!

答:
The token is supposed to be sent in the body of the login response, not in a header.

```<code>var token = jwt.sign(
  payload,
  "randomString",
  {
    expiresIn: 10000
  },
  (err, token) => {
    if (err) throw err;
    res.status(200).json({
      token
    });
  }
);

// This line should send the token to your client in the body
res.json({ token });
</code>```

Your client receives the response from your backend and saves it locally (either in memory, a cookie or localstorage) and should use it for subsequent requests.

When making an authenticated request from your client, only then you should add the token to your Authorization header.

Body:
I'm a new to backend and I was trying to create an authentication and authorization API. The app is working fine in Postman but I have to manually send the token. I want to send it to the header.

This is my auth.js middleware.

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {

  const token = req.header("token");
  console.log(token)
  if (!token) return res.status(401).json({
    message: "Auth Error"
  });

  try {
    const decoded = jwt.verify(token, "randomString");
    req.user = decoded.user;
    next();
  } catch (e) {
    console.error(e);
    res.status(500).send({
      message: "Invalid Token"
    });
  }
};

And this is my authentication index.js file

// Filename : user.js

const express = require("express");
const {
  check,
  validationResult
} = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const auth = require('../middleware/auth')
const router = express.Router();

const User = require("../model/User");

//Signup
router.get('/signup', (req, res) => {
  res.render("signup.pug")
})

router.post(
  "/signup", [
    check("username", "Please Enter a Valid Username").isLength({
      min: 5
    }),
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 7
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    try {
      let user = await User.findOne({
        email
      });
      if (user) {
        return res.status(400).json({
          msg: "User Already Exists"
        });
      }

      user = new User({
        username,
        email,
        password
      });

      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);

      await user.save();

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 10000
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (err) {
      console.log(err.message);
      res.status(500).send("Error in Saving");
    }
  }
);

//Login

router.get('/login', (req, res) => {
  res.render("login.pug")
})

router.post(
  "/login", [
    check("email", "Please enter a valid email").isEmail(),
    check("password", "Please enter a valid password").isLength({
      min: 6
    })
  ],
  async(req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }

    const {
      email,
      password
    } = req.body;
    try {
      let user = await User.findOne({
        email
      });
      if (!user)
        return res.status(400).json({
          message: "User Not Exist"
        });

      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch)
        return res.status(400).json({
          message: "Incorrect Password !"
        });

      const payload = {
        user: {
          id: user.id
        }
      };

      jwt.sign(
        payload,
        "randomString", {
          expiresIn: 3600
        },
        (err, token) => {
          if (err) throw err;
          res.status(200).json({
            token
          });
        }
      );
    } catch (e) {
      console.error(e);
      res.status(500).json({
        message: "Server Error"
      });
    }
  }
);

router.get("/me", auth, async(req, res) => {

  try {
    // request.user is getting fetched from Middleware after token authentication
    const user = await User.findById(req.user.id);
    res.json(user);
  } catch (e) {
    res.send({
      message: "Error in Fetching user"
    });
  }
});

module.exports = router;

Please also tell where to put in the code. Thanks in advance!!!

Body:
The token is supposed to be sent in the body of the login response, not in a header.

var token = jwt.sign(
  payload,
  "randomString",
  {
    expiresIn: 10000
  },
  (err, token) => {
    if (err) throw err;
    res.status(200).json({
      token
    });
  }
);

// This line should send the token to your client in the body
res.json({ token });

Your client receives the response from your backend and saves it locally (either in memory, a cookie or localstorage) and should use it for subsequent requests.

When making an authenticated request from your client, only then you should add the token to your Authorization header.


问:
Configure gnome-terminal so that right click extends selection rather than displays menu
I've been using Linux for a long time, but have only recently 'upgraded' to a full GUI desktop since using it command-line-only for the last three or four years. I used to use 'aterm' before then (with fluxbox, and other old-school things) but I see now that gnome-terminal is pretty usable in Ubuntu's Gnome.

However, there's one thing that really gets me - when you select something and then right click, it doesn't extend the selection, instead it brings up a pop-up menu.

I've been using terminals and emacs for years and right-click has always extended a selection - so there must be some way to configure gnome-terminal to do this. This is a habit I'm not going to be able to grow out of because I use it all the time in emacs.

Does anyone have the magic recipe to restore the behaviour I'm after please?

Alternatively, what's a good and modern alternative to gnome-terminal?

I'm using Ubuntu 10.04.

答:
Try program called terminator.</p>

```<code>sudo apt-get install terminator
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try program called terminator.

sudo apt-get install terminator


问:
Ambiguous call on overloaded variadic template function
I downloaded a C++ library to support multiple dimension array from github, when I built it using GCC8.2.0, the complier ran into a message saying an overrload function is ambiguous.  Consider following code:

```<code>// basic function, set the length i for the dimension D
template<int Rank,int D>
void set_array(std::array<int,Rank>& A,int i)
{
    A[D] = i;
}

// function with parameter pack, set the length for all dimensions recursively
template<int Rank,int D,typename... indices>
void set_array(std::array<int,Rank>& A,int i,indices... idx)
{
    A[D] = i;
    set_array<Rank,D+1>(A,idx...);
}

// class calls set_array in allocation
template<typename T,int Rank>
class MultiArray
{

private:
    std::array<int,Rank> _dim = {{0}};

    template<typename... indices>
    void allocate(indices... idx) {
        static_assert(sizeof...(idx) == Rank,
                      "NUMBER OF INDICES PASSED TO ALLOCATE DOES NOT MATCH RANK OF ARRAY");
        set_array<Rank,0>(_dim,idx...);
    }
};

// code to create object of above MultiArray class.

MultiArray<int, 1> a;
a.allocate(10)
</code>```

The compiler error message is:
call  of overrloaded "set_array<1,0>(std::array&, int&) is ambiguous,

My understanding is when calling set_array<1, 0>(_dim, 10), the compiler can not know which one should be used because the parameter pack can be empty. I tried some ways to fix but failed. Is there any solution to help me out?  Thank you in advance!

答:
A straightforward way to solve this is to require at least one parameter for the second overload, by unrolling it once</p>

```<code>template<int Rank,int D,typename index0, typename... indices>
</code>```

Body:
I downloaded a C++ library to support multiple dimension array from github, when I built it using GCC8.2.0, the complier ran into a message saying an overrload function is ambiguous.  Consider following code:

// basic function, set the length i for the dimension D
template<int Rank,int D>
void set_array(std::array<int,Rank>& A,int i)
{
    A[D] = i;
}

// function with parameter pack, set the length for all dimensions recursively
template<int Rank,int D,typename... indices>
void set_array(std::array<int,Rank>& A,int i,indices... idx)
{
    A[D] = i;
    set_array<Rank,D+1>(A,idx...);
}

// class calls set_array in allocation
template<typename T,int Rank>
class MultiArray
{

private:
    std::array<int,Rank> _dim = {{0}};

    template<typename... indices>
    void allocate(indices... idx) {
        static_assert(sizeof...(idx) == Rank,
                      "NUMBER OF INDICES PASSED TO ALLOCATE DOES NOT MATCH RANK OF ARRAY");
        set_array<Rank,0>(_dim,idx...);
    }
};

// code to create object of above MultiArray class.

MultiArray<int, 1> a;
a.allocate(10)

The compiler error message is:
call  of overrloaded "set_array<1,0>(std::array&, int&) is ambiguous,

My understanding is when calling set_array<1, 0>(_dim, 10), the compiler can not know which one should be used because the parameter pack can be empty. I tried some ways to fix but failed. Is there any solution to help me out?  Thank you in advance!

Body:
A straightforward way to solve this is to require at least one parameter for the second overload, by unrolling it once

template<int Rank,int D,typename index0, typename... indices>


问:
Mailchimp two embedded forms on one page
I would like to use two mailchimp embedded forms on one page. The second form doesn't work.

This is the first form which works:

```<code><!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
    #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
    /* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
       We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="subscribe_url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll">
    <h2>Subscribe</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
    <label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
</label>
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
    <label for="mce-FNAME">First Name </label>
    <input type="text" value="" name="FNAME" class="" id="mce-FNAME">
</div>
    <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
    </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_511911076469753191feb80b9_8aced62855" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
</code>```

If I add the same form, the previous form works, but this one doesn't.

```<code><!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
    #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
    /* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
       We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="subscribe_url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll">
    <h2>Subscribe</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
    <label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
</label>
    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
    <label for="mce-FNAME">First Name </label>
    <input type="text" value="" name="FNAME" class="" id="mce-FNAME">
</div>
    <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
    </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_511911076469753191feb80b9_8aced62855" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
</code>```

I tried to change input attributes in the second form, but it didn't help:

```<code><!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
    #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
    /* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
       We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="subscribe_url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll">
    <h2>Subscribe</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
    <label for="mce-MAIL">Email Address  <span class="asterisk">*</span>
</label>
    <input type="email" value="" name="MAIL" class="required email" id="mce-MAIL">
</div>
<div class="mc-field-group">
    <label for="mce-NAME">First Name </label>
    <input type="text" value="" name="NAME" class="" id="mce-NAME">
</div>
    <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
    </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_511911076469753191feb80b9_8aced62855" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->
</code>```

I have no idea how to embed two mailchimp forms on one page.

答:
If you check mailchimp troubleshooting page, you can find there:

If you need to have more than one embedded form on a single web page, use one of these solutions.

Disable JavaScript on the Classic form.

Embed your Classic form in an iFrame.

Display your embedded form as an Unstyled, Condensed, or Horizontal
form type.

If you want to use Javascript validations for multiple mailchimp forms, you need to embed one form into iframe tag. It's pretty easy, but you can find more details in this blog post.

You just need to upload html file which contains html embedded code and then add its url as the iframe attribute:

```<code><iframe src="http://your-site.com/mailchimp-form.html" frameborder="0" width="654" height="200">
<a href="http://link-to-form-on-mailchimp-site" target="_blank">Anchor text saying "click here to sign up" or something like that for people whose browsers can't read iframes</a>
</iframe>
</code>```

Body:
I would like to use two mailchimp embedded forms on one page. The second form doesn't work.

This is the first form which works:

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="subscribe_url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe

* indicates required

    Email Address  *

    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

    First Name
    <input type="text" value="" name="FNAME" class="" id="mce-FNAME">

<input type="text" name="b_511911076469753191feb80b9_8aced62855" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

If I add the same form, the previous form works, but this one doesn't.

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="subscribe_url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe

* indicates required

    Email Address  *

    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

    First Name
    <input type="text" value="" name="FNAME" class="" id="mce-FNAME">

<input type="text" name="b_511911076469753191feb80b9_8aced62855" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

I tried to change input attributes in the second form, but it didn't help:

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="subscribe_url" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Subscribe

* indicates required

    Email Address  *

    <input type="email" value="" name="MAIL" class="required email" id="mce-MAIL">

    First Name
    <input type="text" value="" name="NAME" class="" id="mce-NAME">

<input type="text" name="b_511911076469753191feb80b9_8aced62855" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

I have no idea how to embed two mailchimp forms on one page.

Body:
If you check mailchimp troubleshooting page, you can find there:

If you need to have more than one embedded form on a single web page, use one of these solutions.

Disable JavaScript on the Classic form.

Embed your Classic form in an iFrame.

Display your embedded form as an Unstyled, Condensed, or Horizontal
form type.

If you want to use Javascript validations for multiple mailchimp forms, you need to embed one form into iframe tag. It's pretty easy, but you can find more details in this blog post.

You just need to upload html file which contains html embedded code and then add its url as the iframe attribute:

<iframe src="http://your-site.com/mailchimp-form.html" frameborder="0" width="654" height="200">
<a href="http://link-to-form-on-mailchimp-site" target="_blank">Anchor text saying "click here to sign up" or something like that for people whose browsers can't read iframes</a>
</iframe>


问:
CORS error when making Axios calls to Cloudrun service from Firebase hosted app
This looks to be pretty obvious but I've been trying to figure it out for a couple of days now and still can't get it to work. Please, can someone point out what I'm missing.

I'm trying to make an axios call to my cloud run service from my firebase hosted SPA. To isolate the issue I followed the steps outlined in the [firebase tutorial for cloud run] (https://firebase.google.com/docs/hosting/cloud-run#node.js)

Step 4 of the tutorial talks about setting up rewrite to use the firebase domain as a proxy to your cloud run service. It says that the helloworld service would be reachable via

Your Firebase subdomains:
  projectID.web.app/helloworld and projectID.firebaseapp.com/helloworld

So I follow the steps and deploy the service. Then I try to make an axios call to the service from the SPA like below

```<code>testHelloWorld () {
  axios.get(`https://myProjectId.firebaseapp.com/helloworld`)
     .then((data) => {
       console.log(data)
     })
     .catch(ex => {
        console.error(ex)
     })
  })
}
</code>```

But then I get the CORS error

Access to XMLHttpRequest at 'https://myProjectId.firebaseapp.com/helloworld' from origin 'https://myFirabaseApp.firebaseapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This answer states that this should be possible so I'm not sure what I'm doing wrong.

N.B:

While debugging, I updated the node app from the tutorial to add cors support like below. Still didnt work.

```<code>const express = require('express');
const app = express();
const cors = require('cors'); //Imported and added this

app.use(cors()); // Used here

app.get('/', (req, res) => {
  console.log('Hello world received a request.');

  const target = process.env.TARGET || 'World';
  res.send(`Hello ${target}!`);
});

const port = process.env.PORT || 8080;
app.listen(port, () => {
  console.log('Hello world listening on port', port);
});

</code>```

So the question here is, how do I make an Axios/AJAX call to my cloud run service using the firebase rewrite rule?

答:
Please check if you have installed cors: npm install cors.

Please check if the 2 following options can solve your issue:

1= Use the following code :

```<code> app.use(cors({origin:true,credentials: true}));
</code>```

2) If the previous didn't work, please use the following code:

```<code>
app.get('/', (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  console.log('Hello world received a request.');
}
</code>```

Please let me know if it works for you.

Body:
This looks to be pretty obvious but I've been trying to figure it out for a couple of days now and still can't get it to work. Please, can someone point out what I'm missing.

I'm trying to make an axios call to my cloud run service from my firebase hosted SPA. To isolate the issue I followed the steps outlined in the [firebase tutorial for cloud run] (https://firebase.google.com/docs/hosting/cloud-run#node.js)

Step 4 of the tutorial talks about setting up rewrite to use the firebase domain as a proxy to your cloud run service. It says that the helloworld service would be reachable via

Your Firebase subdomains:
  projectID.web.app/helloworld and projectID.firebaseapp.com/helloworld

So I follow the steps and deploy the service. Then I try to make an axios call to the service from the SPA like below

testHelloWorld () {
  axios.get(`https://myProjectId.firebaseapp.com/helloworld`)
     .then((data) => {
       console.log(data)
     })
     .catch(ex => {
        console.error(ex)
     })
  })
}

But then I get the CORS error

Access to XMLHttpRequest at 'https://myProjectId.firebaseapp.com/helloworld' from origin 'https://myFirabaseApp.firebaseapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This answer states that this should be possible so I'm not sure what I'm doing wrong.

N.B:

While debugging, I updated the node app from the tutorial to add cors support like below. Still didnt work.

const express = require('express');
const app = express();
const cors = require('cors'); //Imported and added this

app.use(cors()); // Used here

app.get('/', (req, res) => {
  console.log('Hello world received a request.');

  const target = process.env.TARGET || 'World';
  res.send(`Hello ${target}!`);
});

const port = process.env.PORT || 8080;
app.listen(port, () => {
  console.log('Hello world listening on port', port);
});

So the question here is, how do I make an Axios/AJAX call to my cloud run service using the firebase rewrite rule?

Body:
Please check if you have installed cors: npm install cors.

Please check if the 2 following options can solve your issue:

1= Use the following code :

 app.use(cors({origin:true,credentials: true}));

2) If the previous didn't work, please use the following code:

app.get('/', (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  console.log('Hello world received a request.');
}

Please let me know if it works for you.


问:
Google Calendar API with Service User - Reminder overrides are not set

Problem:

When using the service user auth and inserting / updating a calendar event, the reminders are not overridden

The event is inserted / updated correct APART from the reminders are always at the default (email > 10m, popup > 30m).

Context:

Node.js using standard libraries below

Valid service account with downloaded credentials.json

Service account (service-user-account@myapp.iam.gserviceaccount.com) has write access to myuser@gmail.com calendar

Code:

```<code>const {google} = require('googleapis')
const {auth} = require('google-auth-library')
const credentials = require('./credentials.json')

const addEvent = async (auth) => {
  const calendar = google.calendar({version: 'v3', auth})
  const insertRes = await calendar.events.insert({
    calendarId: 'myuser@gmail.com',
    resource: {
      summary: 'Test API',
      start: {
        dateTime: '2020-06-02T12:55:00.000',
        timeZone: 'Europe/London'
      },
      end: {
        dateTime: '2020-06-02T12:56:00.000',
        timeZone: 'Europe/London'
      },
      reminders: {
        useDefault: false,
        overrides: [
          {method: 'popup', 'minutes': 5}
        ]
      }
    }
  })
  console.log('insertRes', insertRes.data)
}

const getAuth = async () => {
  let client = auth.fromJSON(credentials)
  client.scopes = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.events']
  return client
}
const init = async () => {
  const auth = await getAuth()
  await addEvent(auth)
}
init()
</code>```

Response: from console.log(insertRes)

```<code>{ kind: 'calendar#event',
  etag: '"3182200547452000"',
  id: '6063phndufgppo8rfev1XXXXXX',
  status: 'confirmed',
  htmlLink:
   'https://www.google.com/calendar/event?eid=NjA2M3BobmR1ZmdwcG84cmZldjFjdWh2YzQgZGFuZ2FyZmllbGR1a0Bnb29nbGVtYWlsXXXXXX',
  created: '2020-06-02T12:17:53.000Z',
  updated: '2020-06-02T12:17:53.768Z',
  summary: 'Test API',
  creator:
   { email: 'service-user-account@myapp.iam.gserviceaccount.com' },
  organizer: { email: 'myuser@googlemail.com', self: true },
  start:
   { dateTime: '2020-06-02T12:55:00+01:00',
     timeZone: 'Europe/London' },
  end:
   { dateTime: '2020-06-02T12:56:00+01:00',
     timeZone: 'Europe/London' },
  iCalUID: '6063phndufgppo8rfev1XXXXXX@google.com',
  sequence: 0,
  reminders: { useDefault: false, overrides: [{"method":"popup","minutes":5}] }
}
</code>```

Hopefully someone can shed a light on the issue for me.

Thanks

答:
It seems to be a bug, already reported on Google's Public Issue Tracker

Give it a "star" to show that more people are affected and to receive updates on the issue.

Body:
Problem:

When using the service user auth and inserting / updating a calendar event, the reminders are not overridden

The event is inserted / updated correct APART from the reminders are always at the default (email > 10m, popup > 30m).

Context:

Node.js using standard libraries below

Valid service account with downloaded credentials.json

Service account (service-user-account@myapp.iam.gserviceaccount.com) has write access to myuser@gmail.com calendar

Code:

const {google} = require('googleapis')
const {auth} = require('google-auth-library')
const credentials = require('./credentials.json')

const addEvent = async (auth) => {
  const calendar = google.calendar({version: 'v3', auth})
  const insertRes = await calendar.events.insert({
    calendarId: 'myuser@gmail.com',
    resource: {
      summary: 'Test API',
      start: {
        dateTime: '2020-06-02T12:55:00.000',
        timeZone: 'Europe/London'
      },
      end: {
        dateTime: '2020-06-02T12:56:00.000',
        timeZone: 'Europe/London'
      },
      reminders: {
        useDefault: false,
        overrides: [
          {method: 'popup', 'minutes': 5}
        ]
      }
    }
  })
  console.log('insertRes', insertRes.data)
}

const getAuth = async () => {
  let client = auth.fromJSON(credentials)
  client.scopes = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.events']
  return client
}
const init = async () => {
  const auth = await getAuth()
  await addEvent(auth)
}
init()

Response: from console.log(insertRes)

{ kind: 'calendar#event',
  etag: '"3182200547452000"',
  id: '6063phndufgppo8rfev1XXXXXX',
  status: 'confirmed',
  htmlLink:
   'https://www.google.com/calendar/event?eid=NjA2M3BobmR1ZmdwcG84cmZldjFjdWh2YzQgZGFuZ2FyZmllbGR1a0Bnb29nbGVtYWlsXXXXXX',
  created: '2020-06-02T12:17:53.000Z',
  updated: '2020-06-02T12:17:53.768Z',
  summary: 'Test API',
  creator:
   { email: 'service-user-account@myapp.iam.gserviceaccount.com' },
  organizer: { email: 'myuser@googlemail.com', self: true },
  start:
   { dateTime: '2020-06-02T12:55:00+01:00',
     timeZone: 'Europe/London' },
  end:
   { dateTime: '2020-06-02T12:56:00+01:00',
     timeZone: 'Europe/London' },
  iCalUID: '6063phndufgppo8rfev1XXXXXX@google.com',
  sequence: 0,
  reminders: { useDefault: false, overrides: [{"method":"popup","minutes":5}] }
}

Hopefully someone can shed a light on the issue for me.

Thanks


问:
from C++ to C#
What are good c++ to C# articles/tutorial or books?
I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?</p>

答:
I often find that personal experience provides the most insight into language differences.   One can read all the theory written about a new programming language, but without experience this doesn't help much.

I'd recommend downloading Microsoft Visual C# Express Edition (http://www.microsoft.com/express/vcsharp/) and trying it out with a few simple programs. Start with "Hello World!" and work your way from there. (I know this can be tedious, but it helps to build a solid grounding in a language you are unfamiliar with). Once you have a solid feeling for the language, you should be able to focus your efforts (and questions) toward more specific language differences.

Title: from C++ to C#

OwnerDisplayName: Rob


问:
How to animate both rotation and transformation in Raphaël
I'm trying to do something I thought would be rather simple. I've an object that I move around stepwise, i.e. I receive messages every say 100 milliseconds that tell me "your object has moved x pixels to the right and y pixels down". The code below simulates that by moving that object on a circle, but note that it is not known in advance where the object will be heading in the next step.

Anyway, that is pretty simple. But now I want to also tell the object, which is actually a set of subobjects, that it is being rotated.

Unfortunately, I am having trouble getting Raphaël to do what I want. I believe the reason is that while I can animate both translation and rotation independently, I have to set the center of the rotation when it starts. Obviously the center of the rotation changes as the object is moving.

Here's the code I'm using and you can view a live demo here. As you can see, the square rotates as expected, but the arrow rotates incorrectly.

```<code>// c&p this into http://raphaeljs.com/playground.html

var WORLD_SIZE = 400,
    rect = paper.rect(WORLD_SIZE / 2 - 20, 0, 40, 40, 5).attr({ fill: 'red' }),
    pointer = paper.path("M 200 20 L 200 50"),
    debug = paper.text(25, 10, ""),
    obj = paper.set();

obj.push(rect, pointer);

var t = 0,
    step = 0.05;

setInterval(function () {
    var deg = Math.round(Raphael.deg(t));

    t += step;

    debug.attr({ text: deg + '°' });

    var dx = ((WORLD_SIZE - 40) / 2) * (Math.sin(t - step) - Math.sin(t)),
        dy = ((WORLD_SIZE - 40) / 2) * (Math.cos(t - step) - Math.cos(t));

    obj.animate({
        translation: dx + ' ' + dy,
        rotation: -deg
    }, 100);
}, 100);
</code>```

Any help is appreciated!

答:
Check out http://raphaeljs.com/animation.html

Look at the second animation from the top on the right.

Hope this helps!

Here's the code:

```<code>(function () {
    var path1 = "M170,90c0-20 40,20 40,0c0-20 -40,20 -40,0z",
        path2 = "M270,90c0-20 40,20 40,0c0-20 -40,20 -40,0z";
    var t = r.path(path1).attr(dashed);
    r.path(path2).attr({fill: "none", stroke: "#666", "stroke-dasharray": "- ", rotation: 90});
    var el = r.path(path1).attr({fill: "none", stroke: "#fff", "stroke-width": 2}),
        elattrs = [{translation: "100 0", rotation: 90}, {translation: "-100 0", rotation: 0}],
        now = 0;
    r.arrow(240, 90).node.onclick = function () {
        el.animate(elattrs[now++], 1000);
        if (now == 2) {
            now = 0;
        }
};                })();
</code>```

Body:
I'm trying to do something I thought would be rather simple. I've an object that I move around stepwise, i.e. I receive messages every say 100 milliseconds that tell me "your object has moved x pixels to the right and y pixels down". The code below simulates that by moving that object on a circle, but note that it is not known in advance where the object will be heading in the next step.

Anyway, that is pretty simple. But now I want to also tell the object, which is actually a set of subobjects, that it is being rotated.

Unfortunately, I am having trouble getting Raphaël to do what I want. I believe the reason is that while I can animate both translation and rotation independently, I have to set the center of the rotation when it starts. Obviously the center of the rotation changes as the object is moving.

Here's the code I'm using and you can view a live demo here. As you can see, the square rotates as expected, but the arrow rotates incorrectly.

// c&p this into http://raphaeljs.com/playground.html

var WORLD_SIZE = 400,
    rect = paper.rect(WORLD_SIZE / 2 - 20, 0, 40, 40, 5).attr({ fill: 'red' }),
    pointer = paper.path("M 200 20 L 200 50"),
    debug = paper.text(25, 10, ""),
    obj = paper.set();

obj.push(rect, pointer);

var t = 0,
    step = 0.05;

setInterval(function () {
    var deg = Math.round(Raphael.deg(t));

    t += step;

    debug.attr({ text: deg + '°' });

    var dx = ((WORLD_SIZE - 40) / 2) * (Math.sin(t - step) - Math.sin(t)),
        dy = ((WORLD_SIZE - 40) / 2) * (Math.cos(t - step) - Math.cos(t));

    obj.animate({
        translation: dx + ' ' + dy,
        rotation: -deg
    }, 100);
}, 100);

Any help is appreciated!

Body:
Check out http://raphaeljs.com/animation.html

Look at the second animation from the top on the right.

Hope this helps!

Here's the code:

(function () {
    var path1 = "M170,90c0-20 40,20 40,0c0-20 -40,20 -40,0z",
        path2 = "M270,90c0-20 40,20 40,0c0-20 -40,20 -40,0z";
    var t = r.path(path1).attr(dashed);
    r.path(path2).attr({fill: "none", stroke: "#666", "stroke-dasharray": "- ", rotation: 90});
    var el = r.path(path1).attr({fill: "none", stroke: "#fff", "stroke-width": 2}),
        elattrs = [{translation: "100 0", rotation: 90}, {translation: "-100 0", rotation: 0}],
        now = 0;
    r.arrow(240, 90).node.onclick = function () {
        el.animate(elattrs[now++], 1000);
        if (now == 2) {
            now = 0;
        }
};                })();


问:
How can I calculate the area of a circle which I detected with cv2.HoughCircles()?
guys,

I have written a program where I recognize circles with cv2.HoughCircles(). The code works too. Unfortunately I need the area of the circles for my project. But I don't know how to calculate this and my search on the internet was unsuccessful.

Thank you.

答:
Thank you guys,

@Tin Nguyen

if i use:

```<code>for i in circles[0,:]:
area = 3.14159 * i[2] * i[2]
</code>```

then i get the following error: "TypeError: 'NoneType' object is not subscriptable"
This is my code, i want to detect circles in realtime and calculate the area.

```<code>import pypylon.pylon as py  # wrapper to control Basler camera with python
import cv2  # openCV
import numpy as np

first_device = py.TlFactory.GetInstance().CreateFirstDevice()
icam = py.InstantCamera(first_device)
icam.Open()
# set parameters
icam.PixelFormat = "RGB8"
# if only a part of image sensor is used an offset is required or centering
'''icam.Width = 640
icam.Height = 480
icam.CenterX = False
icam.CenterY = False'''
# Demonstration of setting parameters - properties can be found on Pylon Viewer
# Auto property values are 'Off', 'Once', 'Continuous'
icam.GainAuto = 'Off'
icam.ExposureAuto = 'Continuous'
icam.BalanceWhiteAuto = 'Off'
icam.Gain = 0  # minimum gain value
# icam.ExposureTime       = 50000 # exposure time or use ExposureAuto
icam.StartGrabbing(py.GrabStrategy_LatestImages)
while True:
   res = icam.RetrieveResult(1000)  # 1000 = time constant for time-out
   frame = cv2.cvtColor(res.Array, cv2.COLOR_RGB2BGR)

   output = frame.copy()
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

   gray = cv2.GaussianBlur(gray,(5,5),0)
   gray = cv2.medianBlur(gray, 5)

   gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                             cv2.THRESH_BINARY,11,3.5)

   kernel = np.ones((2,3),np.uint8)
   gray = cv2.erode(gray,kernel)

   gray = cv2.dilate(gray, kernel)

   # detect circles in the image
   circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 200, param1=30, param2=45,
                       minRadius=0, maxRadius=0)
# print circles

# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")

    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle in the image
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
        # time.sleep(0.5)
        print
        "Column Number: "
        print
        x
        print
        "Row Number: "
        print
        y
        print
        "Radius is: "
        print
        r

        # Display the resulting frame
        cv2.imshow('gray', gray)
cv2.imshow('frame', output)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

for i in circles[0, :]:
    area = 3.14159 * i[2] * i[2]
    print(area)

icam.StopGrabbing()
icam.Close()
cv2.destroyAllWindows()
</code>```

Body:
Thank you guys,

@Tin Nguyen

if i use:

for i in circles[0,:]:
area = 3.14159 * i[2] * i[2]

then i get the following error: "TypeError: 'NoneType' object is not subscriptable"
This is my code, i want to detect circles in realtime and calculate the area.

import pypylon.pylon as py  # wrapper to control Basler camera with python
import cv2  # openCV
import numpy as np

first_device = py.TlFactory.GetInstance().CreateFirstDevice()
icam = py.InstantCamera(first_device)
icam.Open()
# set parameters
icam.PixelFormat = "RGB8"
# if only a part of image sensor is used an offset is required or centering
'''icam.Width = 640
icam.Height = 480
icam.CenterX = False
icam.CenterY = False'''
# Demonstration of setting parameters - properties can be found on Pylon Viewer
# Auto property values are 'Off', 'Once', 'Continuous'
icam.GainAuto = 'Off'
icam.ExposureAuto = 'Continuous'
icam.BalanceWhiteAuto = 'Off'
icam.Gain = 0  # minimum gain value
# icam.ExposureTime       = 50000 # exposure time or use ExposureAuto
icam.StartGrabbing(py.GrabStrategy_LatestImages)
while True:
   res = icam.RetrieveResult(1000)  # 1000 = time constant for time-out
   frame = cv2.cvtColor(res.Array, cv2.COLOR_RGB2BGR)

   output = frame.copy()
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

   gray = cv2.GaussianBlur(gray,(5,5),0)
   gray = cv2.medianBlur(gray, 5)

   gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                             cv2.THRESH_BINARY,11,3.5)

   kernel = np.ones((2,3),np.uint8)
   gray = cv2.erode(gray,kernel)

   gray = cv2.dilate(gray, kernel)

   # detect circles in the image
   circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 200, param1=30, param2=45,
                       minRadius=0, maxRadius=0)
# print circles

# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")

    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle in the image
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
        # time.sleep(0.5)
        print
        "Column Number: "
        print
        x
        print
        "Row Number: "
        print
        y
        print
        "Radius is: "
        print
        r

        # Display the resulting frame
        cv2.imshow('gray', gray)
cv2.imshow('frame', output)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

for i in circles[0, :]:
    area = 3.14159 * i[2] * i[2]
    print(area)

icam.StopGrabbing()
icam.Close()
cv2.destroyAllWindows()


问:
Login API method returning 400 Bad request in Xamarin Forms
I have a login API method in Xamarin for which I am using a .net core project.The back end login in the web application works perfectly returning the token once I am logged in,but on the client side in Xamarin I am having troubles with it as the response returns a 400 Bad request.I checked the API and everything seems to be fine.I pass the token in the headers for the request along with the credentials and I am checking for the request.
This is the client side API:

  public async Task<string> Login(string email, string password)
        {
            var urlLogin = "http://10.0.2.2:5000/api/Token/";
            var formContent = new FormUrlEncodedContent(new[]
                {
              new KeyValuePair<string, string>("username", email),
              new KeyValuePair<string, string>("password", password),
              new KeyValuePair<string, string>("grant_type", "password")
            });

            var httpClient = new HttpClient();
            var authData = string.Format("{0}:{1}", email, password);
            var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authHeaderValue);
            var json = JsonConvert.SerializeObject(formContent);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                httpClient.DefaultRequestHeaders.Accept.Clear();
                var responseMessage = httpClient.PostAsync(urlLogin, content).Result;
                if(responseMessage.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Login succesful!", "Welcome", "ok", "cancel");
                    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new UsersPage());
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Wrong credentials", "Please try again!", "ok", "cancel");
                }

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }

            return "";
        }```
</div>
</div>
</p>

<p>The <strong>server-side</strong> login api:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>
   [HttpPost]
   [AllowAnonymous]
   public async Task<IActionResult> Post(User userData)
        {
            if (userData != null && userData.Email != null && userData.Password != null)
            {
                var user = await GetUser(userData.Email, userData.Password);

                if (user != null)
                {
                    //create claims details based on the user information
                    var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, config["Jwt:Subject"]),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim("Id", user.Id.ToString()),
                    new Claim("Name", user.Name),
                    new Claim("Phone", user.Phone.ToString()),
                    new Claim("Email", user.Email),
                    new Claim ("ConfPassword",user.ConfPassword)
                   };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]));

                    var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(config["Jwt:Issuer"], config["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

                    return Ok(new JwtSecurityTokenHandler().WriteToken(token));
                }
                else
                {
                    return BadRequest("Invalid credentials");
                }
            }
            else
            {
                return BadRequest();
            }
        }
        private async Task<User> GetUser(string email, string password)
        {
            return await _context.User.FirstOrDefaultAsync(u => u.Email == email && u.Password == password);
        }</code>```

User.cs

   public class User
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public string Phone { get; set; }

        public string Password { get; set; }

        public string ConfPassword { get; set; }
    }```

Can someone please help me figure out what is wrong with the API?I am new in working with mobile API so please bear with me.

答:
I have managed to make it work as @Jason suggested.This is the working method on the client side:

  public async Task<string> Login(User user)
        {
            var urlLogin = "http://10.0.2.2:5000/api/Token/";
            var httpClient = new HttpClient();
            var authData = string.Format("{0}:{1}", user.Email, user.Password);
            var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authHeaderValue);
            var json = JsonConvert.SerializeObject(user);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                httpClient.DefaultRequestHeaders.Accept.Clear();
                var responseMessage = httpClient.PostAsync(urlLogin, content).Result;
                if(responseMessage.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Login succesful!", "Welcome", "ok", "cancel");
                    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new UsersPage());
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Wrong credentials", "Please try again!", "ok", "cancel");
                }

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }

            return "";
        }```

Body:
I have a login API method in Xamarin for which I am using a .net core project.The back end login in the web application works perfectly returning the token once I am logged in,but on the client side in Xamarin I am having troubles with it as the response returns a 400 Bad request.I checked the API and everything seems to be fine.I pass the token in the headers for the request along with the credentials and I am checking for the request.
This is the client side API:

  public async Task<string> Login(string email, string password)
        {
            var urlLogin = "http://10.0.2.2:5000/api/Token/";
            var formContent = new FormUrlEncodedContent(new[]
                {
              new KeyValuePair<string, string>("username", email),
              new KeyValuePair<string, string>("password", password),
              new KeyValuePair<string, string>("grant_type", "password")
            });

            var httpClient = new HttpClient();
            var authData = string.Format("{0}:{1}", email, password);
            var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authHeaderValue);
            var json = JsonConvert.SerializeObject(formContent);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                httpClient.DefaultRequestHeaders.Accept.Clear();
                var responseMessage = httpClient.PostAsync(urlLogin, content).Result;
                if(responseMessage.IsSuccessStatusCode)
                {
                    await App.Current.MainPage.DisplayAlert("Login succesful!", "Welcome", "ok", "cancel");
                    await Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new UsersPage());
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("Wrong credentials", "Please try again!", "ok", "cancel");
                }

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }

            return "";
        }

The server-side login api:

   [HttpPost]
   [AllowAnonymous]
   public async Task<IActionResult> Post(User userData)
        {
            if (userData != null && userData.Email != null && userData.Password != null)
            {
                var user = await GetUser(userData.Email, userData.Password);

                if (user != null)
                {
                    //create claims details based on the user information
                    var claims = new[] {
                    new Claim(JwtRegisteredClaimNames.Sub, config["Jwt:Subject"]),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim("Id", user.Id.ToString()),
                    new Claim("Name", user.Name),
                    new Claim("Phone", user.Phone.ToString()),
                    new Claim("Email", user.Email),
                    new Claim ("ConfPassword",user.ConfPassword)
                   };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"]));

                    var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(config["Jwt:Issuer"], config["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);

                    return Ok(new JwtSecurityTokenHandler().WriteToken(token));
                }
                else
                {
                    return BadRequest("Invalid credentials");
                }
            }
            else
            {
                return BadRequest();
            }
        }
        private async Task<User> GetUser(string email, string password)
        {
            return await _context.User.FirstOrDefaultAsync(u => u.Email == email && u.Password == password);
        }

User.cs

   public class User
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public string Phone { get; set; }

        public string Password { get; set; }

        public string ConfPassword { get; set; }
    }

Can someone please help me figure out what is wrong with the API?I am new in working with mobile API so please bear with me.


问:
Getting response code 403 on API data in requests python
The following python script gives me 403 error, the type of request is 'GET'.

```<code>import requests
import json
url ='https://footballapi.pulselive.com/football/players?pageSize=30&compSeasons=210&altIds=true&page=2&type=player&id=-1&compSeasonId=210'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}
result = requests.get(url, headers=headers)
print(result.status_code)
</code>```

A Screenshot:

Check XHR Request Screenshot

答:
This might be a late answer, but what you're missing is the correct header to access the Pulselive API. The necessary header is 'Origin':'https://www.premierleague.com'.
This makes the API think that the request is coming from the official Premier League website, and they have access to the API.
Hope this helps!

Body:
The following python script gives me 403 error, the type of request is 'GET'.

import requests
import json
url ='https://footballapi.pulselive.com/football/players?pageSize=30&compSeasons=210&altIds=true&page=2&type=player&id=-1&compSeasonId=210'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}
result = requests.get(url, headers=headers)
print(result.status_code)

A Screenshot:

Check XHR Request Screenshot


问:
Using BackgroundWorker to update main form UI with FileSystemWatcher?
I'm a little stuck attempting to use a BackgroundWorker to update my main form UI in response to a FileSystemWatcher event being fired.

FileSystemWatcher checks for an image being added to a specific folder, fires OnCreated Handler

OnCreated handler calls RunWorkerAsync(e.FullPath) to pass the filename to the background worker

Background worker RunWorkerAsync taks the file path, and adds the item to a List(Of Product)

List(Of Product) gets added to a ListBox control on the main UI

My first issue, is updating the main UI thread after the background worker is complete. I process the image in a background worker as it takes a few seconds to generate a thumbnail from the image and don't want to lock the UI.

My second issue I'm running into, is after my event fires the second time, and exception gets thrown that the background worker is busy.

```<code>Private HoldingTank As New List(Of Product)

Private Sub LoadImages()
    Me.ToolStripStatusLabelUpdate.Text = "Images Loading - Please Wait...."
    CheckedListBoxView.Items.Clear()
    HoldingTank = Me.CreateImageList()
    For Each product As Product In HoldingTank
        Me.CheckedListBoxView.Items.Add(New ListViewDataItem With {.Image = product.Image, .ImageAlignment = ContentAlignment.MiddleCenter, .Tag = product})
    Next
    Me.ToolStripStatusLabelUpdate.Text = "Ready"
End Sub

Public Sub WatchFolders()
    watcher.Path = PathImport
    watcher.Filter = "*.tif"
    AddHandler watcher.Created, AddressOf OnCreated
    watcher.EnableRaisingEvents = True
End Sub

 Sub OnCreated(sender As Object, e As IO.FileSystemEventArgs)
    BackgroundWorker1.RunWorkerAsync(e.FullPath)
 End Sub

 Private Sub BackgroundWorker1_LoadImages(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
     HoldingTank.Add(New Product() With {.FileName = path.getFileName(e.argument), .FileExtension = path.GetExtension(e.argument), .FileFullPath = e.argument, .Image = GenerateThumbnail(e.argument)})
     '// Function GenerateThumbnail returns an Image object
End Sub
</code>```

How can i update the CheckedListBoxView control once the BackgroundWorker has added the item to the list without getting an illegal cross-thread call?

How can i check if the worker is busy if another file event raises, before the worker completes?

答:
Firstly, make sure that you have set the SynchronizingObject property of the FileSystemwatcher. If you haven't, it will raise its events on a secondary thread, which you do not want in this case. You should assign the form to that property.

Secondly, you do NOT touch the UI in the DoWork event handler or any method called from it. That is all executing on a secondary thread and you can't modify the UI on any but the UI thread. You do all the work you can in the DoWork event handler and then assign the resulting data to the e.Result property.

You then handle the RunWorkerCompleted event, which is executed on the UI thread, get that data back from the e.Result property and then update the UI. I don't know exactly what control you're using there but you should be able to create the items on the secondary thread but you'll then need to add them to the control on the UI thread.

You can find my own BackgroundWorker examples here.

Body:
I'm a little stuck attempting to use a BackgroundWorker to update my main form UI in response to a FileSystemWatcher event being fired.

FileSystemWatcher checks for an image being added to a specific folder, fires OnCreated Handler

OnCreated handler calls RunWorkerAsync(e.FullPath) to pass the filename to the background worker

Background worker RunWorkerAsync taks the file path, and adds the item to a List(Of Product)

List(Of Product) gets added to a ListBox control on the main UI

My first issue, is updating the main UI thread after the background worker is complete. I process the image in a background worker as it takes a few seconds to generate a thumbnail from the image and don't want to lock the UI.

My second issue I'm running into, is after my event fires the second time, and exception gets thrown that the background worker is busy.

Private HoldingTank As New List(Of Product)

Private Sub LoadImages()
    Me.ToolStripStatusLabelUpdate.Text = "Images Loading - Please Wait...."
    CheckedListBoxView.Items.Clear()
    HoldingTank = Me.CreateImageList()
    For Each product As Product In HoldingTank
        Me.CheckedListBoxView.Items.Add(New ListViewDataItem With {.Image = product.Image, .ImageAlignment = ContentAlignment.MiddleCenter, .Tag = product})
    Next
    Me.ToolStripStatusLabelUpdate.Text = "Ready"
End Sub

Public Sub WatchFolders()
    watcher.Path = PathImport
    watcher.Filter = "*.tif"
    AddHandler watcher.Created, AddressOf OnCreated
    watcher.EnableRaisingEvents = True
End Sub

 Sub OnCreated(sender As Object, e As IO.FileSystemEventArgs)
    BackgroundWorker1.RunWorkerAsync(e.FullPath)
 End Sub

 Private Sub BackgroundWorker1_LoadImages(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
     HoldingTank.Add(New Product() With {.FileName = path.getFileName(e.argument), .FileExtension = path.GetExtension(e.argument), .FileFullPath = e.argument, .Image = GenerateThumbnail(e.argument)})
     '// Function GenerateThumbnail returns an Image object
End Sub

How can i update the CheckedListBoxView control once the BackgroundWorker has added the item to the list without getting an illegal cross-thread call?

How can i check if the worker is busy if another file event raises, before the worker completes?


问:
using functions of an implemented interface creates 'not a function' error
I defined an interface with variables and a function.

When trying to use the function implemented for a class I get 'ERROR TypeError: ...getPrice is not a function"

The definition of the class and interface:

```<code>export interface Charge {
  code: string;
  name: string;

  getPrice: (category: string) => number;
}

export class StorePrice implements Charge {
  code: string;
  name: string;

  getPrice(category: string): number {
    return 234;
  }
}
</code>```

The component:

```<code>@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  charges: Charge[];

  constructor() {
    this.charges = [
      {
        code: "125",
        name: "apple"
      } as StorePrice,
    ];
  }

  asStorePrice(charge: Charge) {
    return charge as StorePrice;
  }
}
</code>```

The HTML where I actually use the function:

```<code><div>
  <div *ngFor="let charge of charges">

  {{asStorePrice(charge).getPrice()}}

  </div>
</div>
</code>```

答:
The problem is with the 'as' use. 'as' is just an other syntax of the cast

```<code><StorePrice> yourVariable;
</code>```

Using, 'as' doesnt create an object of the class. If you want to get the getPrice function on your object, then you need to instantiate the object normally:

```<code>this.charges = [
  new StorePrice("125, "apple)
]
</code>```

Ofc, you need to create the constructor in the class.

Body:
I defined an interface with variables and a function.

When trying to use the function implemented for a class I get 'ERROR TypeError: ...getPrice is not a function"

The definition of the class and interface:

export interface Charge {
  code: string;
  name: string;

  getPrice: (category: string) => number;
}

export class StorePrice implements Charge {
  code: string;
  name: string;

  getPrice(category: string): number {
    return 234;
  }
}

The component:

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  charges: Charge[];

  constructor() {
    this.charges = [
      {
        code: "125",
        name: "apple"
      } as StorePrice,
    ];
  }

  asStorePrice(charge: Charge) {
    return charge as StorePrice;
  }
}

The HTML where I actually use the function:

  {{asStorePrice(charge).getPrice()}}

Body:
The problem is with the 'as' use. 'as' is just an other syntax of the cast

<StorePrice> yourVariable;

Using, 'as' doesnt create an object of the class. If you want to get the getPrice function on your object, then you need to instantiate the object normally:

this.charges = [
  new StorePrice("125, "apple)
]

Ofc, you need to create the constructor in the class.


问:
Laravel Auth simple API always returning Unauthorized 401 error
This is driving me crazy... All is suppossed to be correct and im ALWAYS getting unauthorized error in my API routes!!

Api.php routes:

```<code>Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
</code>```

});

RegisterController:

```<code>    protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(80),
    ]);
}
</code>```

Database:

Request:

Accept application/json is set:

I tried too using jquery to make the request with a query parameter api_key but it doesnt work either!!

I searched a lot and can't solve this. I have another fresh application with Laravel and auth and it works perfect but this project is old and i recently updated it to Laravel 7 and I don't know why this dont works.

More info:

Im using php artisan serve to serve the application.

My kernel.php:

```<code><?php
</code>```

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

```<code>/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth:api',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'language' => \App\Http\Middleware\GetRequestLanguage::class,
    'setLocale' => \App\Http\Middleware\SetLocale::class,
];

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\Authenticate::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];
</code>```

}

Thank's you... I hope you can help me...

答:
you just need to send your token as Body in postman like this
example picture of sending authentication by postman
you must send your token in body(form data) and the key of your token must be api_token</p>

Body:
This is driving me crazy... All is suppossed to be correct and im ALWAYS getting unauthorized error in my API routes!!

Api.php routes:

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();

});

RegisterController:

    protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(80),
    ]);
}

Database:

Request:

Accept application/json is set:

I tried too using jquery to make the request with a query parameter api_key but it doesnt work either!!

I searched a lot and can't solve this. I have another fresh application with Laravel and auth and it works perfect but this project is old and i recently updated it to Laravel 7 and I don't know why this dont works.

More info:

Im using php artisan serve to serve the application.

My kernel.php:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth:api',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'language' => \App\Http\Middleware\GetRequestLanguage::class,
    'setLocale' => \App\Http\Middleware\SetLocale::class,
];

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\Authenticate::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];

}

Thank's you... I hope you can help me...


问:
iOS Buttons Conflicting with Edge Gestures on Custom Keyboard
I have buttons on my custom keyboard on the left and right side of the screen that have .touchdown actions. When I click on them they don't register the .touchdown right away and seem to be waiting to see if there is a swipe gesture. I tried using code to defer the edge gestures but in iOS 13 this doesn't seem to do the trick. Does anyone have a solution for how to get the buttons on the edge perform .touchdown action immediately when clicked?

```<code>override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
    return [.left, .bottom, .right]
}
</code>```

I also tried using the point function in a custom button class but that only makes it highlight but still doesn't perform the action right away.

```<code>override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let inside = super.point(inside: point, with: event)

    if inside && !isHighlighted && event?.type == .touches {
        isHighlighted = inside
    }

    return bounds.insetBy(dx: -2.7, dy: -12).contains(point)
}
</code>```

答:
```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if let window = view.window,
        let recognizers = window.gestureRecognizers {
        recognizers.forEach { r in
            r.delaysTouchesBegan = false
            r.cancelsTouchesInView = false
            r.isEnabled = false
        }
    }
}
</code>```

Body:
I have buttons on my custom keyboard on the left and right side of the screen that have .touchdown actions. When I click on them they don't register the .touchdown right away and seem to be waiting to see if there is a swipe gesture. I tried using code to defer the edge gestures but in iOS 13 this doesn't seem to do the trick. Does anyone have a solution for how to get the buttons on the edge perform .touchdown action immediately when clicked?

override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
    return [.left, .bottom, .right]
}

I also tried using the point function in a custom button class but that only makes it highlight but still doesn't perform the action right away.

override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let inside = super.point(inside: point, with: event)

    if inside && !isHighlighted && event?.type == .touches {
        isHighlighted = inside
    }

    return bounds.insetBy(dx: -2.7, dy: -12).contains(point)
}