问:
A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'
```<code>import 'dart:async';
import 'question.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

String opentdb = 'https://opentdb.com/api.php?amount=15&type=boolean';

class QuestionServices {
  Future<List<Question>> getData() async {
    List<Question> questions;
    String link = opentdb;
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data['results'] as List;
      print(rest);
      questions =
          rest.map<Question>((json) => Question.fromJson(json)).toList();
    }
    print("List Size: ${questions.length}");
    // _questions = questions;
    return questions;
  }

  List<Question> newQuestions = getData();
}
</code>```

```<code>class Question {
  final String question;
  final bool answer;

  Question({this.question, this.answer});

  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      question: json['question'] as String,
      answer: json['correct_answer'] as bool,
    );
  }
}
</code>```

I am trying to create a list of questions from a JSON database but whenever I try to get the returned list I get the error:

```<code>"A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'."
</code>```

I am unsure why the List I'm returning is giving out that error. Is there maybe a different way to get a json to a list?

答:
getData returns a Future, therefore you need to do the following:

```<code>Future<List<Question>> newQuestions = getData();
</code>```

Body:
import 'dart:async';
import 'question.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

String opentdb = 'https://opentdb.com/api.php?amount=15&type=boolean';

class QuestionServices {
  Future<List<Question>> getData() async {
    List<Question> questions;
    String link = opentdb;
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data['results'] as List;
      print(rest);
      questions =
          rest.map<Question>((json) => Question.fromJson(json)).toList();
    }
    print("List Size: ${questions.length}");
    // _questions = questions;
    return questions;
  }

  List<Question> newQuestions = getData();
}

class Question {
  final String question;
  final bool answer;

  Question({this.question, this.answer});

  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      question: json['question'] as String,
      answer: json['correct_answer'] as bool,
    );
  }
}

I am trying to create a list of questions from a JSON database but whenever I try to get the returned list I get the error:

"A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'."

I am unsure why the List I'm returning is giving out that error. Is there maybe a different way to get a json to a list?

Body:
getData returns a Future, therefore you need to do the following:

Future<List<Question>> newQuestions = getData();


来源: stackexchange

问:
Comment Blog creating not working symfony
Hello i was trying to add comment in blog everything is fine it shows no error but when i click submit nothing happens i mean it doesn't add it in data base i dont know what im missing
this is what i have in controller

```<code>public function addCommentAction(Request $request, $id)
    {
        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();
        $blog = $em->getRepository(Blog::class)->find($id);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirect($this->generateUrl('blog_details'));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
        ));

    }
</code>```

this is what i have in blog.yml

```<code>comment_new:
    path:     /{id}/details
    defaults: { _controller: "BlogBundle:Blog:addComment" }
    methods:  [GET, POST]
</code>```

and finally this is the twig page

```<code><div class="comments-form">
                                <h4 class="comments-title">Leave A Reply</h4>

                                    <!-- .row -->
                                    <form action="{{ path('comment_new', { 'id': blog.id }) }}" method="post" >

                                        <textarea id="form_comment" name="form[comment]" required="required" class="form-control comments-textarea" placeholder="Comments*"></textarea>

                                        <input type="submit" class="btn btn-default" />

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

答:
There might be a typo:

```<code>->add('contenu', TextareaType::class) // Should be 'comment'
</code>```

In form you have used :

```<code> <textarea id="form_comment" name="form[comment]" required="required" class="form-control comments-textarea" placeholder="Comments*"></textarea>
</code>```

It seems there is mapping error, you can check by just rendering {{ form(form) }} in your template

ContentLicense: CC BY-SA 4.0

Body:
Hello i was trying to add comment in blog everything is fine it shows no error but when i click submit nothing happens i mean it doesn't add it in data base i dont know what im missing
this is what i have in controller

public function addCommentAction(Request $request, $id)
    {
        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();
        $blog = $em->getRepository(Blog::class)->find($id);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirect($this->generateUrl('blog_details'));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
        ));

    }

this is what i have in blog.yml

comment_new:
    path:     /{id}/details
    defaults: { _controller: "BlogBundle:Blog:addComment" }
    methods:  [GET, POST]

and finally this is the twig page

Leave A Reply

                                    <form action="{{ path('comment_new', { 'id': blog.id }) }}" method="post" >

                                        <textarea id="form_comment" name="form[comment]" required="required" class="form-control comments-textarea" placeholder="Comments*"></textarea>

                                        <input type="submit" class="btn btn-default" />

                                </form>

Body:
There might be a typo:

->add('contenu', TextareaType::class) // Should be 'comment'

In form you have used :

 <textarea id="form_comment" name="form[comment]" required="required" class="form-control comments-textarea" placeholder="Comments*"></textarea>

It seems there is mapping error, you can check by just rendering {{ form(form) }} in your template


问:
How to create two tables with same column definition in one script in T-SQL?
I have two scripts:

```<code>CREATE TABLE Customers
(
    Id INT,
    Age INT,
    FirstName NVARCHAR(20),
    LastName NVARCHAR(20),
    Email VARCHAR(30),
    Phone VARCHAR(20)
)

CREATE TABLE _Customers
(
    Id INT,
    Age INT,
    FirstName NVARCHAR(20),
    LastName NVARCHAR(20),
    Email VARCHAR(30),
    Phone VARCHAR(20)
)
</code>```

The only difference is the table name.

How to replace 2 column definitions with one? So not to have errors in the future in case of renaming a column or adding a new column to one table (tables always have to be equally defined)?

答:
in oracle

```<code>CREATE TABLE new_table
  AS (SELECT * FROM old_table);
</code>```

as you updated question so sql server it will be

```<code>SELECT * INTO newtable
FROM oldtable
WHERE condition
</code>```

Body:
I have two scripts:

CREATE TABLE Customers
(
    Id INT,
    Age INT,
    FirstName NVARCHAR(20),
    LastName NVARCHAR(20),
    Email VARCHAR(30),
    Phone VARCHAR(20)
)

CREATE TABLE _Customers
(
    Id INT,
    Age INT,
    FirstName NVARCHAR(20),
    LastName NVARCHAR(20),
    Email VARCHAR(30),
    Phone VARCHAR(20)
)

The only difference is the table name.

How to replace 2 column definitions with one? So not to have errors in the future in case of renaming a column or adding a new column to one table (tables always have to be equally defined)?

Body:
in oracle

CREATE TABLE new_table
  AS (SELECT * FROM old_table);

as you updated question so sql server it will be

SELECT * INTO newtable
FROM oldtable
WHERE condition


答:
In SQL Server, if you want to create a new table with the same column names and types, you can use:

```<code>select c.*
into _customer
from customer c
where 1 = 0;
</code>```

You might want to drop _customer before doing this.

Note:  This does not copy constraints or triggers, so it is not an alternative to create table like that is available in other databases.  But your question seems to be about columns and types.

Also:  age is a horrible value to store into a table.  It literally changes every day.

Title: How to create two tables with same column definition in one script in T-SQL?

Body:
In SQL Server, if you want to create a new table with the same column names and types, you can use:

select c.*
into _customer
from customer c
where 1 = 0;

You might want to drop _customer before doing this.

Note:  This does not copy constraints or triggers, so it is not an alternative to create table like that is available in other databases.  But your question seems to be about columns and types.

Also:  age is a horrible value to store into a table.  It literally changes every day.


问:
JMeter Logger (jmeter.log) - How to Change the Timestamp Format (jmeter 5.2.1)
Currently, the jmeter.log file is written with a timestamp of format 2020-02-13 16:36:29,356

However, the comma before the ms is causing me some issues when parsing in elastic search. I would like to change it to a '.' so that I can use commas to delimit the subsequent log message elements. I tried using pipes, but my devops tell me this is a pain for them...

I've done a fair bit of trawling through the internet and cannot find anything that explains how to modify the jmeter.log timestamp format. Plenty that explains how to change all the other log timestamp formats (e.g. jtl) but nothing on jmeter.log

I saw something that recommended entering log_format=%{time:yyyy/MM/dd HH:mm:ss},%5.5{priority},%{category}:,%{message} %{throwable} into jmeter.properties but this doesn't seem to make any difference.

I'm using jmeter 5.2.1

Thanks...

答:
In the log4j2.xml file (lives in "bin" folder of your JMeter installation) locate the following lines:

```<code><pattern>%d %p %c{1.}: %m%n</pattern>
</code>```

and change them to

```<code><pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %p %c{1.}: %m%n</pattern>
</code>```

So the whole Appenders section would look like:

```<code><File name="jmeter-log" fileName="${sys:jmeter.logfile:-jmeter.log}" append="false">
  <PatternLayout>
    <pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %p %c{1.}: %m%n</pattern>
  </PatternLayout>
</File>

<GuiLogEvent name="gui-log-event">
  <PatternLayout>
    <pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %p %c{1.}: %m%n</pattern>
  </PatternLayout>
</GuiLogEvent>
</code>```

Restart JMeter to pick up the change

That's it, now you should be able to enjoy the dot between seconds and milliseconds

References:

Log4J PatternLayout

How to Configure JMeter Logging

Body:
In the log4j2.xml file (lives in "bin" folder of your JMeter installation) locate the following lines:

<pattern>%d %p %c{1.}: %m%n</pattern>

and change them to

<pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %p %c{1.}: %m%n</pattern>

So the whole Appenders section would look like:

<File name="jmeter-log" fileName="${sys:jmeter.logfile:-jmeter.log}" append="false">
  <PatternLayout>
    <pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %p %c{1.}: %m%n</pattern>
  </PatternLayout>
</File>

<GuiLogEvent name="gui-log-event">
  <PatternLayout>
    <pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %p %c{1.}: %m%n</pattern>
  </PatternLayout>
</GuiLogEvent>

Restart JMeter to pick up the change

That's it, now you should be able to enjoy the dot between seconds and milliseconds

References:

Log4J PatternLayout

How to Configure JMeter Logging


问:
Converting minutes to hours in prolog
I am trying to convert total minutes(N) to number of hours(H) and number of minutes(M) in prolog using this code (Have not implemented counting the minutes yet):

```<code>minutes_to_hours(N, H, M) :-

   (   N >= 60
   ->  H is H1+1,
       N is N1-60,
       minutes_to_hours(N, H, M)
   ;   writeln(H)
   ).
</code>```

I get this error:

```<code>Arguments are not sufficiently instantiated
In:
[2] _1440 is _1446+1
[1] mins_to_hours_and_mins(60,_1508,_1510) at  line 1
</code>```

答:
H1 is not instantiated, hence the error. But note there is no need for recursion, you can do it similarly to other languages:

?- [user].
|: minutes_to_hours(N, H, M) :-
|:   H is N // 60,
|:   M is N mod 60.
|: ^D% user://1 compiled 0.05 sec, 1 clauses
true.

?- minutes_to_hours(125,H,M).
H = 2,
M = 5.
```

Title: Converting minutes to hours in prolog

Body:
I am trying to convert total minutes(N) to number of hours(H) and number of minutes(M) in prolog using this code (Have not implemented counting the minutes yet):

minutes_to_hours(N, H, M) :-

   (   N >= 60
   ->  H is H1+1,
       N is N1-60,
       minutes_to_hours(N, H, M)
   ;   writeln(H)
   ).

I get this error:

Arguments are not sufficiently instantiated
In:
[2] _1440 is _1446+1
[1] mins_to_hours_and_mins(60,_1508,_1510) at  line 1


问:
Call function/axios function before component died
I would like to know if it's possible to call function before component died.
I tried a lot of things like the code bellow but it's not working as expected.
Like :

```<code>export const  isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i);
export const  eventName = isOnIOS ? "pagehide" : "beforeunload";
</code>```

```<code>  componentDidUpdate() {
    window.addEventListener(eventName, () => {
      this.handleLogOut();
    });
  }
  componentWillUnmount() {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }
</code>```

It's almost working on computer but quite weird cause sometimes I haven't log of my axios function; on Iphone/Ipad it's not working at all.
So I would like to know if you guys have others ideas about this ?
Thx a lot and have a good day!

答:
There is no lifecycle hook for component «death». Closest to this action is componentWillUnmount() for class based components and useEffect hook for function based components.

So, if you have

```<code>  componentWillUnmount() {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }
</code>```

the equivalent code for function based component will be:

```<code>useEffect(() => {
  return () => {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }
}, [])
</code>```

Also be sure to check out React hooks for more detailed info.

Body:
I would like to know if it's possible to call function before component died.
I tried a lot of things like the code bellow but it's not working as expected.
Like :

export const  isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i);
export const  eventName = isOnIOS ? "pagehide" : "beforeunload";

  componentDidUpdate() {
    window.addEventListener(eventName, () => {
      this.handleLogOut();
    });
  }
  componentWillUnmount() {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }

It's almost working on computer but quite weird cause sometimes I haven't log of my axios function; on Iphone/Ipad it's not working at all.
So I would like to know if you guys have others ideas about this ?
Thx a lot and have a good day!

Body:
There is no lifecycle hook for component «death». Closest to this action is componentWillUnmount() for class based components and useEffect hook for function based components.

So, if you have

  componentWillUnmount() {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }

the equivalent code for function based component will be:

useEffect(() => {
  return () => {
    this.handleLogOut();
    window.removeEventListener(eventName, this.handleLogOut);
  }
}, [])

Also be sure to check out React hooks for more detailed info.


问:
Append a numpy array with different first dimensions
My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10), then (160*30*10) and then may be (120*30*10) . I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy  array with shape (380*30*10) (i.e sum  of 100+160+120) . The second and third dimension doesnt change in the numpy array.

How can I do the above in python. I tried the following.

```<code>np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)
</code>```

The np_model is an empty array which I have defined as np_model = np.empty(1,30,10) and np_label as np_label = np.empty(1 ,str)

np_temp1 corresponds to array within each for loop like 100*30*10,120*30*10 etc and np_temp2 is a string with "item1","item2" etc

The np_label is a string numpy array with 1 label corresponding to np_temp1.shape[0]. But the result I get in np_model is flattened array with size 380*30*10 = 1140000

Any help is appreciated.

答:
To specifically answer your question towards starting with an empty array, that'd be my solution, solely using np.concatenate:

import numpy as np

# Some arrays to append in a loop
arrays = (
    np.random.rand(100, 30, 10),
    np.random.rand(160, 30, 10),
    np.random.rand(120, 30, 10)
)

# Initial empty array
array = np.zeros((0, 30, 10))

# Appending arrays in loop
for a in arrays:
    array = np.concatenate((array, a), axis=0)

# Output shape
print(array.shape)
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>(380, 30, 10)
</code>```

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
----------------------------------------
```

Body:
My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10), then (160*30*10) and then may be (120*30*10) . I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy  array with shape (380*30*10) (i.e sum  of 100+160+120) . The second and third dimension doesnt change in the numpy array.

How can I do the above in python. I tried the following.

np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)

The np_model is an empty array which I have defined as np_model = np.empty(1,30,10) and np_label as np_label = np.empty(1 ,str)

np_temp1 corresponds to array within each for loop like 100*30*10,120*30*10 etc and np_temp2 is a string with "item1","item2" etc

The np_label is a string numpy array with 1 label corresponding to np_temp1.shape[0]. But the result I get in np_model is flattened array with size 380*30*10 = 1140000

Any help is appreciated.

Body:
To specifically answer your question towards starting with an empty array, that'd be my solution, solely using np.concatenate:

import numpy as np

# Some arrays to append in a loop
arrays = (
    np.random.rand(100, 30, 10),
    np.random.rand(160, 30, 10),
    np.random.rand(120, 30, 10)
)

# Initial empty array
array = np.zeros((0, 30, 10))

# Appending arrays in loop
for a in arrays:
    array = np.concatenate((array, a), axis=0)

# Output shape
print(array.shape)

Output:

(380, 30, 10)

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
----------------------------------------


问:
I am currently building a React app with Google OAuth2.0, it is not redirecting after completing login
Built a simple react login page using OAut2.0 but does not redirect to a new page after login, rather lands back on the login page.

I want my page to redirect to the dashboard after login.

Google API console has been configured with Authorized JavaScript origins( URIs) and Authorized redirect URIs.

If possible you can share how to use passport JS for reactjs.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import GoogleLogin from 'react-google-login'; // or import { GoogleLogin } from 'react-google-login';

const responseGoogle = (response) => {   console.log(response); }
ReactDOM.render(<GoogleLogin
    clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
    buttonText="Login"
    onSuccess={responseGoogle}
    onFailure={responseGoogle}
    cookiePolicy={'single_host_origin'}/>,
    document.getElementById('googleButton') );
</code>```

答: so in your responseGoogle method, instead of console.log() you could run return this.history.push("/dashboard") this would redirect to your dashboard or the route that is the dashboard or you could send a snippet of your response logged to the console for us to see

Body:
Built a simple react login page using OAut2.0 but does not redirect to a new page after login, rather lands back on the login page.

I want my page to redirect to the dashboard after login.

Google API console has been configured with Authorized JavaScript origins( URIs) and Authorized redirect URIs.

If possible you can share how to use passport JS for reactjs.

import React from 'react';
import ReactDOM from 'react-dom';
import GoogleLogin from 'react-google-login'; // or import { GoogleLogin } from 'react-google-login';

const responseGoogle = (response) => {   console.log(response); }
ReactDOM.render(<GoogleLogin
    clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
    buttonText="Login"
    onSuccess={responseGoogle}
    onFailure={responseGoogle}
    cookiePolicy={'single_host_origin'}/>,
    document.getElementById('googleButton') );


问:
setToken doesn't switch YouTube channel in Google API (gapi)
I've got a problem that I cannot solve. I want to allow users to connect to multiple youtube channels at once and create youtube streams for them. The main code looks like this:

```<code>export const setGapiTokenForTarget = async (token) => {
    await window.gapi.client.setToken(token);
    await window.gapi.auth.setToken(token);
};

export const bindStreamToBroadcast = async (streamId, broadcastId, token) => {
    await setGapiTokenForTarget(token);
    return window.gapi.client.youtube.liveBroadcasts.bind({
        'id': broadcastId,
        'part': 'snippet',
        'streamId': streamId
    });
};

export const createBroadcast = async (token) => {
    await setGapiTokenForTarget(token);
    return window.gapi.client.youtube.liveBroadcasts.insert({
        'part': 'snippet,contentDetails,status',
        'resource': {
            'snippet': {
                'title': 'l1',
                'scheduledStartTime': '2020-02-07T09:20:17.039Z',
                'scheduledEndTime': '2020-02-07T09:40:17.039Z'
            },
            'status': {
                'privacyStatus': 'unlisted'
            }
        }
    });
};

export const createStream = async (token) => {
    await setGapiTokenForTarget(token);
    return window.gapi.client.youtube.liveStreams.insert({
        'part': 'snippet,cdn,contentDetails,status',
        'resource': {
            'snippet': {
                'title': 'LIVE PANEL TEST',
                'description': 'LIVE PANEL TEST'
            },
            'cdn': {
                'frameRate': '60fps',
                'ingestionType': 'rtmp',
                'resolution': '1080p'
            },
            'contentDetails': {
                'isReusable': true
            }
        }
    });
};

export const createStreamAndBroadcastForTarget = async (target) => {
    const broadcast = await createBroadcast(target.token);
    const stream = await createStream(target.token);
    const binded = await bindStreamToBroadcast(stream.result.id, broadcast.result.id, target.token);

    return { stream, broadcast, binded };
};

export const createStreamAndBroadcastForTargets = async (targets, { ...all }) => {
    const youtubeEvents = targets.map(createStreamAndBroadcastForTarget);

    return Promise.all(youtubeEvents);
};
</code>```

This is just the prototype and the data is hard-coded. However, when I try to setToken for each target (channel), the profile doesn't change and I'm doing the same thing (creating lives) at only one of the channels. Each channel has it's own token returned from google after sign in and it is an object taken directly from google, not just key (string). I've checked it and every token is different for each channel. It looks like window.gapi.client.setToken and window.gapi.auth.setToken is not working and it doesn't switch anything.

答:
The YouTube API is channel based not user based. Your going to have to logout a user and log them in under a different channel.

Your going to have to have a live token for each channel in your script if you want to have access to more then on at a time and im not sure that library supports that.

Body:
I've got a problem that I cannot solve. I want to allow users to connect to multiple youtube channels at once and create youtube streams for them. The main code looks like this:

export const setGapiTokenForTarget = async (token) => {
    await window.gapi.client.setToken(token);
    await window.gapi.auth.setToken(token);
};

export const bindStreamToBroadcast = async (streamId, broadcastId, token) => {
    await setGapiTokenForTarget(token);
    return window.gapi.client.youtube.liveBroadcasts.bind({
        'id': broadcastId,
        'part': 'snippet',
        'streamId': streamId
    });
};

export const createBroadcast = async (token) => {
    await setGapiTokenForTarget(token);
    return window.gapi.client.youtube.liveBroadcasts.insert({
        'part': 'snippet,contentDetails,status',
        'resource': {
            'snippet': {
                'title': 'l1',
                'scheduledStartTime': '2020-02-07T09:20:17.039Z',
                'scheduledEndTime': '2020-02-07T09:40:17.039Z'
            },
            'status': {
                'privacyStatus': 'unlisted'
            }
        }
    });
};

export const createStream = async (token) => {
    await setGapiTokenForTarget(token);
    return window.gapi.client.youtube.liveStreams.insert({
        'part': 'snippet,cdn,contentDetails,status',
        'resource': {
            'snippet': {
                'title': 'LIVE PANEL TEST',
                'description': 'LIVE PANEL TEST'
            },
            'cdn': {
                'frameRate': '60fps',
                'ingestionType': 'rtmp',
                'resolution': '1080p'
            },
            'contentDetails': {
                'isReusable': true
            }
        }
    });
};

export const createStreamAndBroadcastForTarget = async (target) => {
    const broadcast = await createBroadcast(target.token);
    const stream = await createStream(target.token);
    const binded = await bindStreamToBroadcast(stream.result.id, broadcast.result.id, target.token);

    return { stream, broadcast, binded };
};

export const createStreamAndBroadcastForTargets = async (targets, { ...all }) => {
    const youtubeEvents = targets.map(createStreamAndBroadcastForTarget);

    return Promise.all(youtubeEvents);
};

This is just the prototype and the data is hard-coded. However, when I try to setToken for each target (channel), the profile doesn't change and I'm doing the same thing (creating lives) at only one of the channels. Each channel has it's own token returned from google after sign in and it is an object taken directly from google, not just key (string). I've checked it and every token is different for each channel. It looks like window.gapi.client.setToken and window.gapi.auth.setToken is not working and it doesn't switch anything.


问:
How to enter text at the beginning of JTextField
Is there a way to add functionality that would enable a user to type into a JTextField but the cursor stays at the beginning of the input, thus making the text backward?

Example:

User types '5'

5 is displayed

User types '9'

95 is displayed

答:
If you need this to happen only with numbers, I suggest you to use a JSpinner component instead of a JTextField. But with textField you can achieve it like this:

```<code>    JTextField field = new JTextField();
    AbstractDocument document = (AbstractDocument) field.getDocument();
    document.setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            offset = 0;//Insert string at offset 0
            super.insertString(fb, offset, string, attr);
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            offset = 0; //Insert string at offset 0
            super.replace(fb, offset, length, text, attrs);
        }
    });
</code>```

Body:
If you need this to happen only with numbers, I suggest you to use a JSpinner component instead of a JTextField. But with textField you can achieve it like this:

    JTextField field = new JTextField();
    AbstractDocument document = (AbstractDocument) field.getDocument();
    document.setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            offset = 0;//Insert string at offset 0
            super.insertString(fb, offset, string, attr);
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            offset = 0; //Insert string at offset 0
            super.replace(fb, offset, length, text, attrs);
        }
    });


问:
How can I fix this issue: Provide a one-off default now?
When I run makemigrations I get this error:

```<code>You are trying to add the field 'post_date' with 'auto_now_add=True' to user asking without a default; the database needs something
 to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:
</code>```

In this code I try to set the date field and I find this error. When I do a search about this issue I find that I need to set the default and I set:

```<code>from django.utils import timezone
post_date = models.DateField(auto_now_add=True, default=timezone.now())
</code>```

When I set default I get this error:

```<code>WARNINGS:
community.UserAsking.post_date: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If y
ou want to have the current date as default, use `django.utils.timezone.now`
</code>```

How can I skip this issue and migrate successfully?

models.py:

```<code>class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
    post_date = models.DateField(auto_now_add=True)
</code>```

答:
The error is saying that since you now want to have a default value for date field, you then need to provide on for the records that are already stored in DB.

First what you need to do is to change this:

```<code>models.DateField(auto_now_add=True, default=timezone.now())
</code>```

to this:

```<code>models.DateField(auto_now_add=True)
</code>```

Next - do as Arakkal Abu adviced:

choose option 1 and type timezone.now and hit enter

Note: you do not need to call method like now() insead just use now (without parentheses)

Body:
When I run makemigrations I get this error:

You are trying to add the field 'post_date' with 'auto_now_add=True' to user asking without a default; the database needs something
 to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:

In this code I try to set the date field and I find this error. When I do a search about this issue I find that I need to set the default and I set:

from django.utils import timezone
post_date = models.DateField(auto_now_add=True, default=timezone.now())

When I set default I get this error:

WARNINGS:
community.UserAsking.post_date: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If y
ou want to have the current date as default, use `django.utils.timezone.now`

How can I skip this issue and migrate successfully?

models.py:

class UserAsking(models.Model):
    userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
    question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
    field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
    post_date = models.DateField(auto_now_add=True)

Body:
The error is saying that since you now want to have a default value for date field, you then need to provide on for the records that are already stored in DB.

First what you need to do is to change this:

models.DateField(auto_now_add=True, default=timezone.now())

to this:

models.DateField(auto_now_add=True)

Next - do as Arakkal Abu adviced:

choose option 1 and type timezone.now and hit enter

Note: you do not need to call method like now() insead just use now (without parentheses)


问:
jQuery Center Div toggle in IE6
Click the button to center div, click again to left align. This works in all browsers except IE6. IE6 doesn't support margin:0 auto; How can i work around this. div width is dynamic and not always 200px.

Check jsfiddle http://jsfiddle.net/hZ23J/1/

```<code><button id="center">Left Align</button>
<div></div>

$('#center').toggle(function() {
    $('div').css('margin', '0');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $(this).text('Left Align')
});
</code>```

答:
For IE6 use

```<code>body{
text-align:center;
}
</code>```

And your jQuery code will look like

```<code>$('#center').toggle(function() {
    $('div').css('margin', '0');
    $('body').css('text-align', 'left');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $('body').css('text-align', 'center');
    $(this).text('Left Align')
});
</code>```

Check working example at http://jsfiddle.net/jNWYP/1/

ContentLicense: CC BY-SA 3.0

Title: jQuery Center Div toggle in IE6

Body:
Click the button to center div, click again to left align. This works in all browsers except IE6. IE6 doesn't support margin:0 auto; How can i work around this. div width is dynamic and not always 200px.

Check jsfiddle http://jsfiddle.net/hZ23J/1/

<button id="center">Left Align</button>

$('#center').toggle(function() {
    $('div').css('margin', '0');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $(this).text('Left Align')
});

Body:
For IE6 use

body{
text-align:center;
}

And your jQuery code will look like

$('#center').toggle(function() {
    $('div').css('margin', '0');
    $('body').css('text-align', 'left');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $('body').css('text-align', 'center');
    $(this).text('Left Align')
});

Check working example at http://jsfiddle.net/jNWYP/1/


问:
How to fix a "NameError: name 'color' is not defined"?
here is my code :

```<code>size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)
</code>```

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

答:
A couple comments. Since you define color as a class variable, you probably don't want to reassign it as an instance variable. Just use it directly with Particle.color (see draw below). If you want to keep track of IDs you can just use id(object). You can use your existing strategy for ID as a count though.

```<code>class Particle:
    color = (255, 255, 0)

    def __init__(self, rect):
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        print(Particle.color, self.rect) # pygame.draw.rect

p = Particle("Rectangle dimensions")
id(p)
> 4559902608

p2 = Particle("Rectangle dimensions")
id(p2)
> 4559964496
</code>```

Body:
here is my code :

size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

Body:
A couple comments. Since you define color as a class variable, you probably don't want to reassign it as an instance variable. Just use it directly with Particle.color (see draw below). If you want to keep track of IDs you can just use id(object). You can use your existing strategy for ID as a count though.

class Particle:
    color = (255, 255, 0)

    def __init__(self, rect):
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        print(Particle.color, self.rect) # pygame.draw.rect

p = Particle("Rectangle dimensions")
id(p)
> 4559902608

p2 = Particle("Rectangle dimensions")
id(p2)
> 4559964496


问:
permission denied error on tomcat docker image deployment to openshift container - /usr/local/tomcat/conf/web.xml (permission denied)
Here is my Dockerfile content. When I run this locally it works well but when I try to deploy it on the openshift container it throws permission denied error

```<code>    FROM tomcat:8.0.36-jre8
    CMD groupadd -r myuser -g 501
    CMD useradd -d /home/myuser -u 501 -m -s /bin/bash -g myuser myuser
    CMD chown -R myuser:myuser /usr/local/tomcat
    ADD target/ui-1.0.war /usr/local/tomcat/webapps/
    ADD docker-tomcat-conf/server.xml /usr/local/tomcat/conf/
    ADD docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF
    EXPOSE 8080
    CMD chmod +x /usr/local/tomcat/bin/catalina.sh
    ENTRYPOINT ["catalina.sh", "run"]
</code>```

and the error

```<code>    Parse error in application web.xml file at file:/usr/local/tomcat/conf/web.xml
java.io.FileNotFoundException: /usr/local/tomcat/conf/web.xml (Permission denied)
    at java.io.FileInputStream.open0(Native Method)
</code>```

答:
```<code>FROM tomcat:8.0.36-jre8
RUN groupadd -r myuser -g 501
RUN useradd -d /home/myuser -u 501 -m -s /bin/bash -g myuser myuser
RUN chown -R myuser:myuser /usr/local/tomcat
ADD target/ui-1.0.war /usr/local/tomcat/webapps/
ADD docker-tomcat-conf/server.xml /usr/local/tomcat/conf/
ADD docker-tomcat-conf/web.xml /usr/local/tomcat/conf/
EXPOSE 8080
RUN chmod +x /usr/local/tomcat/bin/catalina.sh
ENTRYPOINT ["catalina.sh", "run"]
</code>```

First of you need to replace the CMD commands with RUN statements.

Additionally, aren't you missing a / at

```<code>docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF
</code>```

I guess this should be

```<code>docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF/
</code>```

or

```<code>docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF/web.xml
</code>```

Shouldn't /usr/local/tomcat/webapps/manager/WEB-INF/ be /usr/local/tomcat/conf/?

Body:
Here is my Dockerfile content. When I run this locally it works well but when I try to deploy it on the openshift container it throws permission denied error

    FROM tomcat:8.0.36-jre8
    CMD groupadd -r myuser -g 501
    CMD useradd -d /home/myuser -u 501 -m -s /bin/bash -g myuser myuser
    CMD chown -R myuser:myuser /usr/local/tomcat
    ADD target/ui-1.0.war /usr/local/tomcat/webapps/
    ADD docker-tomcat-conf/server.xml /usr/local/tomcat/conf/
    ADD docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF
    EXPOSE 8080
    CMD chmod +x /usr/local/tomcat/bin/catalina.sh
    ENTRYPOINT ["catalina.sh", "run"]

and the error

    Parse error in application web.xml file at file:/usr/local/tomcat/conf/web.xml
java.io.FileNotFoundException: /usr/local/tomcat/conf/web.xml (Permission denied)
    at java.io.FileInputStream.open0(Native Method)

Body:
FROM tomcat:8.0.36-jre8
RUN groupadd -r myuser -g 501
RUN useradd -d /home/myuser -u 501 -m -s /bin/bash -g myuser myuser
RUN chown -R myuser:myuser /usr/local/tomcat
ADD target/ui-1.0.war /usr/local/tomcat/webapps/
ADD docker-tomcat-conf/server.xml /usr/local/tomcat/conf/
ADD docker-tomcat-conf/web.xml /usr/local/tomcat/conf/
EXPOSE 8080
RUN chmod +x /usr/local/tomcat/bin/catalina.sh
ENTRYPOINT ["catalina.sh", "run"]

First of you need to replace the CMD commands with RUN statements.

Additionally, aren't you missing a / at

docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF

I guess this should be

docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF/

or

docker-tomcat-conf/web.xml /usr/local/tomcat/webapps/manager/WEB-INF/web.xml

Shouldn't /usr/local/tomcat/webapps/manager/WEB-INF/ be /usr/local/tomcat/conf/?


问:
Reverse value from one view to another by using protocol in Swift
Now I'm learing the swift programming and I'm stuck on the protocol grammar.

There's a simple function I want to implement: There are two ViewControllers I've created in one Main.Storyboard, The first ViewController has a label and a button to go to the second ViewController. The second one has a textField and a button to go back to the first ViewController.

I entered some words in the textField and click go-back button to dismiss the view, but I can't see the label changed on the first view.

Here's what I've coded for the delegate view:

```<code>import UIKit

protocol SecondViewDelegate {
    func getText(text: String)
}

class SecondViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    var text: String?
    var delegate: SecondViewDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    @IBAction func backButton(_ sender: UIButton) {
//        print(text!)
        delegate?.getText(text: text!)
        dismiss(animated: true, completion: nil)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
//        print("textFieldDidEndEditing has been called")
        text = textField.text
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        return true
    }
}
</code>```

I've print the text when I pressed the backButton and I'm sure the text printed on console is which what I entered in the textField.

And here's the code for another view which showed the text:

```<code>class ViewController: UIViewController, SecondViewDelegate {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondVC = SecondViewController()
        secondVC.delegate = self
    }

    @IBAction func clickButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToSecond", sender: self)
    }

    func getText(text: String) {
        self.textLabel.text = text
    }

}
</code>```

When I returned to the view, the label didn't change. And I added a breakpoint in the function getText and run the app, the app didn't crash.

I don't know which part I've done wrong. Can anyone point out the problem to help me? Thanks!

答:
In your first view controller, if you are using segues to go to second view controller, you need to set the delegates in prepareForSegue method. Currently you are creating a new object in viewDidLoad and assigning it the delegate, which is wrong.

Here is the solution:

```<code>class ViewController: UIViewController, SecondViewDelegate {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func clickButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToSecond", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecond" {
            if let vc = segue.destination as? SecondViewController {
                vc.delegate = self
            }
        }
    }

    func getText(text: String) {
        self.textLabel.text = text
    }

}
</code>```

Body:
Now I'm learing the swift programming and I'm stuck on the protocol grammar.

There's a simple function I want to implement: There are two ViewControllers I've created in one Main.Storyboard, The first ViewController has a label and a button to go to the second ViewController. The second one has a textField and a button to go back to the first ViewController.

I entered some words in the textField and click go-back button to dismiss the view, but I can't see the label changed on the first view.

Here's what I've coded for the delegate view:

import UIKit

protocol SecondViewDelegate {
    func getText(text: String)
}

class SecondViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    var text: String?
    var delegate: SecondViewDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    @IBAction func backButton(_ sender: UIButton) {
//        print(text!)
        delegate?.getText(text: text!)
        dismiss(animated: true, completion: nil)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
//        print("textFieldDidEndEditing has been called")
        text = textField.text
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.endEditing(true)
        return true
    }
}

I've print the text when I pressed the backButton and I'm sure the text printed on console is which what I entered in the textField.

And here's the code for another view which showed the text:

class ViewController: UIViewController, SecondViewDelegate {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondVC = SecondViewController()
        secondVC.delegate = self
    }

    @IBAction func clickButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToSecond", sender: self)
    }

    func getText(text: String) {
        self.textLabel.text = text
    }

}

When I returned to the view, the label didn't change. And I added a breakpoint in the function getText and run the app, the app didn't crash.

I don't know which part I've done wrong. Can anyone point out the problem to help me? Thanks!

Body:
In your first view controller, if you are using segues to go to second view controller, you need to set the delegates in prepareForSegue method. Currently you are creating a new object in viewDidLoad and assigning it the delegate, which is wrong.

Here is the solution:

class ViewController: UIViewController, SecondViewDelegate {

    @IBOutlet weak var textLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func clickButton(_ sender: UIButton) {
        performSegue(withIdentifier: "goToSecond", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecond" {
            if let vc = segue.destination as? SecondViewController {
                vc.delegate = self
            }
        }
    }

    func getText(text: String) {
        self.textLabel.text = text
    }

}


问:
Invalid certificate (CSR)
I generate .certSigningRequest file via Keychain Access (Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority..., I fill in my mail and I save it to disk).

When I log into Apple developer account and try to generate Certificate with it I get message: "Invalid CSR - Invalid Certificate"

I did this number of times previously with my previous Mac but it is not working on my new system.

What am I doing wrong? I have followed exact steps https://help.apple.com/developer-account/#/devbfa00fef7

答:
Just forgot to input 'Common name' in Certificate Assistant form.

So, make sure you filled

User Email Address

Common Name

Saved on disk check

Title: Invalid certificate (CSR)


问:
thread safe with pop and visit in c++ queue
I know std::queue is not thread safe, but I don't want to lock queue.
so I use pop & push limit on usages.

for instance,
when I want to pop:
I have an enum to express first element status

```<code>enum {
    Busy = 1,
    Unused,
}
</code>```

when I add an elment to queue:

```<code>void UserAdd() {
    lock.lock();
    element.status = BUSY;
    queue.push_back(element);
    lock.unlock();
}
</code>```

when I visit :

```<code>//only visit function, and every element only called once.
void UserVisit() {
    auto header = queue.front();
    .......
    queue.front().status = UNUSED;
    return ;
}
</code>```

I judge first elements status when I want to pop element.

If first element is Busy, wait;

If first element is Unused, pop;

```<code>void UserPop() {
    while (queue.front().status != Unused) {
        usleep(200);
    }
    lock.lock();
    queue.pop();
    lock.unlock();
}
</code>```

thread A: 1. UserAdd, 2. UserVisit, 1.UserAdd, 2.UserVisit loop ...

thread B: 1. UserPop.

Is UserPop() && UserVisit thread safe ?.

I think It's thread safe.

答:
 No thread safety

Note that the member function pop() does modify the queue. If UserPop() is called by multiple threads concurrently, one thread may modify the queue by calling pop() on it at the same time another thread is reading the queue by calling front():

```<code>void UserPop() {
    while (queue.front().status != Unused) { // <-- read queue
        usleep(200);
    }
    queue.pop(); // <-- modify queue
}
</code>```

Since the queue itself, std::queue, doesn't handle concurrent access for you, UserPop() is not thread-safe.

Make it thread safe

A simple approach to make it thread-safe is to add a mutex and hold a lock on it when reading or modifying the queue:

```<code>std::mutex mtx;

// ...

void UserPop() {
    std::unique_lock<std::mutex> lck(mtx);
    // mtx is locked at this point
    while (queue.front().status != Unused) {
        lck.unlock();
        usleep(200); // mtx is not locked
        lck.lock();
    }
    // mtx is locked at this point
    queue.pop();
}
</code>```

std::queue's member functions front() and pop() above are always called while holding a lock on the mutex.

However, you may want to consider using std::condition_variable instead. It provides an optimization over the busy waiting:

```<code>std::mutex mtx;
std::condition_variable cv;

void UserPop() {
    std::unique_lock<std::mutex> lck(mtx);
    cv.wait(lck, [this]() { return queue.front().status == Unused; });
    queue.pop();
}
</code>```

Body:
I know std::queue is not thread safe, but I don't want to lock queue.
so I use pop & push limit on usages.

for instance,
when I want to pop:
I have an enum to express first element status

enum {
    Busy = 1,
    Unused,
}

when I add an elment to queue:

void UserAdd() {
    lock.lock();
    element.status = BUSY;
    queue.push_back(element);
    lock.unlock();
}

when I visit :

//only visit function, and every element only called once.
void UserVisit() {
    auto header = queue.front();
    .......
    queue.front().status = UNUSED;
    return ;
}

I judge first elements status when I want to pop element.

If first element is Busy, wait;

If first element is Unused, pop;

void UserPop() {
    while (queue.front().status != Unused) {
        usleep(200);
    }
    lock.lock();
    queue.pop();
    lock.unlock();
}

thread A: 1. UserAdd, 2. UserVisit, 1.UserAdd, 2.UserVisit loop ...

thread B: 1. UserPop.

Is UserPop() && UserVisit thread safe ?.

I think It's thread safe.

Body:
 No thread safety

Note that the member function pop() does modify the queue. If UserPop() is called by multiple threads concurrently, one thread may modify the queue by calling pop() on it at the same time another thread is reading the queue by calling front():

void UserPop() {
    while (queue.front().status != Unused) { // <-- read queue
        usleep(200);
    }
    queue.pop(); // <-- modify queue
}

Since the queue itself, std::queue, doesn't handle concurrent access for you, UserPop() is not thread-safe.

Make it thread safe

A simple approach to make it thread-safe is to add a mutex and hold a lock on it when reading or modifying the queue:

std::mutex mtx;

// ...

void UserPop() {
    std::unique_lock<std::mutex> lck(mtx);
    // mtx is locked at this point
    while (queue.front().status != Unused) {
        lck.unlock();
        usleep(200); // mtx is not locked
        lck.lock();
    }
    // mtx is locked at this point
    queue.pop();
}

std::queue's member functions front() and pop() above are always called while holding a lock on the mutex.

However, you may want to consider using std::condition_variable instead. It provides an optimization over the busy waiting:

std::mutex mtx;
std::condition_variable cv;

void UserPop() {
    std::unique_lock<std::mutex> lck(mtx);
    cv.wait(lck, [this]() { return queue.front().status == Unused; });
    queue.pop();
}


问:
Android Q foregroundServiceType attribute
Why need foregroundServiceType attribute in Android Q except for location? In case a service is used for location access, we need to set it. But, what about other types?
https://developer.android.com/preview/features#fg-service-types
Do we really need to set them? And if not, will there be some problems or exceptions?</p>

答:
You won't be able access some APIs from the service in Android Q.
Take a look at Javadoc in Android sources </p>


问:
How to compute distance between my original and supplied point in Java
```<code>public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}
</code>```

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}
```

Would this be fine?

答:
You didn't use in the parameter.    </p>

```<code>public double distance(Point other) {

        double d = Math.pow(other.getX()- getX(), 2) + Math.pow(other.getY() - getY(), 2);

        return Math.sqrt(d);
}
</code>```

Body:
public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}

Would this be fine?

Body:
You didn't use in the parameter.

public double distance(Point other) {

        double d = Math.pow(other.getX()- getX(), 2) + Math.pow(other.getY() - getY(), 2);

        return Math.sqrt(d);
}


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答:
I never got around to looking into smarty. Others scared me away saying it was very complex. I use Twig for pretty much everything I do now, even small stuff. Even if it isn't worth it for a small site I think it's worth learning for the long term - getting a good grounding in template inheritance and blocks is absolutely worth it.

Check this out:

```<code><?php echo htmlspecialchars(\$var, ENT_QUOTES, 'UTF-8') ?>
</code>```

vs.

```<code>{{ var|escape }}
</code>```

yummy:

```<code>{% for i in 0..10 %}
  * {{ i }}
{% endfor %}
</code>```

Body:
I never got around to looking into smarty. Others scared me away saying it was very complex. I use Twig for pretty much everything I do now, even small stuff. Even if it isn't worth it for a small site I think it's worth learning for the long term - getting a good grounding in template inheritance and blocks is absolutely worth it.

Check this out:

<?php echo htmlspecialchars(\$var, ENT_QUOTES, 'UTF-8') ?>

vs.

{{ var|escape }}

yummy:

{% for i in 0..10 %}
  * {{ i }}
{% endfor %}


问:
Input of length greater than 255 in postgresql rails
I have a field with datatype string in the rails Postgresql table. What happens when I enter value more than 255. Does the Postgresql cut the string to 255 characters or does it prohibits from entering?</p>

答:
As per http://www.sqlines.com/postgresql/datatypes/text

...for example, VARCHAR(255) does not allow inserting a string more than 255 characters long.

It won't truncate the string for you, and it will fail if you try to insert one.


问:
How to get rid of "Functions are not valid as a React child" warning in React app
I am new in React and I am Developing simple CRUD application in React with the help of Hooks.

 The app has two form components AddUserForm and EditUserForm which add and edit users list corespondingly. Also there is a component which displays the list of users (but I have not got warnings there).

Everything works fine but I have the following warning message in my browser's console:

 Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it..

Here is how I render child components in my App.js file. (I marked the lines where I have warnings with red arrows)

Update
Here is how I handle form in AddUserForm component:

```<code>return (
 <Fragment>
  <form> // line 15, here I have warning as well
    onSubmit=
    {event => {
      event.preventDefault();
      if (!user.name || !user.username) return;

      props.addUser(user);
      setUser(initialFormState);
    }}
    <label>Name</label>
    <input type='text' name='name' value='' onChange={handleInputChange} />
    <label>Username</label>
    <input
      type='text'
      name='username'
      value=''
      onChange={handleInputChange}
    />
    <button>Add new user</button>
  </form>
 </Fragment>
);
</code>```

I have checked some solutions that are written for example here but none of them were helpfull for this issue.

Could you give me any hint of what I am doing wrong?

答:
I think it's just a typo:

```<code><form> // You just closed form element, so
onSubmit=
{event => { // this is a function returned as a React child
  event.preventDefault();
  if (!user.name || !user.username) return;

  props.addUser(user);
  setUser(initialFormState);
}}
<label>Name</label>
<input type='text' name='name' value='' onChange={handleInputChange} />
<label>Username</label>
<input
  type='text'
  name='username'
  value=''
  onChange={handleInputChange}
/>
<button>Add new user</button>
</code>```

Should be like this:

```<code><form // Note the missing >
onSubmit=
{event => { // this is a function returned as a React child
  event.preventDefault();
  if (!user.name || !user.username) return;

  props.addUser(user);
  setUser(initialFormState);
}}> // form opening tag closed here
</code>```

This actually is not a React issue, but an invalid HTML causing React to throw an error, as it can't parse and render JSX.

Body:
I am new in React and I am Developing simple CRUD application in React with the help of Hooks.

 The app has two form components AddUserForm and EditUserForm which add and edit users list corespondingly. Also there is a component which displays the list of users (but I have not got warnings there).

Everything works fine but I have the following warning message in my browser's console:

 Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it..

Here is how I render child components in my App.js file. (I marked the lines where I have warnings with red arrows)

Update
Here is how I handle form in AddUserForm component:

return (
 <Fragment>
  <form> // line 15, here I have warning as well
    onSubmit=
    {event => {
      event.preventDefault();
      if (!user.name || !user.username) return;

      props.addUser(user);
      setUser(initialFormState);
    }}
    Name
    <input type='text' name='name' value='' onChange={handleInputChange} />
    Username
    <input
      type='text'
      name='username'
      value=''
      onChange={handleInputChange}
    />
    <button>Add new user</button>
  </form>
 </Fragment>
);

I have checked some solutions that are written for example here but none of them were helpfull for this issue.

Could you give me any hint of what I am doing wrong?

Body:
I think it's just a typo:

<form> // You just closed form element, so
onSubmit=
{event => { // this is a function returned as a React child
  event.preventDefault();
  if (!user.name || !user.username) return;

  props.addUser(user);
  setUser(initialFormState);
}}
<label>Name</label>
<input type='text' name='name' value='' onChange={handleInputChange} />
<label>Username</label>
<input
  type='text'
  name='username'
  value=''
  onChange={handleInputChange}
/>
<button>Add new user</button>

Should be like this:

<form // Note the missing >
onSubmit=
{event => { // this is a function returned as a React child
  event.preventDefault();
  if (!user.name || !user.username) return;

  props.addUser(user);
  setUser(initialFormState);
}}> // form opening tag closed here

This actually is not a React issue, but an invalid HTML causing React to throw an error, as it can't parse and render JSX.


问:
Change class on scrolling through div
I have a sticky sidebar like this:

```<code><ul class = "cars">
       <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li>
    ......
        <li class=""><a href="javascript:void(0)" class="model" data-id="2"> Mersedes </a></li>
</ul>
</code>```

And table like this:

```<code>     <div class="element-title" id="car-category-1">BMW</div>
.....
     <div class="element-title" id="car-category-2">Mersedes</div>
</code>```

Now what I am trying to do:

 Scrolling through the
 should change the class of
 of BMW to .active

 Same for Mersedes, if scroll through
 then change
 with Mersedes to active.

this is jquery for click scroll

```<code>  $(document).on('click', '.model', function () {
        var this_id = $(this).data('id');
        var gotom = setInterval(function () {
            cars_go_to_navtab(this_id);
            clearInterval(gotom);
        }, 400);

        $('.cars li').removeClass('active');
        $(this).parent().addClass('active');
    });
function cars_go_to_navtab(id) {
    var scrolling_div = $('#car-category-' + id);
    $('html, body').animate({
        scrollTop: scrolling_div.offset().top - 70
    }, 500);
}
</code>```

答:
A simple implementation using Jquery. Also, explore the possibilities of Intersection Observer API

$(document).on("scroll", function() {
  var scrollPos = $(document).scrollTop();
  $('#menu a').each(function() {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
      $('#menu ul li a').removeClass("active");
      currLink.addClass("active");
    } else {
      currLink.removeClass("active");
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  font-family: helvetica, sans-serif;
}

.content {
  flex: 1;
  padding-left: 200px;
}

.section {
  background-color: grey;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box;
}

#menu {
  position: fixed;
  top: 0;
  background: #444;
  width: 200px;
}

#menu a {
  padding: 10px;
  display: flex;
  color: #FFF;
  text-decoration: none;
}

h1 {
  font-size: 30px;
  color: #FFF;
}

.active {
  background: #4CAF50;
  color: #FFF;
}</code>```

BMW

Mercedes

        BMW

        Mercedes

```

Title: Change class on scrolling through div

Body:
I have a sticky sidebar like this:

 BMW

    ......

 Mersedes

And table like this:

BMW

.....

Mersedes

Now what I am trying to do:

 Scrolling through the
 should change the class of
 of BMW to .active

 Same for Mersedes, if scroll through
 then change
 with Mersedes to active.

this is jquery for click scroll

  $(document).on('click', '.model', function () {
        var this_id = $(this).data('id');
        var gotom = setInterval(function () {
            cars_go_to_navtab(this_id);
            clearInterval(gotom);
        }, 400);

        $('.cars li').removeClass('active');
        $(this).parent().addClass('active');
    });
function cars_go_to_navtab(id) {
    var scrolling_div = $('#car-category-' + id);
    $('html, body').animate({
        scrollTop: scrolling_div.offset().top - 70
    }, 500);
}

Body:
A simple implementation using Jquery. Also, explore the possibilities of Intersection Observer API

$(document).on("scroll", function() {
  var scrollPos = $(document).scrollTop();
  $('#menu a').each(function() {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
      $('#menu ul li a').removeClass("active");
      currLink.addClass("active");
    } else {
      currLink.removeClass("active");
    }
  });
});

* {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  font-family: helvetica, sans-serif;
}

.content {
  flex: 1;
  padding-left: 200px;
}

.section {
  background-color: grey;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box;
}

#menu {
  position: fixed;
  top: 0;
  background: #444;
  width: 200px;
}

#menu a {
  padding: 10px;
  display: flex;
  color: #FFF;
  text-decoration: none;
}

h1 {
  font-size: 30px;
  color: #FFF;
}

.active {
  background: #4CAF50;
  color: #FFF;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container">
  <div id="menu">
    <ul>
      <li><a class="active" href="#bmw">BMW</a>
      </li>
      <li><a href="#mercedes">Mercedes</a></li>
    </ul>
  </div>
  <div class="content">
    <div class="section" id="bmw">
      <h1>
        BMW
      </h1>
    </div>
    <div class="section" id="mercedes">
      <h1>
        Mercedes
      </h1>
    </div>
  </div>
</div>


问:
Creating a transparency group or setting graphics state soft mask with PDFBox
I have a grayscale image that serves as a soft mask and I want to use it on a group of PDF objects (images or paths).

The mask and the objects do not necessarily use the same transformation matrix, and there might be more than one object to mask, so that excludes the possibility of using the SMask attribute of the ImageXObject dictionary.

So after reading some of the PDF specification, it looks like I should do the following: create a transparency group with the objects to mask, then draw it with the soft mask set on the graphics state.

Will that work? How can I achieve this, preferably with PDFBox?

Here's an example. I have these two images: the mask and another image.

The mask image is 200x200. It is drawn with the matrix [[4 0 100] [0 4 100]].

The image is 400x300. It is drawn with the matrix [[2 0 100] [0 2 150]].

Additionally, a 400x400 black square is drawn below the image with no transform matrix.

So a transparency group is created with the image and the square, then it's drawn with the mask image. Here's the expected result:

Rather ugly as far as the effect goes, but that's just an example.

答:
As far as I can see establishing an extended graphics state soft mask is a very manual task in PDFBox. You can do so as follows:

try (   PDDocument document = new PDDocument()  ) {
    final PDImageXObject image = RETRIEVE PHOTO IMAGE;
    final PDImageXObject mask = RETRIEVE MASK IMAGE;

    PDTransparencyGroupAttributes transparencyGroupAttributes = new PDTransparencyGroupAttributes();
    transparencyGroupAttributes.getCOSObject().setItem(COSName.CS, COSName.DEVICEGRAY);

    PDTransparencyGroup transparencyGroup = new PDTransparencyGroup(document);
    transparencyGroup.setBBox(PDRectangle.A4);
    transparencyGroup.setResources(new PDResources());
    transparencyGroup.getCOSObject().setItem(COSName.GROUP, transparencyGroupAttributes);
    try (   PDFormContentStream canvas = new PDFormContentStream(transparencyGroup)   ) {
        canvas.drawImage(mask, new Matrix(400, 0, 0, 400, 100, 100));
    }

    COSDictionary softMaskDictionary = new COSDictionary();
    softMaskDictionary.setItem(COSName.S, COSName.LUMINOSITY);
    softMaskDictionary.setItem(COSName.G, transparencyGroup);

    PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
    extendedGraphicsState.getCOSObject().setItem(COSName.SMASK, softMaskDictionary);

    PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);
    try (   PDPageContentStream canvas = new PDPageContentStream(document, page)   ) {
        canvas.saveGraphicsState();
        canvas.setGraphicsStateParameters(extendedGraphicsState);
        canvas.setNonStrokingColor(Color.BLACK);
        canvas.addRect(100, 100, 400, 400);
        canvas.fill();
        canvas.drawImage(image, new Matrix(400, 0, 0, 300, 100, 150));
        canvas.restoreGraphicsState();
    }

    document.save(new File(RESULT_FOLDER, "SoftMaskedImageAndRectangle.pdf"));
}
```

The result:

If I were you, though, I would not use a bitmap image for the soft mask but instead a PDF gradient. The result most likely will be much less pixelated.

Body:
As far as I can see establishing an extended graphics state soft mask is a very manual task in PDFBox. You can do so as follows:

try (   PDDocument document = new PDDocument()  ) {
    final PDImageXObject image = RETRIEVE PHOTO IMAGE;
    final PDImageXObject mask = RETRIEVE MASK IMAGE;

    PDTransparencyGroupAttributes transparencyGroupAttributes = new PDTransparencyGroupAttributes();
    transparencyGroupAttributes.getCOSObject().setItem(COSName.CS, COSName.DEVICEGRAY);

    PDTransparencyGroup transparencyGroup = new PDTransparencyGroup(document);
    transparencyGroup.setBBox(PDRectangle.A4);
    transparencyGroup.setResources(new PDResources());
    transparencyGroup.getCOSObject().setItem(COSName.GROUP, transparencyGroupAttributes);
    try (   PDFormContentStream canvas = new PDFormContentStream(transparencyGroup)   ) {
        canvas.drawImage(mask, new Matrix(400, 0, 0, 400, 100, 100));
    }

    COSDictionary softMaskDictionary = new COSDictionary();
    softMaskDictionary.setItem(COSName.S, COSName.LUMINOSITY);
    softMaskDictionary.setItem(COSName.G, transparencyGroup);

    PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
    extendedGraphicsState.getCOSObject().setItem(COSName.SMASK, softMaskDictionary);

    PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);
    try (   PDPageContentStream canvas = new PDPageContentStream(document, page)   ) {
        canvas.saveGraphicsState();
        canvas.setGraphicsStateParameters(extendedGraphicsState);
        canvas.setNonStrokingColor(Color.BLACK);
        canvas.addRect(100, 100, 400, 400);
        canvas.fill();
        canvas.drawImage(image, new Matrix(400, 0, 0, 300, 100, 150));
        canvas.restoreGraphicsState();
    }

    document.save(new File(RESULT_FOLDER, "SoftMaskedImageAndRectangle.pdf"));
}

The result:

If I were you, though, I would not use a bitmap image for the soft mask but instead a PDF gradient. The result most likely will be much less pixelated.


问:
A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'
```<code>import 'dart:async';
import 'question.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

String opentdb = 'https://opentdb.com/api.php?amount=15&type=boolean';

class QuestionServices {
  Future<List<Question>> getData() async {
    List<Question> questions;
    String link = opentdb;
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data['results'] as List;
      print(rest);
      questions =
          rest.map<Question>((json) => Question.fromJson(json)).toList();
    }
    print("List Size: ${questions.length}");
    // _questions = questions;
    return questions;
  }

  List<Question> newQuestions = getData();
}
</code>```

```<code>class Question {
  final String question;
  final bool answer;

  Question({this.question, this.answer});

  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      question: json['question'] as String,
      answer: json['correct_answer'] as bool,
    );
  }
}
</code>```

I am trying to create a list of questions from a JSON database but whenever I try to get the returned list I get the error:

```<code>"A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'."
</code>```

I am unsure why the List I'm returning is giving out that error. Is there maybe a different way to get a json to a list?

答:
```<code>List<Question> getData() async { // remove Future
    List<Question> questions;
    String link = opentdb;
 ...

//how to access now you will get instance of List<Question>

getData().then((List<Question> newQuestions){

})
</code>```

Body:
import 'dart:async';
import 'question.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

String opentdb = 'https://opentdb.com/api.php?amount=15&type=boolean';

class QuestionServices {
  Future<List<Question>> getData() async {
    List<Question> questions;
    String link = opentdb;
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data['results'] as List;
      print(rest);
      questions =
          rest.map<Question>((json) => Question.fromJson(json)).toList();
    }
    print("List Size: ${questions.length}");
    // _questions = questions;
    return questions;
  }

  List<Question> newQuestions = getData();
}

class Question {
  final String question;
  final bool answer;

  Question({this.question, this.answer});

  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      question: json['question'] as String,
      answer: json['correct_answer'] as bool,
    );
  }
}

I am trying to create a list of questions from a JSON database but whenever I try to get the returned list I get the error:

"A value of type 'Future<List<Question>>' can't be assigned to a variable of type 'List<Question>'."

I am unsure why the List I'm returning is giving out that error. Is there maybe a different way to get a json to a list?


答:
Technically spoken: You dont need the instance attributes, color and ID are already available:

```<code>class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.rect = rect

        print(self.ID)
        print(self.color)

p = Particle(None)
</code>```

Output:

```<code>1
(255, 255, 0)
</code>```

Note: In case you really need color and ID as instance variables, use a another name:

```<code>class Particle:
    color = (255, 255, 0)
    ID = 0
    def __init__(self, rect):
        Particle.ID += 1
        self.rect = rect
        self.pcolor = self.color
        self.pID = self.ID
</code>```

Title: How to fix a "NameError: name 'color' is not defined"?

Body:
here is my code :

size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

Body:
Technically spoken: You dont need the instance attributes, color and ID are already available:

class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.rect = rect

        print(self.ID)
        print(self.color)

p = Particle(None)

Output:

1
(255, 255, 0)

Note: In case you really need color and ID as instance variables, use a another name:

class Particle:
    color = (255, 255, 0)
    ID = 0
    def __init__(self, rect):
        Particle.ID += 1
        self.rect = rect
        self.pcolor = self.color
        self.pID = self.ID


问:
How to devide loop into several stages
i have a loop for 2001 files:

for i in tqdm(result_file_list):
    df = read_pickle(file_path, i)
    final_df += df
```

<p>and i want to save final_df every 100 files, whats the easiest way yo do it?</p>

<p>i have in mind only smth like this:</p>

<pre class="lang-py prettyprint-override"><code>for i in tqdm(result_file_list[:100]):
    df = read_pickle(file_path, i)
    final_df += df
</code>```

for i in tqdm(result_file_list[100:200]):
    df = read_pickle(file_path, i)
    final_df += df
```

答:
This should help, calculate how many iterations (your stages)</p>

```<code>import math

#2001 / 100 = 20.01 (21 iteration, round it up 20.01 > 21)

stages = math.ceil(2001/100.0)

#for z in xrange(stages): #python2
for z in range(stages): #python3
    for i in tqdm(result_file_list[i*x: (i*z)+100]):
        your_code()
</code>```

Title: How to devide loop into several stages

Body:
i have a loop for 2001 files:

for i in tqdm(result_file_list):
    df = read_pickle(file_path, i)
    final_df += df

and i want to save final_df every 100 files, whats the easiest way yo do it?

i have in mind only smth like this:

for i in tqdm(result_file_list[:100]):
    df = read_pickle(file_path, i)
    final_df += df

for i in tqdm(result_file_list[100:200]):
    df = read_pickle(file_path, i)
    final_df += df

Body:
This should help, calculate how many iterations (your stages)

import math

#2001 / 100 = 20.01 (21 iteration, round it up 20.01 > 21)

stages = math.ceil(2001/100.0)

#for z in xrange(stages): #python2
for z in range(stages): #python3
    for i in tqdm(result_file_list[i*x: (i*z)+100]):
        your_code()


问:
Getting black diamond question mark while reading csv file in node js
I have a csv file with text as: The right curly single quote mark is ’ and right curly double quote mark is ”.

I am getting text as: The right curly single quote mark is � and right curly double quote mark is �.

I have used node fs module to read file with utf8 encoding as describe below:

```<code>var express = require('express');
var app = express();
var fs = require("fs");

app.get('/', function (req, res) {
  var data = fs.readFileSync('abc.csv',{encoding: 'utf8'});
  res.send(data);
})

var server = app.listen(8080, function () {});
</code>```

Can anyone help me to fetch correct data for curly single quote and curly double quote?

答:
First thing, utf8 is actually the default, so you shouldn't even need to pass it as an option

Please make sure to save the CSV file as a CSV utf-8. This will help you out to resolve the issue.

```<code>fs.appendFile('log.csv', '\ufeffThis is an example with accents : é � è à ', 'utf8', function(err) {
    if (err) throw err;
});
</code>```

now if you see

```<code>$ file -I log.csv
$ log.csv: text/plain; charset=utf-8
</code>```

Another way,
You can manually use utf8 module from npm to encode/decode the string.

Body:
I have a csv file with text as: The right curly single quote mark is ’ and right curly double quote mark is ”.

I am getting text as: The right curly single quote mark is � and right curly double quote mark is �.

I have used node fs module to read file with utf8 encoding as describe below:

var express = require('express');
var app = express();
var fs = require("fs");

app.get('/', function (req, res) {
  var data = fs.readFileSync('abc.csv',{encoding: 'utf8'});
  res.send(data);
})

var server = app.listen(8080, function () {});

Can anyone help me to fetch correct data for curly single quote and curly double quote?

Body:
First thing, utf8 is actually the default, so you shouldn't even need to pass it as an option

Please make sure to save the CSV file as a CSV utf-8. This will help you out to resolve the issue.

fs.appendFile('log.csv', '\ufeffThis is an example with accents : é � è à ', 'utf8', function(err) {
    if (err) throw err;
});

now if you see

$ file -I log.csv
$ log.csv: text/plain; charset=utf-8

Another way,
You can manually use utf8 module from npm to encode/decode the string.


问:
How to import python files in google colaboratory?
I am trying to run my program on Google Colab; where my code make use of .py files written seprately.

In normal system I have all files inside one folder and it works using import xyz, but when I tried using same folder in Google drive it gives import error.

答:
Something I've used when I have multiple python scripts and want to automatically import through code is to set it up as a package and clone from the repo.

First set up the scripts in a repo with a setup.py and __init__.py files (obviously).

Then add this to the top of your notebook:

```<code>!rm -rf <repo-name>  # in case you need to refresh after pushing changes
!git clone https://github.com/<user>/<repo-name>.git
</code>```

Then install the package:

```<code>!pip install ./<repo-name>
</code>```

Now conveniently import functions or whatever:

```<code>from <app-name>.<module> import <function>
</code>```

Body:
Something I've used when I have multiple python scripts and want to automatically import through code is to set it up as a package and clone from the repo.

First set up the scripts in a repo with a setup.py and __init__.py files (obviously).

Then add this to the top of your notebook:

!rm -rf <repo-name>  # in case you need to refresh after pushing changes
!git clone https://github.com/<user>/<repo-name>.git

Then install the package:

!pip install ./<repo-name>

Now conveniently import functions or whatever:

from <app-name>.<module> import <function>


答: I think this is a Apple error. you just need to simply refresh the website again and again or need to use another browser.</p>

Title: Invalid certificate (CSR)

Body:
I generate .certSigningRequest file via Keychain Access (Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority..., I fill in my mail and I save it to disk).

When I log into Apple developer account and try to generate Certificate with it I get message: "Invalid CSR - Invalid Certificate"

I did this number of times previously with my previous Mac but it is not working on my new system.

What am I doing wrong? I have followed exact steps https://help.apple.com/developer-account/#/devbfa00fef7


答:
In the method distance you are passing the other point as variable with the name x (Not a very good name) and can access its fields and methods with that variable:

```<code>public double distance(Point x) {
     double currentPointX = this.getX();
     double otherPointX = x.getX();
}
</code>```

The same for the Y-value and you can then do your math with those values.

Title: How to compute distance between my original and supplied point in Java

Body:
public class Point {

private double X, Y;

  public Point() {
    setPoint(0.0,0.0);
  }

   public Point (double X, double Y) {
      setPoint(X,Y);
   }

  public void setPoint(double X, double Y) {
    this.X = X;
    this.Y = Y;
  }
  public double getX() {

    return this.X;
  }
  public double getY() {

    return this.Y;
  }

 /**
     * Compute the distance of this Point to the supplied Point x.
     *
     * @param x  Point from which the distance should be measured.
     * @return   The distance between x and this instance
     */
    public double distance(Point x) {

    double d= Math.pow(this.X-X,2)+Math.pow(this.Y-Y,2);
    return Math.sqrt(d);
}

I'm trying to compute the distance of my "original point" and my supplied point x. I'm not exactly sure if i'm doing this right. My main concern is:

How do I refer to the coordinates of my original point and the supplied point? The maths here is basic, so I'm confident with that.

Any help is appreciated. PS I'm new to Java.

So also I was thinking of assigning my point the value within the function:

public double distance(Point x) {

    Point x = new Point(X,Y);
    double d= Math.pow(this.X-x.X,2)+Math.pow(this.Y-x.Y,2);
    return Math.sqrt(d);
}

Would this be fine?

Body:
In the method distance you are passing the other point as variable with the name x (Not a very good name) and can access its fields and methods with that variable:

public double distance(Point x) {
     double currentPointX = this.getX();
     double otherPointX = x.getX();
}

The same for the Y-value and you can then do your math with those values.