问:
Getting 'Async Storage has been extracted' warning when I'm not using Async Storage
I'm getting one of the annoying yellow warning in my React Native app about Async Storage having been extracted from react-native core and will be removed yada yada yada. I'm not using anything with Async Storage (although some modules might be) and I haven't installed it ever. Why am I getting this warning when I'm not using it at all? Oh, and how do I get rid of it?

package.json

```<code>{
  "name": "LoganTransitApp3",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.8.3",
    "react-fetch-hook": "^1.6.0-alpha.2",
    "react-native": "0.59.8",
    "react-native-geolocation-service": "^2.0.1",
    "react-native-gesture-handler": "^1.2.2",
    "react-native-iphone-x-helper": "^1.2.1",
    "react-native-maps": "^0.24.2",
    "react-native-permissions": "^1.1.1",
    "react-native-reanimated": "^1.0.1",
    "react-native-rename": "^2.4.1",
    "react-native-svg": "^9.4.0",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.11.0",
    "react-navigation-custom-bottom-tab-component": "^1.1.1",
    "react-navigation-tabs": "^2.1.3",
    "reactn": "^2.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.4.4",
    "@babel/runtime": "^7.4.4",
    "babel-jest": "^24.8.0",
    "eslint-config-rallycoding": "^3.2.0",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.54.0",
    "react-test-renderer": "16.8.3"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答:
Your issue is likely related to the react-native-permissions package. The android implementation uses AsyncStorage
:

import { AsyncStorage, NativeModules, PermissionsAndroid } from 'react-native'

permission.android.js

There is an open Pull Request that fixes this, but it has not been merged yet (Seems that the author is working on a big update of the library, so there have been no updates to master for over a year. Consider forking or looking into another library).

Body:
I'm getting one of the annoying yellow warning in my React Native app about Async Storage having been extracted from react-native core and will be removed yada yada yada. I'm not using anything with Async Storage (although some modules might be) and I haven't installed it ever. Why am I getting this warning when I'm not using it at all? Oh, and how do I get rid of it?

package.json

{
  "name": "LoganTransitApp3",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.8.3",
    "react-fetch-hook": "^1.6.0-alpha.2",
    "react-native": "0.59.8",
    "react-native-geolocation-service": "^2.0.1",
    "react-native-gesture-handler": "^1.2.2",
    "react-native-iphone-x-helper": "^1.2.1",
    "react-native-maps": "^0.24.2",
    "react-native-permissions": "^1.1.1",
    "react-native-reanimated": "^1.0.1",
    "react-native-rename": "^2.4.1",
    "react-native-svg": "^9.4.0",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.11.0",
    "react-navigation-custom-bottom-tab-component": "^1.1.1",
    "react-navigation-tabs": "^2.1.3",
    "reactn": "^2.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.4.4",
    "@babel/runtime": "^7.4.4",
    "babel-jest": "^24.8.0",
    "eslint-config-rallycoding": "^3.2.0",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.54.0",
    "react-test-renderer": "16.8.3"
  },
  "jest": {
    "preset": "react-native"
  }
}


来源: stackexchange

问:
I have some questions about the way to assign values to the std::array
I'm learning C++ on codesdope.com and I have read a document on another website, learncpp.com. But these two websites have different ways to assign values to the array.

```<code>//codesdope.com

std::array<int,5> n  {{1,2,3,4,5}};
</code>```

```<code>//learncpp.com

std::array<int,5> n = {1,2,3,4,5};
</code>```

Which way is more accurate? Which way should I choose? What is the difference between them?

答:
Both versions have the same assembly code:

```<code>    std::array<int,5> n {{1,2,3,4,5}};

    mov     rcx, qword ptr [.L__const.main.n]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n+16]
    mov     dword ptr [rbp - 8], edx
</code>```

the second style:

```<code>    std::array<int,5> n2 {1,2,3,4,5};

    mov     rcx, qword ptr [.L__const.main.n2]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n2+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n2+16]
    mov     dword ptr [rbp - 8], edx
</code>```

meaning they both have the same performance.
The second is better, because it is more readable.

ContentLicense: CC BY-SA 4.0

Body:
I'm learning C++ on codesdope.com and I have read a document on another website, learncpp.com. But these two websites have different ways to assign values to the array.

//codesdope.com

std::array<int,5> n  {{1,2,3,4,5}};

//learncpp.com

std::array<int,5> n = {1,2,3,4,5};

Which way is more accurate? Which way should I choose? What is the difference between them?

Body:
Both versions have the same assembly code:

    std::array<int,5> n {{1,2,3,4,5}};

    mov     rcx, qword ptr [.L__const.main.n]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n+16]
    mov     dword ptr [rbp - 8], edx

the second style:

    std::array<int,5> n2 {1,2,3,4,5};

    mov     rcx, qword ptr [.L__const.main.n2]
    mov     qword ptr [rbp - 24], rcx
    mov     rcx, qword ptr [.L__const.main.n2+8]
    mov     qword ptr [rbp - 16], rcx
    mov     edx, dword ptr [.L__const.main.n2+16]
    mov     dword ptr [rbp - 8], edx

meaning they both have the same performance.
The second is better, because it is more readable.


问:
How to test if email was sent after executing celery task
I'm using Django 1.10 and Celery 4.1

I have a shared_task which sends an email to the user.

```<code># myapp/tasks.py
@shared_task
def notify_user(user_id):
    # TODO: send email and do other stuff here
    user = get_object_or_404(User, pk=user_id)

    send_mail(
        'Subject',
        'Body',
        'from@example.com',
        [user.email],
    )
</code>```

I have another file which contains a function that calls puts that tasks into the queue.

```<code># myapp/utils.py
# ...
def update_queue(self):
    # increment no_of_used_referrals by 1
    if no_of_used_referrals == 5:
        notify_user.apply_async((self.user_id,))
    else:
        notify_user.apply_async((self.user_id,), eta=new_eta)
</code>```

Now I am trying to test whether calling update_queue() (where all required checks passes) sends an email to the user when its executed.

I tried to do the following:

```<code># myapp/tests.py
def update_queue_should_call_notify_user_immediately_after_five_referrals_were_used(self):
    with unittest.mock.patch('myapp.tasks.notify_user.apply_async') as notify_user_mock:
        # ...
        for _ in range(5):
            entry.update_queue()
        self.assertTrue(notify_user_mock.called)
        notify_user_mock.assert_called_with((user_id,))
    # TODO: check if email was sent

    # I tried using :
    # self.assertEqual(len(mail.outbox), 1)
    # but it fails with error saying 0 != 1
def test_notify_user_should_send_an_email(self):
    notify_user.apply_async((user_id,))

    # I tried using:
    # self.assertEqual(len(mail.outbox), 1)
    # but it fails with error saying 0 != 1
</code>```

I have set EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' in my project settings.

Can someone please tell me what is wrong with what I am doing and how to correctly test this case?

EDIT
I have updated my code where I excluded mocking - as suggested by @DanielRoseman.

EDIT2
Please see updated files above.

I am simulating referral system. Once 5 referral links associated with a particular user have been used, user get's some nice feature to their profile. Otherwise they have to wait for a specific time, which I set using eta argument on apply_async.

Every time I call update_queue I check if the number of referals is equal to 5(please see updated code above).

If it is - I want to call notify_user immediately, without passing eta argument value.

If it is not - I increment number of used referral links, revoke old notify_user task, create new notify_user task with new eta argument value.

In order to test that I am simulating that behaviour in for-loop, and I want to test whether after 5 iterations(equal to 5 used referral links) an email was sent to the user (for test purposes I use in-memory backend for email).

答:
tasks.py

```<code>from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.contrib.auth import get_user_model

from accounts.models import Token
from celery import shared_task

@shared_task(bind=True)
def send_login_email_task(self, email):
    try:
        uid = str(uuid.uuid4())
        Token.objects.create(email=email, uid=uid)
        current_site = 'localhost:8000'
        mail_subject = 'Activate your account.'
        message = render_to_string('accounts/login_activation_email.html', {
            'domain': current_site,
            'uid': uid
        })
        print('called')
        email = EmailMessage(mail_subject, message, to=[email])
        email.send()
    except Token.DoesNotExist:
        logging.warning(
            "Tried to send activation email to non-existing user '%s'", email)
    except smtplib.SMTPException as exc:
        raise self.retry(exc=exc)
</code>```

test_tasks.py

```<code>from django.test import TestCase
from unittest.mock import patch
from django.contrib.auth import get_user_model
from celery.exceptions import Retry
from proj.celery import App
import smtplib
import uuid

import accounts.tasks
from accounts.models import Token
@patch('accounts.tasks.EmailMessage')
def test_send_login_email_task(self, mock_email_message):

    # call task
    token = Token.objects.get(email=self.email, uid=self.uid)
    print(token.email)
    accounts.tasks.send_login_email_task.apply_async((token.email,))
    self.assertEqual(mock_email_message.called, True)

    # patch EmailMessage
    print(mock_email_message.call_args)
    args, kwargs = mock_email_message.call_args
    subject = args[0]
    self.assertEqual(subject, 'Activate your account.')
    self.assertEqual(kwargs, {'to': ['ama@example.com']})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Django 1.10 and Celery 4.1

I have a shared_task which sends an email to the user.

# myapp/tasks.py
@shared_task
def notify_user(user_id):
    # TODO: send email and do other stuff here
    user = get_object_or_404(User, pk=user_id)

    send_mail(
        'Subject',
        'Body',
        'from@example.com',
        [user.email],
    )

I have another file which contains a function that calls puts that tasks into the queue.

# myapp/utils.py
# ...
def update_queue(self):
    # increment no_of_used_referrals by 1
    if no_of_used_referrals == 5:
        notify_user.apply_async((self.user_id,))
    else:
        notify_user.apply_async((self.user_id,), eta=new_eta)

Now I am trying to test whether calling update_queue() (where all required checks passes) sends an email to the user when its executed.

I tried to do the following:

# myapp/tests.py
def update_queue_should_call_notify_user_immediately_after_five_referrals_were_used(self):
    with unittest.mock.patch('myapp.tasks.notify_user.apply_async') as notify_user_mock:
        # ...
        for _ in range(5):
            entry.update_queue()
        self.assertTrue(notify_user_mock.called)
        notify_user_mock.assert_called_with((user_id,))
    # TODO: check if email was sent

    # I tried using :
    # self.assertEqual(len(mail.outbox), 1)
    # but it fails with error saying 0 != 1
def test_notify_user_should_send_an_email(self):
    notify_user.apply_async((user_id,))

    # I tried using:
    # self.assertEqual(len(mail.outbox), 1)
    # but it fails with error saying 0 != 1

I have set EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' in my project settings.

Can someone please tell me what is wrong with what I am doing and how to correctly test this case?

EDIT
I have updated my code where I excluded mocking - as suggested by @DanielRoseman.

EDIT2
Please see updated files above.

I am simulating referral system. Once 5 referral links associated with a particular user have been used, user get's some nice feature to their profile. Otherwise they have to wait for a specific time, which I set using eta argument on apply_async.

Every time I call update_queue I check if the number of referals is equal to 5(please see updated code above).

If it is - I want to call notify_user immediately, without passing eta argument value.

If it is not - I increment number of used referral links, revoke old notify_user task, create new notify_user task with new eta argument value.

In order to test that I am simulating that behaviour in for-loop, and I want to test whether after 5 iterations(equal to 5 used referral links) an email was sent to the user (for test purposes I use in-memory backend for email).

Body:
tasks.py

from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.contrib.auth import get_user_model

from accounts.models import Token
from celery import shared_task

@shared_task(bind=True)
def send_login_email_task(self, email):
    try:
        uid = str(uuid.uuid4())
        Token.objects.create(email=email, uid=uid)
        current_site = 'localhost:8000'
        mail_subject = 'Activate your account.'
        message = render_to_string('accounts/login_activation_email.html', {
            'domain': current_site,
            'uid': uid
        })
        print('called')
        email = EmailMessage(mail_subject, message, to=[email])
        email.send()
    except Token.DoesNotExist:
        logging.warning(
            "Tried to send activation email to non-existing user '%s'", email)
    except smtplib.SMTPException as exc:
        raise self.retry(exc=exc)

test_tasks.py

from django.test import TestCase
from unittest.mock import patch
from django.contrib.auth import get_user_model
from celery.exceptions import Retry
from proj.celery import App
import smtplib
import uuid

import accounts.tasks
from accounts.models import Token
@patch('accounts.tasks.EmailMessage')
def test_send_login_email_task(self, mock_email_message):

    # call task
    token = Token.objects.get(email=self.email, uid=self.uid)
    print(token.email)
    accounts.tasks.send_login_email_task.apply_async((token.email,))
    self.assertEqual(mock_email_message.called, True)

    # patch EmailMessage
    print(mock_email_message.call_args)
    args, kwargs = mock_email_message.call_args
    subject = args[0]
    self.assertEqual(subject, 'Activate your account.')
    self.assertEqual(kwargs, {'to': ['ama@example.com']})


问:
can't use passed prop in child's method:{} vue.js
I pass the array to child as prop. And trying to use it in google map method. But when I use it inside initMap: function the array being empty.

in parent

```<code><div class="mapWrap">
    <mapping :articles="filterArticles" />
</div>

computed: {
  filterArticles(){
   let api = this.$store.getters.articles;

   let filteredStates = api.filter((article) => {
       return (this.keyword.length === 0 || article.address.includes(this.keyword)) &&
       (this.regions.length === 0 || this.regions.includes(article.region)) &&
       (this.rooms.length === 0 || this.rooms.includes(article.rooms1)) &&
       (this.city.length === 0 || this.city.includes(article.city))
   });

   return filteredStates;
  },
}
</code>```

in child

```<code>props: {
    articles: {
        type:Array
    },
},
name:"mapping",
data(){
    return {
        marker:[],
    }
},
mounted(){
    this.initMap();
},
methods: {
    initMap: function() {
        var mapOptions = {
            mapTypeId: 'roadmap',
            center: new google.maps.LatLng(35.652832, 139.839478),
            zoom: 10
        };

        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        var articles = this.articles;
        console.log(articles);

    },
},
</code>```

The way I am doing it wrong? Because prop has the items but when I put it inside the initMap method, it starts being empty...

答:
I have tried to trace the code and from what you have, it will work in most cases EXCEPT if the data that you have fetched using this.$store.getters.articles is async. Ideally, you should not be relying on the child component's mount event because it can get mounted way before you can display any data. To verify that, you can add a console.log(this.articles) inside the mounted hook and see that it's most likely empty.

What I suggest you do is, given that in the parent component you have articles as a computed property (which is reactive), you should also call the initMap inside the child every time the prop articles changes. The easiest way to do just that is with a watcher inside the child component:

```<code>watch: {
  articles () {
    this.initMap()
  }
}
</code>```

Body:
I pass the array to child as prop. And trying to use it in google map method. But when I use it inside initMap: function the array being empty.

in parent

    <mapping :articles="filterArticles" />

computed: {
  filterArticles(){
   let api = this.$store.getters.articles;

   let filteredStates = api.filter((article) => {
       return (this.keyword.length === 0 || article.address.includes(this.keyword)) &&
       (this.regions.length === 0 || this.regions.includes(article.region)) &&
       (this.rooms.length === 0 || this.rooms.includes(article.rooms1)) &&
       (this.city.length === 0 || this.city.includes(article.city))
   });

   return filteredStates;
  },
}

in child

props: {
    articles: {
        type:Array
    },
},
name:"mapping",
data(){
    return {
        marker:[],
    }
},
mounted(){
    this.initMap();
},
methods: {
    initMap: function() {
        var mapOptions = {
            mapTypeId: 'roadmap',
            center: new google.maps.LatLng(35.652832, 139.839478),
            zoom: 10
        };

        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        var articles = this.articles;
        console.log(articles);

    },
},

The way I am doing it wrong? Because prop has the items but when I put it inside the initMap method, it starts being empty...

Body:
I have tried to trace the code and from what you have, it will work in most cases EXCEPT if the data that you have fetched using this.$store.getters.articles is async. Ideally, you should not be relying on the child component's mount event because it can get mounted way before you can display any data. To verify that, you can add a console.log(this.articles) inside the mounted hook and see that it's most likely empty.

What I suggest you do is, given that in the parent component you have articles as a computed property (which is reactive), you should also call the initMap inside the child every time the prop articles changes. The easiest way to do just that is with a watcher inside the child component:

watch: {
  articles () {
    this.initMap()
  }
}


问:
How to know what column has been resized when using TableColumnModelListener
I'm using TableColumnModelListener on a JTable to know when a Column is resized.

I took a look at the ChangeEvent object inside the columnMarginChanged(ChangeEvent e) method, but I didn't found a way to know what column has been resized.

Is there a way?

答:
I didn't found a way to know what column has been resized.

In the columnMarginChanged() method you can use:

```<code>TableColumn resizingColumn = table.getTableHeader().getResizingColumn();
</code>```

Body:
I didn't found a way to know what column has been resized.

In the columnMarginChanged() method you can use:

TableColumn resizingColumn = table.getTableHeader().getResizingColumn();


问:
How can I view Arabic/Persian numbers in a HTML page with strict doctype?
I have an HTML page that is right-to-left. When I don't use any doctype, my numbers are in Arabic/Persian, but when I use strict mode they turn to English.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">
</code>```

Before adding doctype:

After adding doctype:

also I added these meta tags to my page:

```<code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="fa" />
</code>```

So how can I view Arabic numbers in a page with strict doctype (in IE because Firefox doesn't show Arabic numbers anyway)?

答:
Assuming you want an XHTML 1.0 Strict document:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fa" lang="fa" dir="rtl">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Title here</title>
  </head>

  <body>
    <p>Text here</p>
  </body>
</html>
</code>```

Here's an equivalent HTML 4.01 Strict document:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html lang="fa" dir="rtl">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Title here</title>
  </head>

  <body>
    <p>Text here</p>
  </body>
</html>
</code>```

Here's an equivalent HTML5 page, just for comparison purposes.

```<code><!DOCTYPE html>
<html lang="fa" dir="rtl">
  <head>
    <meta charset="UTF-8" />
    <title>Title here</title>
  </head>

  <body>
    <p>Text here</p>
  </body>
</html>
</code>```

Body:
I have an HTML page that is right-to-left. When I don't use any doctype, my numbers are in Arabic/Persian, but when I use strict mode they turn to English.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">

Before adding doctype:

After adding doctype:

also I added these meta tags to my page:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="fa" />

So how can I view Arabic numbers in a page with strict doctype (in IE because Firefox doesn't show Arabic numbers anyway)?

Body:
Assuming you want an XHTML 1.0 Strict document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fa" lang="fa" dir="rtl">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Title here</title>
  </head>

  <body>
    <p>Text here</p>
  </body>
</html>

Here's an equivalent HTML 4.01 Strict document:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html lang="fa" dir="rtl">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Title here</title>
  </head>

  <body>
    <p>Text here</p>
  </body>
</html>

Here's an equivalent HTML5 page, just for comparison purposes.

<!DOCTYPE html>
<html lang="fa" dir="rtl">
  <head>
    <meta charset="UTF-8" />
    <title>Title here</title>
  </head>

  <body>
    <p>Text here</p>
  </body>
</html>


问:
TypeScript is referencing non-static method
I need to load a module from the root, so I am using require.main.require() to do so. Since import cannot access the root, I need to use require. However, this is referencing the wrong connect() method:

```<code>export class MongoClient extends EventEmitter {
  connect(callback: MongoCallback<MongoClient>): void;
}
</code>```

What I need is for it to reference the static method:

```<code>export class MongoClient extends EventEmitter {
  static connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
}
</code>```

The code runs fine when compiled and executed with node, it's just that it is showing an error in the editor. This is what I am doing:

```<code>declare type MongoClient = import('mongodb').MongoClient

const mongo = require.main && require.main.require('mongodb')
const MongoClient: MongoClient = mongo.MongoClient

async function connect() {
  let url = 'mongodb://....'
  await MongoClient.connect(url, { useNewUrlParser: true })
}
</code>```

Expected 0-1 arguments, but got 2.

答:
The problem is that typescript is expecting a member function call as connect is being called on a variable, but the type declaration specifies connect as static.

Since you have to import through require.main which results in an instance as opposed to a static class, the easiest workaround is to re declare connect as an instance member.

```<code>import { MongoClient, MongoClientOptions} from "mongodb";

declare class MyMongoClient extends MongoClient {
  connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
  connect(): Promise<MongoClient>;
}

const mongo = require.main && require.main.require('mongodb')
const mongoClient = mongo.MongoClient  as MyMongoClient

async function connect() {
  let url = 'mongodb://....'
  await mongoClient.connect(url, { useNewUrlParser: true })
}
</code>```

Because of the declare keyword, the actual module will not be pulled in after transpilation.

Body:
I need to load a module from the root, so I am using require.main.require() to do so. Since import cannot access the root, I need to use require. However, this is referencing the wrong connect() method:

export class MongoClient extends EventEmitter {
  connect(callback: MongoCallback<MongoClient>): void;
}

What I need is for it to reference the static method:

export class MongoClient extends EventEmitter {
  static connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
}

The code runs fine when compiled and executed with node, it's just that it is showing an error in the editor. This is what I am doing:

declare type MongoClient = import('mongodb').MongoClient

const mongo = require.main && require.main.require('mongodb')
const MongoClient: MongoClient = mongo.MongoClient

async function connect() {
  let url = 'mongodb://....'
  await MongoClient.connect(url, { useNewUrlParser: true })
}

Expected 0-1 arguments, but got 2.

Body:
The problem is that typescript is expecting a member function call as connect is being called on a variable, but the type declaration specifies connect as static.

Since you have to import through require.main which results in an instance as opposed to a static class, the easiest workaround is to re declare connect as an instance member.

import { MongoClient, MongoClientOptions} from "mongodb";

declare class MyMongoClient extends MongoClient {
  connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
  connect(): Promise<MongoClient>;
}

const mongo = require.main && require.main.require('mongodb')
const mongoClient = mongo.MongoClient  as MyMongoClient

async function connect() {
  let url = 'mongodb://....'
  await mongoClient.connect(url, { useNewUrlParser: true })
}

Because of the declare keyword, the actual module will not be pulled in after transpilation.


问:
how to read a json result using variable in nodejs
I have a nodejs package that I can read in console with

```<code>myapps.app({appId: '123'}).then(console.log); //return json result in console
</code>```

I need to read it using a variable result:

```<code>var result = myapps.app({appId: '123'});
console.log(result);
</code>```

but it's not working!

答:
Because myapps.app is asynchronous function which returns a promise, to use it in a synchronous style code, you must use the async/await syntax, like this

```<code>var result = await myapps.app({appId: '123'})
console.log(result)
</code>```

But make sure this code is wrapped with an async function.

```<code>async function() { ... }
</code>```

Or immediately invoked async function like this

```<code>(async function() { ... })()
</code>```

Here's a resource could help you with async/await https://javascript.info/async-await

Body:
I have a nodejs package that I can read in console with

myapps.app({appId: '123'}).then(console.log); //return json result in console

I need to read it using a variable result:

var result = myapps.app({appId: '123'});
console.log(result);

but it's not working!

Body:
Because myapps.app is asynchronous function which returns a promise, to use it in a synchronous style code, you must use the async/await syntax, like this

var result = await myapps.app({appId: '123'})
console.log(result)

But make sure this code is wrapped with an async function.

async function() { ... }

Or immediately invoked async function like this

(async function() { ... })()

Here's a resource could help you with async/await https://javascript.info/async-await


问:
jQuery form submit: Any way to know what element triggered the submit?
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

```<code>$('form').submit(function() {
    ...code done here to validate form fields
});
</code>```

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

答:
```<code>var myForm =   $('form');
$('input[type="submit"]',myForm).click(function(e) {
    var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
    //do other things here
});
</code>```

EDIT

```<code>.submit(function(event){
    var target = event.originalEvent.explicitOriginalTarget.value;
    //But IE does not have the "explicitOriginalTarget" property
});
</code>```

Body:
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.

$('form').submit(function() {
    ...code done here to validate form fields
});

The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?

Body:
var myForm =   $('form');
$('input[type="submit"]',myForm).click(function(e) {
    var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
    //do other things here
});

EDIT

.submit(function(event){
    var target = event.originalEvent.explicitOriginalTarget.value;
    //But IE does not have the "explicitOriginalTarget" property
});


问:
Unexpected nil when using Chameleon's result to set UIView.backgroundColor
I'm trying to use Chameleon to get analogous colors. The returned array of colors is not nil, each of the 5 elements are also not nil. However the code "tintView.backgroundColor = color" results in "Fatal error: Unexpectedly found nil while unwrapping an Optional value". The first picture shows the code and the non-nil 5 element array returned from a call to Chameleon. The 2nd picture shows the variable as copied from the global array (it's missing data)

1

I've tried setting Chameleon to use Swift 4 as well as Swift 4.2. No difference. I'm currently targeting iPhone 7 running IOS 11.4 What am I missing? Shouldn't this simply work?

Pertinent part of Globals.swift:

```<code>  static var companionColors = ColorSchemeOf(.analogous, color: UIColor.flatYellowDark, isFlatScheme: true)
  static var complimentryColor = UIColor(complementaryFlatColorOf:selectedColor)
  static var initialColorName = "Yellow"
  static var selectedColor = UIColor.flatYellowDark {
      didSet {
          companionColors = ColorSchemeOf(.analogous, color: selectedColor, isFlatScheme: true)
          complimentryColor = UIColor(complementaryFlatColorOf:selectedColor)
        }
    }
</code>```

CommonViewController:

```<code>  class CommonViewController: UIViewController {
    @IBOutlet weak var canvas: UIImageView!
    @IBOutlet weak var tintView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
      let color = Globals.companionColors[1]
      tintView.backgroundColor = color
    }
  }
</code>```

As mentioned the line 'tintView.backgroundColor = color' is throwing the error. Globals.companionColors contains 5 elements of type UIDeviceRGBColor* with RGBA values and a UIColor component. 'color' is an NSObject.

答:
Try removing everything in viewDidAppear and replacing with:

```<code>var colorArray = NSArray(ofColorsWithColorScheme:ColorScheme.Analogous, with:UIColor.flatRedColor(), flatScheme:true)

tintView.backgroundColor = colorArray[1]
</code>```

Make sure Chameleon is installed and imported correctly. Of course you’d modify flatRedColor to the color of your choice but perhaps try this code first and see if it works. My guess is there is a problem in Globals but without seeing the code for it I cannot know for sure.

Body:
I'm trying to use Chameleon to get analogous colors. The returned array of colors is not nil, each of the 5 elements are also not nil. However the code "tintView.backgroundColor = color" results in "Fatal error: Unexpectedly found nil while unwrapping an Optional value". The first picture shows the code and the non-nil 5 element array returned from a call to Chameleon. The 2nd picture shows the variable as copied from the global array (it's missing data)

1

I've tried setting Chameleon to use Swift 4 as well as Swift 4.2. No difference. I'm currently targeting iPhone 7 running IOS 11.4 What am I missing? Shouldn't this simply work?

Pertinent part of Globals.swift:

  static var companionColors = ColorSchemeOf(.analogous, color: UIColor.flatYellowDark, isFlatScheme: true)
  static var complimentryColor = UIColor(complementaryFlatColorOf:selectedColor)
  static var initialColorName = "Yellow"
  static var selectedColor = UIColor.flatYellowDark {
      didSet {
          companionColors = ColorSchemeOf(.analogous, color: selectedColor, isFlatScheme: true)
          complimentryColor = UIColor(complementaryFlatColorOf:selectedColor)
        }
    }

CommonViewController:

  class CommonViewController: UIViewController {
    @IBOutlet weak var canvas: UIImageView!
    @IBOutlet weak var tintView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
      let color = Globals.companionColors[1]
      tintView.backgroundColor = color
    }
  }

As mentioned the line 'tintView.backgroundColor = color' is throwing the error. Globals.companionColors contains 5 elements of type UIDeviceRGBColor* with RGBA values and a UIColor component. 'color' is an NSObject.

Body:
Try removing everything in viewDidAppear and replacing with:

var colorArray = NSArray(ofColorsWithColorScheme:ColorScheme.Analogous, with:UIColor.flatRedColor(), flatScheme:true)

tintView.backgroundColor = colorArray[1]

Make sure Chameleon is installed and imported correctly. Of course you’d modify flatRedColor to the color of your choice but perhaps try this code first and see if it works. My guess is there is a problem in Globals but without seeing the code for it I cannot know for sure.


问:
calculate date difference in hours using reduce
Scenario

I have an array of objects with multiple users with their attendances(in time, out time). I'm trying to use Array.prototype.reduce() to minimize the code.

Following is the sample object/array, the in and out can be more depending on the user.

```<code>"temp": [
        {
            "name": "Test User",
            "id": 35,
            "Attendance": [
                {
                    "id": 34890,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T10:11:06.000Z",
                    "flag": "0\t1\t0\t0\t0",
                    "type": "IN"
                },
                {
                    "id": 34904,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T13:12:23.000Z",
                    "flag": "1\t1\t0\t0\t0",
                    "type": "OUT"
                },
                {
                    "id": 34914,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T13:46:18.000Z",
                    "flag": "0\t1\t0\t0\t0",
                    "type": "IN"
                },
                {
                    "id": 34943,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T16:00:02.000Z",
                    "flag": "1\t1\t0\t0\t0",
                    "type": "OUT"
                },
            ]
        }
  ]
</code>```

Code

Please Ignore few variables which I've kept for logging purpose

```<code>let temp = attendances;
        let mappedAttendance = temp.map(emp => {
          let hours = 0,i=0;
          const empHours = emp.Attendance.reduce((firstEle, secondEle) => {
            if (
              firstEle.type === "IN" &&
              secondEle.type === "OUT" &&
              (firstEle !== undefined && secondEle !== undefined)
            ) {
              hours +=
                Math.abs(
                  new Date(firstEle.time).getTime() -
                    new Date(secondEle.time).getTime()
                ) / 36e5;
            }
            i++;
            return hours;
          });

          return {
            name: emp.name,
            id: emp.id,
            hours: empHours
          };
        });
</code>```

Goal

Also I want the output to be like follow

```<code>       {
            "name": "Test User",
            "id": 35,
            "hours": 3.0213888888888887
        },
</code>```

Problem

It seems it's not calculating well as after first iteration the returning value will be firstEle and it's hours which is calculated in the first iteration and it's causing the problem for calculating, I've tried multiple ways but I'm not coming up with the solution on how to make this reduce work.

UPDATE

Karamell's answer was perfect but I'm still having a difficult time achieving the following condition in reduce
Also, I managed to get exactly what I wanted with the following,
As if there is IN,OUT,OUT it won't calculate last OUT which is what I wanted

```<code>          let hours = 0;
          emp.Attendance.reduce((firstEle, secondEle) => {
            if (
              firstEle.type === "IN" &&
              secondEle.type === "OUT" &&
              (firstEle !== undefined && secondEle !== undefined)
            ) {
              hours +=
                Math.abs(
                  new Date(firstEle.time).getTime() -
                    new Date(secondEle.time).getTime()
                ) / 36e5;
            }
            return secondEle;
          });
</code>```

答:
If you just want very concise code

```<code>emp.Attendance.reduce(
  ([result, lastIn], { time, type }) =>
    type === 'OUT' ? [result + (new Date(time) - lastIn)] : [result, new Date(time)],
  [0],
) /
  (1000 * 60 * 60);
</code>```

It returns 5.2502... for your data which is probably correct.

You haven't specified what should happen if the data doesn't match up, in terms of in/out pairs, but this should work for correct data.

Body:
Scenario

I have an array of objects with multiple users with their attendances(in time, out time). I'm trying to use Array.prototype.reduce() to minimize the code.

Following is the sample object/array, the in and out can be more depending on the user.

"temp": [
        {
            "name": "Test User",
            "id": 35,
            "Attendance": [
                {
                    "id": 34890,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T10:11:06.000Z",
                    "flag": "0\t1\t0\t0\t0",
                    "type": "IN"
                },
                {
                    "id": 34904,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T13:12:23.000Z",
                    "flag": "1\t1\t0\t0\t0",
                    "type": "OUT"
                },
                {
                    "id": 34914,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T13:46:18.000Z",
                    "flag": "0\t1\t0\t0\t0",
                    "type": "IN"
                },
                {
                    "id": 34943,
                    "employee_code": "AL028",
                    "date": "2018-11-20",
                    "time": "2018-11-20T16:00:02.000Z",
                    "flag": "1\t1\t0\t0\t0",
                    "type": "OUT"
                },
            ]
        }
  ]

Code

Please Ignore few variables which I've kept for logging purpose

let temp = attendances;
        let mappedAttendance = temp.map(emp => {
          let hours = 0,i=0;
          const empHours = emp.Attendance.reduce((firstEle, secondEle) => {
            if (
              firstEle.type === "IN" &&
              secondEle.type === "OUT" &&
              (firstEle !== undefined && secondEle !== undefined)
            ) {
              hours +=
                Math.abs(
                  new Date(firstEle.time).getTime() -
                    new Date(secondEle.time).getTime()
                ) / 36e5;
            }
            i++;
            return hours;
          });

          return {
            name: emp.name,
            id: emp.id,
            hours: empHours
          };
        });

Goal

Also I want the output to be like follow

       {
            "name": "Test User",
            "id": 35,
            "hours": 3.0213888888888887
        },

Problem

It seems it's not calculating well as after first iteration the returning value will be firstEle and it's hours which is calculated in the first iteration and it's causing the problem for calculating, I've tried multiple ways but I'm not coming up with the solution on how to make this reduce work.

UPDATE

Karamell's answer was perfect but I'm still having a difficult time achieving the following condition in reduce
Also, I managed to get exactly what I wanted with the following,
As if there is IN,OUT,OUT it won't calculate last OUT which is what I wanted

          let hours = 0;
          emp.Attendance.reduce((firstEle, secondEle) => {
            if (
              firstEle.type === "IN" &&
              secondEle.type === "OUT" &&
              (firstEle !== undefined && secondEle !== undefined)
            ) {
              hours +=
                Math.abs(
                  new Date(firstEle.time).getTime() -
                    new Date(secondEle.time).getTime()
                ) / 36e5;
            }
            return secondEle;
          });

Body:
If you just want very concise code

emp.Attendance.reduce(
  ([result, lastIn], { time, type }) =>
    type === 'OUT' ? [result + (new Date(time) - lastIn)] : [result, new Date(time)],
  [0],
) /
  (1000 * 60 * 60);

It returns 5.2502... for your data which is probably correct.

You haven't specified what should happen if the data doesn't match up, in terms of in/out pairs, but this should work for correct data.


问:
Rails 'Can't verify CSRF token authenticity' on `ShopifyAPI::Product.delete()`, but working on `ShopifyAPI::Product.find()`
I'm creating a public, embedded app for Shopify with a simple goal: retrieve a list of products that are out of stock and give the owner the option to delete them. I'm making an API request to find products that are out of stock, which is working fine. Though when I attempt to delete the products, I'm getting 'can't verify CSRF...'

I'm running rails 5.2.3 and ruby 2.5.0 , I've tried using a different version of rails, ensured I have <% csrf meta... %> in my layout, and the app has 'write_products' permissions in the authorization url.

I'm new to rails so I'm hoping this is the result of a simple mistake I'm making.

Here's my routes.rb:

```<code>Rails.application.routes.draw do
  root :to => 'home#index'
  mount ShopifyApp::Engine, at: '/'
  post '/destroy', to: 'home#destroy'
end
</code>```

home_controller :

```<code>class HomeController < AuthenticatedController
  def index
    @products = ShopifyAPI::Product.find(:all, params: { limit: 10 })
    @webhooks = ShopifyAPI::Webhook.find(:all)
  end

  def destroy
    params[:product_ids].each do |product_id|
      puts product_id
      ShopifyAPI::Product.delete(product_id)
    end
  end
end
</code>```

and the HTML form sending the post request:

```<code><form action="destroy" method="post">
<% @products.each do |product| %>
  <% if product.variants.all? { |variant| variant.inventory_quantity == 0 } %>
    <input type="checkbox" name="product_ids[]" value="<%=product.id%>"><%= product.title %></input>
  <% end %>
<% end %>
<button type="submit">delete products</button>
</form>
</code>```

The form POSTs selected product_id's to the destroy route, which makes an API call to delete each product.

The relevant Heroku logs output is:

```<code>2019-06-01T16:47:00.028409+00:00 app[web.1]: I, [2019-06-01T16:47:00.028316 #4]  INFO -- : [f88f9c69-7c6c-4a31-a386-f6916c295700] Started POST "/destroy" for 24.96.97.148 at 2019-06-01 16:47:00 +0000
2019-06-01T16:47:00.029561+00:00 app[web.1]: I, [2019-06-01T16:47:00.029496 #4]  INFO -- : [f88f9c69-7c6c-4a31-a386-f6916c295700] Processing by HomeController#destroy as HTML
2019-06-01T16:47:00.029628+00:00 app[web.1]: I, [2019-06-01T16:47:00.029573 #4]  INFO -- : [f88f9c69-7c6c-4a31-a386-f6916c295700]   Parameters: {"product_ids"=>["1594488094775"]}
2019-06-01T16:47:00.029867+00:00 app[web.1]: W, [2019-06-01T16:47:00.029808 #4]  WARN -- : [f88f9c69-7c6c-4a31-a386-f6916c295700] Can't verify CSRF token authenticity.
</code>```

EDIT:

I updated my route to :
post '/home', to: 'home#destroy'

and used the form_tag method to create my form which added an authentication token to the form:

```<code><%= form_tag(home_path) do %>
<% @products.each do |product| %>
  <% if product.variants.all? { |variant| variant.inventory_quantity == 0 } %>
    <input type="checkbox" name="product_ids[]" value="<%=product.id%>"><%= product.title %></input>
  <% end %>
<% end %>
<button type="submit">delete products</button>
<% end %>
</form>
</code>```

And it solved my issue.

答:
I think you forgot the = in your csrf_meta_tag.

<%= csrf_meta_tag %>

The <%= indicates that the output of the command should be printed to the html, while <% is just an operation without printing to the html.

Body:
I'm creating a public, embedded app for Shopify with a simple goal: retrieve a list of products that are out of stock and give the owner the option to delete them. I'm making an API request to find products that are out of stock, which is working fine. Though when I attempt to delete the products, I'm getting 'can't verify CSRF...'

I'm running rails 5.2.3 and ruby 2.5.0 , I've tried using a different version of rails, ensured I have <% csrf meta... %> in my layout, and the app has 'write_products' permissions in the authorization url.

I'm new to rails so I'm hoping this is the result of a simple mistake I'm making.

Here's my routes.rb:

Rails.application.routes.draw do
  root :to => 'home#index'
  mount ShopifyApp::Engine, at: '/'
  post '/destroy', to: 'home#destroy'
end

home_controller :

class HomeController < AuthenticatedController
  def index
    @products = ShopifyAPI::Product.find(:all, params: { limit: 10 })
    @webhooks = ShopifyAPI::Webhook.find(:all)
  end

  def destroy
    params[:product_ids].each do |product_id|
      puts product_id
      ShopifyAPI::Product.delete(product_id)
    end
  end
end

and the HTML form sending the post request:

<form action="destroy" method="post">
<% @products.each do |product| %>
  <% if product.variants.all? { |variant| variant.inventory_quantity == 0 } %>
    <input type="checkbox" name="product_ids[]" value="<%=product.id%>"><%= product.title %></input>
  <% end %>
<% end %>
<button type="submit">delete products</button>
</form>

The form POSTs selected product_id's to the destroy route, which makes an API call to delete each product.

The relevant Heroku logs output is:

2019-06-01T16:47:00.028409+00:00 app[web.1]: I, [2019-06-01T16:47:00.028316 #4]  INFO -- : [f88f9c69-7c6c-4a31-a386-f6916c295700] Started POST "/destroy" for 24.96.97.148 at 2019-06-01 16:47:00 +0000
2019-06-01T16:47:00.029561+00:00 app[web.1]: I, [2019-06-01T16:47:00.029496 #4]  INFO -- : [f88f9c69-7c6c-4a31-a386-f6916c295700] Processing by HomeController#destroy as HTML
2019-06-01T16:47:00.029628+00:00 app[web.1]: I, [2019-06-01T16:47:00.029573 #4]  INFO -- : [f88f9c69-7c6c-4a31-a386-f6916c295700]   Parameters: {"product_ids"=>["1594488094775"]}
2019-06-01T16:47:00.029867+00:00 app[web.1]: W, [2019-06-01T16:47:00.029808 #4]  WARN -- : [f88f9c69-7c6c-4a31-a386-f6916c295700] Can't verify CSRF token authenticity.

EDIT:

I updated my route to :
post '/home', to: 'home#destroy'

and used the form_tag method to create my form which added an authentication token to the form:

<%= form_tag(home_path) do %>
<% @products.each do |product| %>
  <% if product.variants.all? { |variant| variant.inventory_quantity == 0 } %>
    <input type="checkbox" name="product_ids[]" value="<%=product.id%>"><%= product.title %></input>
  <% end %>
<% end %>
<button type="submit">delete products</button>
<% end %>
</form>

And it solved my issue.


问:
Where to find Java Mission Control and VisualVM on Ubuntu (OpenJDK 8)?
I installed OpenJDK 8 on Ubuntu using sudo apt-get install openjdk-8-jdk, and it was installed to /usr/lib/jvm/java-8-openjdk-amd64.

Where can I find the Java Mission Control (I think called jmc) and VisualVM (I think called jvisualvm) programs?

I assumed both to be installed with the JDK:

The Java Mission Control page states that "Starting with the release of Oracle JDK 7 Update 40 (7u40), Java Mission Control is bundled with the HotSpot JVM."

The VisualVM page says "March 18th, 2014: JDK 8 has been released and is available for download here. It contains Java VisualVM tool based on VisualVM 1.3.6."

What am I missing? Are both only part of the Oracle JDK, or did I use the wrong install command?

If they are not part of the OpenJDK, can I download them using apt-get install?

答:
An alternative to the build instructions provided by Steven is to use docker-compose to do the build:</p>

```<code>$ hg clone http://hg.openjdk.java.net/jmc/jmc/
$ cd jmc/jmc/docker
$ docker-compose up
# Wait for the build to finish, then exit it with Ctrl-C
$ cd ../target
$ ls products/org.openjdk.jmc/
linux macosx win32
# Run the binary from the correct OS
$ ./products/org.openjdk.jmc/linux/gtk/x86_64/jmc
</code>```

Body:
An alternative to the build instructions provided by Steven is to use docker-compose to do the build:

$ hg clone http://hg.openjdk.java.net/jmc/jmc/
$ cd jmc/jmc/docker
$ docker-compose up
# Wait for the build to finish, then exit it with Ctrl-C
$ cd ../target
$ ls products/org.openjdk.jmc/
linux macosx win32
# Run the binary from the correct OS
$ ./products/org.openjdk.jmc/linux/gtk/x86_64/jmc


问:
How can I start a timer on keydown and stop on keyup?
I would like to be able to press the spacebar and left arrow key at the same time and have a timer start for ten seconds. If the user stops pressing the key then the timer should stop as well and the result should be cancelled.
I have already tried to use the clearInterval() method.

function startTimer(duration, display) {
  var timer = duration;
  var minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      window.open('1.html', '_self')
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10;
  var display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

var timesdown = 0;

document.addEventListener('keypress', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    timesdown = 0
    clearInterval(startTimer);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="time"></div></code>```

When I press down on the key, the timer continues to try to restart but when I lift up the timer continues counting.

答:
Your code has several problems. First, you are using keypress instead of keydown and keypress will not detect the arrow keys.

You also have the event.code wrong. It's ArrowLeft, not LeftArrow.

Events are also only processed one at a time. event.code cannot be 'Space' and 'LeftArrow' at the same time. event.code is one variable!

Since events are processed only one at a time you need extra logic to capture that state.

The code below is a working example, correcting all of the above problems.

var intervalID = false;
var spaceDown = false;
var arrowDown = false;
var spaceUp = false;
var arrowUp = false;

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;

  intervalID = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      console.log("window.open('1.html', '_self')");
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10,
    display = document.querySelector('#time');

  startTimer(fiveMinutes, display);
};

var timesdown = 0

document.addEventListener('keydown', function(event) {

  if (event.code == 'Space') {
    spaceDown = true;
    spaceUp = false;
  }

  if (event.code == 'ArrowLeft') {
    arrowDown = true;
    arrowUp = false;
  }

  if (spaceDown && arrowDown) {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {

  if (event.code == 'Space') {
    spaceDown = false;
    spaceUp = true;
  }

  if (event.code == 'ArrowLeft') {
    arrowDown = false;
    arrowUp = true;
  }

  if (spaceUp && arrowUp) {
    timesdown = 0;
    clearInterval(intervalID);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<body>
  <div id="time"></div>
</body>

</html></code>```

Body:
I would like to be able to press the spacebar and left arrow key at the same time and have a timer start for ten seconds. If the user stops pressing the key then the timer should stop as well and the result should be cancelled.
I have already tried to use the clearInterval() method.

function startTimer(duration, display) {
  var timer = duration;
  var minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      window.open('1.html', '_self')
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10;
  var display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

var timesdown = 0;

document.addEventListener('keypress', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    timesdown = 0
    clearInterval(startTimer);
  }
});

When I press down on the key, the timer continues to try to restart but when I lift up the timer continues counting.

Body:
Your code has several problems. First, you are using keypress instead of keydown and keypress will not detect the arrow keys.

You also have the event.code wrong. It's ArrowLeft, not LeftArrow.

Events are also only processed one at a time. event.code cannot be 'Space' and 'LeftArrow' at the same time. event.code is one variable!

Since events are processed only one at a time you need extra logic to capture that state.

The code below is a working example, correcting all of the above problems.

var intervalID = false;
var spaceDown = false;
var arrowDown = false;
var spaceUp = false;
var arrowUp = false;

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;

  intervalID = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      console.log("window.open('1.html', '_self')");
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10,
    display = document.querySelector('#time');

  startTimer(fiveMinutes, display);
};

var timesdown = 0

document.addEventListener('keydown', function(event) {

  if (event.code == 'Space') {
    spaceDown = true;
    spaceUp = false;
  }

  if (event.code == 'ArrowLeft') {
    arrowDown = true;
    arrowUp = false;
  }

  if (spaceDown && arrowDown) {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {

  if (event.code == 'Space') {
    spaceDown = false;
    spaceUp = true;
  }

  if (event.code == 'ArrowLeft') {
    arrowDown = false;
    arrowUp = true;
  }

  if (spaceUp && arrowUp) {
    timesdown = 0;
    clearInterval(intervalID);
  }
});

<html>

<body>
  <div id="time"></div>
</body>

</html>


问:
Problems drawing an "x" in the center of a circle using XAML
I am trying to create a red circle with a black x through it using XAML.

My problem is that they aren't aligned correctly.

What is the right way to do this?

This is what I've got so far:

```<code>  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Image>
    <Image.Source>
      <DrawingImage>
        <DrawingImage.Drawing>
          <DrawingGroup>
            <GeometryDrawing Brush="Red">
              <GeometryDrawing.Pen>
                <Pen Brush="Transparent" Thickness="0"/>
              </GeometryDrawing.Pen>
              <GeometryDrawing.Geometry>
                <EllipseGeometry Center="8,8" RadiusX="8" RadiusY="8"/>
              </GeometryDrawing.Geometry>
            </GeometryDrawing>
            <GeometryDrawing>
              <GeometryDrawing.Pen>
                <Pen Brush="Black" Thickness="2.5"/>
              </GeometryDrawing.Pen>
              <GeometryDrawing.Geometry>
                <PathGeometry>
                  <PathFigure StartPoint="4,4">
                    <LineSegment Point="12,12"/>
                  </PathFigure>
                  <PathFigure StartPoint="4,12">
                    <LineSegment Point="12,4"/>
                  </PathFigure>
                </PathGeometry>
              </GeometryDrawing.Geometry>
            </GeometryDrawing>
          </DrawingGroup>
        </DrawingImage.Drawing>
      </DrawingImage>
    </Image.Source>
    </Image>
  </Grid>
</code>```

Simply putting an ellipse in the same grid with a black X the X isn't quite centered on the ellipse because the coordinates of each line you draw are really coordinates within the space allotted for it.

I think they needed to be in some sort of geometry or drawing aggregate to give them the same coordinate system. The geometry group and path are aggregators but both require their contents to have the same fill and stroke and the stroke and fill is different for the red circle (no stroke) and the black X (no fill).

The only aggregator that gives common coordinate systems and allows different fills & strokes for its members that I could find was the DrawingGroup.

The string shortcuts that work for creating a Path via its Data property don't appear to work for creating a PathGeometry so all had to be filled in by hand.

答:
OK, so three hundred ways to skin a cat. Without fully understanding your use case I just came up with the fastest way to draw what you requested.

```<code>    <Grid HorizontalAlignment="Left"
          Height="80"
          Margin="80,80,0,0"
          VerticalAlignment="Top"
          Width="80">
        <Ellipse Fill="Red"
                 HorizontalAlignment="Stretch"
                 VerticalAlignment="Stretch" />
        <Path Data="M40,53 L48,69 62,69 49,46 61,24 48,24 C48,24 40,39 40,39 40,39 32,24 32,24 L18,24 30,46 17,69 31,69 z"
              Fill="Black"
              Margin="15"
              Stretch="Fill"
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              />
    </Grid>
</code>```

This is probably outside what exactly you're looking for, but hopefully it at least gives you another way to think about it.

Body:
I am trying to create a red circle with a black x through it using XAML.

My problem is that they aren't aligned correctly.

What is the right way to do this?

This is what I've got so far:

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Image>
    <Image.Source>
      <DrawingImage>
        <DrawingImage.Drawing>
          <DrawingGroup>
            <GeometryDrawing Brush="Red">
              <GeometryDrawing.Pen>
                <Pen Brush="Transparent" Thickness="0"/>
              </GeometryDrawing.Pen>
              <GeometryDrawing.Geometry>
                <EllipseGeometry Center="8,8" RadiusX="8" RadiusY="8"/>
              </GeometryDrawing.Geometry>
            </GeometryDrawing>
            <GeometryDrawing>
              <GeometryDrawing.Pen>
                <Pen Brush="Black" Thickness="2.5"/>
              </GeometryDrawing.Pen>
              <GeometryDrawing.Geometry>
                <PathGeometry>
                  <PathFigure StartPoint="4,4">
                    <LineSegment Point="12,12"/>
                  </PathFigure>
                  <PathFigure StartPoint="4,12">
                    <LineSegment Point="12,4"/>
                  </PathFigure>
                </PathGeometry>
              </GeometryDrawing.Geometry>
            </GeometryDrawing>
          </DrawingGroup>
        </DrawingImage.Drawing>
      </DrawingImage>
    </Image.Source>
    </Image>
  </Grid>

Simply putting an ellipse in the same grid with a black X the X isn't quite centered on the ellipse because the coordinates of each line you draw are really coordinates within the space allotted for it.

I think they needed to be in some sort of geometry or drawing aggregate to give them the same coordinate system. The geometry group and path are aggregators but both require their contents to have the same fill and stroke and the stroke and fill is different for the red circle (no stroke) and the black X (no fill).

The only aggregator that gives common coordinate systems and allows different fills & strokes for its members that I could find was the DrawingGroup.

The string shortcuts that work for creating a Path via its Data property don't appear to work for creating a PathGeometry so all had to be filled in by hand.

Body:
OK, so three hundred ways to skin a cat. Without fully understanding your use case I just came up with the fastest way to draw what you requested.

    <Grid HorizontalAlignment="Left"
          Height="80"
          Margin="80,80,0,0"
          VerticalAlignment="Top"
          Width="80">
        <Ellipse Fill="Red"
                 HorizontalAlignment="Stretch"
                 VerticalAlignment="Stretch" />
        <Path Data="M40,53 L48,69 62,69 49,46 61,24 48,24 C48,24 40,39 40,39 40,39 32,24 32,24 L18,24 30,46 17,69 31,69 z"
              Fill="Black"
              Margin="15"
              Stretch="Fill"
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              />
    </Grid>

This is probably outside what exactly you're looking for, but hopefully it at least gives you another way to think about it.


问:
multiple static interfaces with implementation-dependent type of member function
I have two interfaces that I want to use with CRTP for static polymorphism. One of them contains a function whose types in the signature are implementation-dependent.

This problem looks like what has been asked here without solution. The solution I came up with includes an additional templated structure defining the type. This template is then specialized for the implementation avoiding the "invalid use of incomplete type" error.

Here my code

#include <iostream>
#include <memory>

template<class impl1>
struct Interface1 {
    double foo() { return static_cast<impl1*>(this)->fooimpl();}
};

template<class impl1, class impl2>
struct typeHelp;

template<class impl1, class impl2>
struct Interface2 {
    void bar(typename typeHelp<impl1,impl2>::type value) {
        static_cast<impl2*>(this)->barimpl(value);
    }
};

//Implementation2 pre declaration
template<class impl1>
struct Implementation2;

//Partial specialization of templated typeHelp
template<class impl1>
struct typeHelp<impl1, Implementation2<impl1>> {
    using type = int;
};

//Implementation2
template<class impl1>
struct Implementation2 : public Interface2<impl1, Implementation2<impl1>> {
    std::shared_ptr<Interface1<impl1>> imp1;
    void barimpl(typename typeHelp<impl1,Implementation2>::type value) {
        std::cout << imp1->foo() << " " << value << std::endl;
    }
};

//Implementation1
struct Implementation1 : public Interface1<Implementation1> {
    double fooimpl() {return 0.;}
};

int main()
{
    Implementation2<Implementation1> obj;
    obj.imp1 = std::make_shared<Implementation1>();
    obj.bar(4);
}
```

What I don't like in this code is that Interface2 and typeHelp depend on template parameter impl1. This works for my particular case, where Implementation2 is templated with respect to impl1 but it wouldn't if Implementation2 weren't. I wonder if there is a more general and elegant solution to this problem.

答:
My bad; a little bit more of search and I would have found the answer. On this link, Andy G points out that it is possible to specialize a class template with a templated class. The result is more clean than before

#include <iostream>
#include <memory>

//Interface1.hpp
template<class impl1>
struct Interface1 {
    double foo() { return static_cast<impl1*>(this)->fooimpl();}
};

//Interface2.hpp
template<class impl2>
struct typeHelp;

template<class impl2>
struct Interface2 {
    void bar(typename typeHelp<impl2>::type value) {
        static_cast<impl2*>(this)->barimpl(value);
    }
};

//Implementation2.hpp
template<class impl1>
struct Implementation2;

//specialization of typeHelp with templated class
template<class impl1>
struct typeHelp<Implementation2<impl1>> {
    using type = int;
};

//Actual implementation of Implementation2
template<class impl1>
struct Implementation2 : public Interface2<Implementation2<impl1>> {
    std::shared_ptr<Interface1<impl1>> imp1;
    void barimpl(typename typeHelp<Implementation2<impl1>>::type value) {
        std::cout << imp1->foo() << " " << value << std::endl;
    }
};

//Implementation1.hpp
struct Implementation1 : public Interface1<Implementation1> {
    double fooimpl() {return 0.;}
};

//Main.hpp
int main()
{
    Implementation2<Implementation1> obj;
    obj.imp1 = std::make_shared<Implementation1>();
    obj.bar(4);
}
```

Body:
I have two interfaces that I want to use with CRTP for static polymorphism. One of them contains a function whose types in the signature are implementation-dependent.

This problem looks like what has been asked here without solution. The solution I came up with includes an additional templated structure defining the type. This template is then specialized for the implementation avoiding the "invalid use of incomplete type" error.

Here my code

#include <iostream>
#include <memory>

template<class impl1>
struct Interface1 {
    double foo() { return static_cast<impl1*>(this)->fooimpl();}
};

template<class impl1, class impl2>
struct typeHelp;

template<class impl1, class impl2>
struct Interface2 {
    void bar(typename typeHelp<impl1,impl2>::type value) {
        static_cast<impl2*>(this)->barimpl(value);
    }
};

//Implementation2 pre declaration
template<class impl1>
struct Implementation2;

//Partial specialization of templated typeHelp
template<class impl1>
struct typeHelp<impl1, Implementation2<impl1>> {
    using type = int;
};

//Implementation2
template<class impl1>
struct Implementation2 : public Interface2<impl1, Implementation2<impl1>> {
    std::shared_ptr<Interface1<impl1>> imp1;
    void barimpl(typename typeHelp<impl1,Implementation2>::type value) {
        std::cout << imp1->foo() << " " << value << std::endl;
    }
};

//Implementation1
struct Implementation1 : public Interface1<Implementation1> {
    double fooimpl() {return 0.;}
};

int main()
{
    Implementation2<Implementation1> obj;
    obj.imp1 = std::make_shared<Implementation1>();
    obj.bar(4);
}

What I don't like in this code is that Interface2 and typeHelp depend on template parameter impl1. This works for my particular case, where Implementation2 is templated with respect to impl1 but it wouldn't if Implementation2 weren't. I wonder if there is a more general and elegant solution to this problem.


问:
Condense Array to Number
I'm trying to solve a problem for my homework but im stuck.

Here is the task:

Write a program to read an array of integers and condense them by summing adjacent couples of elements until a single integer is obtained. For example, if we have 3 elements {2, 10, 3}, we sum the first two and the second two elements and obtain {2+10, 10+3} = {12, 13}, then we sum again all adjacent elements and obtain {12+13} = {25}.

This is what i've done so far but im stuck and don't know how to continue.

```<code>for (int i = 0; i < arr.length; i++) {
    arr[i] = Integer.parseInt(input[i]);
}

int sum = 0;
int[] condensed = new int [arr.length-1];
System.out.println(condensed.length);

while (condensed.length > 1) {
    for (int i = 0; i < condensed.length; i++) {
        condensed[i] = arr[i] + arr[i+1];
    }
}

if (condensed.length == 1) {
    sum = condensed[0] + condensed[1];
    System.out.println(sum);
}
</code>```

The input is "5 0 4 1 2" and the output should be "35" but I get "4".

答:
i've wrote an example code that you can expand if you have troubles let me know:

```<code>        int[] a1 = new int[] {2, 10 , 3};
        int[] a2 = new int[2];
        int[] a3 = new int[1];

        for(int i = 0; i < a1.length - 1; i++)
            a2[i] = a1[i] + a1[i + 1];

        for(int i = 0; i < a2.length - 1; i++)
            a3[i] = a2[i] + a2[i + 1];

        System.out.println(a3[0]);
</code>```

in general you whould generate N int arrays (N = arr.length - 1) and fill them with a loop

Title: Condense Array to Number

Body:
I'm trying to solve a problem for my homework but im stuck.

Here is the task:

Write a program to read an array of integers and condense them by summing adjacent couples of elements until a single integer is obtained. For example, if we have 3 elements {2, 10, 3}, we sum the first two and the second two elements and obtain {2+10, 10+3} = {12, 13}, then we sum again all adjacent elements and obtain {12+13} = {25}.

This is what i've done so far but im stuck and don't know how to continue.

for (int i = 0; i < arr.length; i++) {
    arr[i] = Integer.parseInt(input[i]);
}

int sum = 0;
int[] condensed = new int [arr.length-1];
System.out.println(condensed.length);

while (condensed.length > 1) {
    for (int i = 0; i < condensed.length; i++) {
        condensed[i] = arr[i] + arr[i+1];
    }
}

if (condensed.length == 1) {
    sum = condensed[0] + condensed[1];
    System.out.println(sum);
}

The input is "5 0 4 1 2" and the output should be "35" but I get "4".

Body:
i've wrote an example code that you can expand if you have troubles let me know:

        int[] a1 = new int[] {2, 10 , 3};
        int[] a2 = new int[2];
        int[] a3 = new int[1];

        for(int i = 0; i < a1.length - 1; i++)
            a2[i] = a1[i] + a1[i + 1];

        for(int i = 0; i < a2.length - 1; i++)
            a3[i] = a2[i] + a2[i + 1];

        System.out.println(a3[0]);

in general you whould generate N int arrays (N = arr.length - 1) and fill them with a loop


问:
How to get object value only without mentioning key from array list using ngFor in Angular 7
I have an array list which has list of emp objects. I want to iterate in html using *ngFor loop. But I do not want to give like {{emp.empname}}. I want to get values only with out mentioning the key with emp object.

```<code>const epmloyees = [
                    {'empname': 'kumaresan', 'id': 2},
                    {'empname': 'perumal', 'id': 3},
                  ]
</code>```

HTML code

```<code>        <tr *ngFor="let emp of epmloyees ">

        <td scope="row" class="font-weight-bold">{{emp}}</td>
</code>```

答:
You can try this

 {{emp}}
```

Body:
I have an array list which has list of emp objects. I want to iterate in html using *ngFor loop. But I do not want to give like {{emp.empname}}. I want to get values only with out mentioning the key with emp object.

const epmloyees = [
                    {'empname': 'kumaresan', 'id': 2},
                    {'empname': 'perumal', 'id': 3},
                  ]

HTML code

        {{emp}}

Body:
You can try this

 <tr *ngFor="let emp of Object.values(epmloyees)">
 <td scope="row" class="font-weight-bold">{{emp}}</td>


问:
How to get heart rate in watchOS 3+ without using a workout session
I would like to collect the heart rate of the user programmatically by a watchkit extension, but not during a workout session.

As far as I know watchOS 3+ doesn't collect heart rate if the user is moving: however as soon as he's resting for a while (10 minutes ?) I'd like to get somehow the current bpm value by the HealthKit API.

答:
Since you are having a companion iPhone app, you may query heart rate updates from there.

You just need to have an iPhone with paired Apple watch (which is
obvious)

The Default Apple Watch Heart Rate monitor app updates the HealthKit
data immediately only when it is in the foreground.

When the Default Apple Watch Heart Rate monitor app is in the
Background, it updates the HealthKit data at the interval of 9-10
mins.
This code should do the work:

```<code>import UIKit
import HealthKit

class ViewController: UIViewController {
@IBOutlet weak var heartRateLabel: UILabel!
@IBOutlet weak var timeStampLabel: UILabel!

var hkStore: HKHealthStore?
let heartRateUnit: HKUnit = HKUnit.count().unitDivided(by: .minute())
var healthStore: HKHealthStore?
override func viewDidLoad() {
    super.viewDidLoad()
    healthStore = HKHealthStore()
    let sampleTypes = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!

    healthStore?.requestAuthorization(toShare: [sampleTypes], read: [sampleTypes], completion: { (success, error) in
        if (error != nil) {
            print(error!.localizedDescription)
        }
    })

    getSamples()
}
func getSamples() {
    let heartrate = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
    let sort = [
        NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
    ]
    let sampleQuery = HKSampleQuery(sampleType: heartrate!, predicate: nil, limit: 1, sortDescriptors: sort, resultsHandler: { [unowned self] (query, results, error) in
        if let results = results as? [HKQuantitySample]
        {
            let sample = results[0] as HKQuantitySample
            let value = sample.quantity.doubleValue(for: self.heartRateUnit)
            let rate = results[0]
            print(value, rate)
            self.updateHeartRate(samples: results)
        }
    })
    healthStore?.execute(sampleQuery)
}

func updateHeartRate(samples: [HKSample]?) {
    guard let heartRateSamples = samples as? [HKQuantitySample] else {return}
    DispatchQueue.main.async {
        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValue(for: self.heartRateUnit)
        self.heartRateLabel.text = String(UInt16(value))
        let date = sample.startDate
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        self.timeStampLabel.text = dateFormatter.string(from: date)
     }
 }
}
</code>```

Notice that the query need to be fire periodically.

Body:
Since you are having a companion iPhone app, you may query heart rate updates from there.

You just need to have an iPhone with paired Apple watch (which is
obvious)

The Default Apple Watch Heart Rate monitor app updates the HealthKit
data immediately only when it is in the foreground.

When the Default Apple Watch Heart Rate monitor app is in the
Background, it updates the HealthKit data at the interval of 9-10
mins.
This code should do the work:

import UIKit
import HealthKit

class ViewController: UIViewController {
@IBOutlet weak var heartRateLabel: UILabel!
@IBOutlet weak var timeStampLabel: UILabel!

var hkStore: HKHealthStore?
let heartRateUnit: HKUnit = HKUnit.count().unitDivided(by: .minute())
var healthStore: HKHealthStore?
override func viewDidLoad() {
    super.viewDidLoad()
    healthStore = HKHealthStore()
    let sampleTypes = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!

    healthStore?.requestAuthorization(toShare: [sampleTypes], read: [sampleTypes], completion: { (success, error) in
        if (error != nil) {
            print(error!.localizedDescription)
        }
    })

    getSamples()
}
func getSamples() {
    let heartrate = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
    let sort = [
        NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
    ]
    let sampleQuery = HKSampleQuery(sampleType: heartrate!, predicate: nil, limit: 1, sortDescriptors: sort, resultsHandler: { [unowned self] (query, results, error) in
        if let results = results as? [HKQuantitySample]
        {
            let sample = results[0] as HKQuantitySample
            let value = sample.quantity.doubleValue(for: self.heartRateUnit)
            let rate = results[0]
            print(value, rate)
            self.updateHeartRate(samples: results)
        }
    })
    healthStore?.execute(sampleQuery)
}

func updateHeartRate(samples: [HKSample]?) {
    guard let heartRateSamples = samples as? [HKQuantitySample] else {return}
    DispatchQueue.main.async {
        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValue(for: self.heartRateUnit)
        self.heartRateLabel.text = String(UInt16(value))
        let date = sample.startDate
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        self.timeStampLabel.text = dateFormatter.string(from: date)
     }
 }
}

Notice that the query need to be fire periodically.


问:
vba error: object variable or with block variable not set
I'm getting a "object variable or with block variable not set" error message when running the following code. It is in Access and refers to an Excel spreadsheet. What is wrong with the code?

```<code>wsTest.Range("A11").Activate

Do Until IsEmpty(ActiveCell)
    intX = intX + wsTest.Cells(ActiveCell.Row, "L") 'error occurs on this line
    intY = intY + wsTest.Cells(ActiveCell.Row, "I")
    ActiveCell.Offset(1, 0).Select ' Step down 1 row to the next cell.
Loop
</code>```

The first time the code is run, there is no error, only the second time. Closing and reopening Access "fixes" the problem. How can that be related to this code?

答:
Try changing </p>

```<code>wsTest.Range("A11").Activate
</code>```

<p>to </p>

```<code>wsTest.Range("A11").Select
</code>```

Body:
I'm getting a "object variable or with block variable not set" error message when running the following code. It is in Access and refers to an Excel spreadsheet. What is wrong with the code?

wsTest.Range("A11").Activate

Do Until IsEmpty(ActiveCell)
    intX = intX + wsTest.Cells(ActiveCell.Row, "L") 'error occurs on this line
    intY = intY + wsTest.Cells(ActiveCell.Row, "I")
    ActiveCell.Offset(1, 0).Select ' Step down 1 row to the next cell.
Loop

The first time the code is run, there is no error, only the second time. Closing and reopening Access "fixes" the problem. How can that be related to this code?

Body:
Try changing

wsTest.Range("A11").Activate

to

wsTest.Range("A11").Select


问:
Unable to install python-docx
I need to create table in a Word document through Python 3.4. For that, I am trying to install python-docx in Windows. If I use pip install python-docx I am getting the following error:

```<code>vcvarsall.bat error
</code>```

So I installed Visual Studio and then tried to install it and I am still getting the following :

```<code>error: Setup script exited with error: command '"C:\Program Files (x86)\Microsoft Visual
Studio 10.0\VC\BIN\cl.exe"' failed with exit status 2
</code>```

答:
This worked fro me:

```<code>pip uninstall docx
pip uninstall lxml
pip install lxml
pip install python-docx
</code>```

following this git-hub discussion

Title: Unable to install python-docx

Body:
I need to create table in a Word document through Python 3.4. For that, I am trying to install python-docx in Windows. If I use pip install python-docx I am getting the following error:

vcvarsall.bat error

So I installed Visual Studio and then tried to install it and I am still getting the following :

error: Setup script exited with error: command '"C:\Program Files (x86)\Microsoft Visual
Studio 10.0\VC\BIN\cl.exe"' failed with exit status 2

Body:
This worked fro me:

pip uninstall docx
pip uninstall lxml
pip install lxml
pip install python-docx

following this git-hub discussion


问:
Adding a time.sleep() method for Google Translate API in python
I'm setting up a Django Views that requests products data from an API, parse them with BeautifulSoup, apply the googletrans module and save the response into my Postgresql database. I have a 429 HTTP error when I run my script because I send to many requests at once and I was adviced to add a time.sleep() method of 2 seconds to fix the issue.

The only thing is that I'm not sure where should I place this method in my script, and I need to make sure that its the right way to do it before risking of getting my IP address blocked by Google tranlsate API again.

This is my Views:

```<code>from bs4 import BeautifulSoup
from googletrans import Translator
import requests
import json

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('translating item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            #Parsing work
            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #Translation doesn't work
            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")
</code>```

This is what I came out with, is this okay?

```<code>  Product.objects.get_or_create(
      title=titlefr.text,
      destination=destinationfr.text,
      description=translation.text,
      link=item['canonicalUrl'],
      image=item['image']['url']
  )time.sleep(2) #here
</code>```

or like this:

```<code>resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            }, time.sleep(2)) #or here
</code>```

Please help.

EDIT

Based on @jay answer, Is this correct?

```<code>  Product.objects.get_or_create(
      title=titlefr.text,
      destination=destinationfr.text,
      description=translation.text,
      link=item['canonicalUrl'],
      image=item['image']['url']
  )

  #at the very end of the for loop
  time.sleep(2)
</code>```

答:
I would recommend at the very end of the for loop, so that it waits 2 seconds before relooping. </p>

<pre class="lang-py prettyprint-override"><code>        destinationname = item['city']['name']
        destinationfr = translator.translate(destinationname, dest='fr')

        Product.objects.get_or_create(
            title=titlefr.text,
            destination=destinationfr.text,
            description=translation.text,
            link=item['canonicalUrl'],
            image=item['image']['url']
        )
        time.sleep(2)

return render(request, "form.html")
</code>```

Body:
I'm setting up a Django Views that requests products data from an API, parse them with BeautifulSoup, apply the googletrans module and save the response into my Postgresql database. I have a 429 HTTP error when I run my script because I send to many requests at once and I was adviced to add a time.sleep() method of 2 seconds to fix the issue.

The only thing is that I'm not sure where should I place this method in my script, and I need to make sure that its the right way to do it before risking of getting my IP address blocked by Google tranlsate API again.

This is my Views:

from bs4 import BeautifulSoup
from googletrans import Translator
import requests
import json

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('translating item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            #Parsing work
            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #Translation doesn't work
            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")

This is what I came out with, is this okay?

  Product.objects.get_or_create(
      title=titlefr.text,
      destination=destinationfr.text,
      description=translation.text,
      link=item['canonicalUrl'],
      image=item['image']['url']
  )time.sleep(2) #here

or like this:

resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            }, time.sleep(2)) #or here

Please help.

EDIT

Based on @jay answer, Is this correct?

  Product.objects.get_or_create(
      title=titlefr.text,
      destination=destinationfr.text,
      description=translation.text,
      link=item['canonicalUrl'],
      image=item['image']['url']
  )

  #at the very end of the for loop
  time.sleep(2)

Body:
I would recommend at the very end of the for loop, so that it waits 2 seconds before relooping.

        destinationname = item['city']['name']
        destinationfr = translator.translate(destinationname, dest='fr')

        Product.objects.get_or_create(
            title=titlefr.text,
            destination=destinationfr.text,
            description=translation.text,
            link=item['canonicalUrl'],
            image=item['image']['url']
        )
        time.sleep(2)

return render(request, "form.html")


问:
not sure why setAttribute() isn't working for audio element
In my code i want to set the attribute value for the audio element so that it changes "testing" to "working" in the paragraph element when the audio file stops playing.

I know i can create the audio element outside of the script but i need this for something else i'm doing.

The "horse.mp3" file is there because i was playing around on this page trying to get it working: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_audio

<!DOCTYPE html>

testing

```

答:
You don't need to wrap your onended attribute to a function. Also, you were using multiple double quotation inside the attribute value. It won't work. I have replaced the double quotes with single quotes.

```<code>var audio = new Audio("horse.mp3");

audio.setAttribute("onended", "document.getElementById('test').innerHTML = 'working'");

audio.play();
</code>```

Body:
You don't need to wrap your onended attribute to a function. Also, you were using multiple double quotation inside the attribute value. It won't work. I have replaced the double quotes with single quotes.

var audio = new Audio("horse.mp3");

audio.setAttribute("onended", "document.getElementById('test').innerHTML = 'working'");

audio.play();


问:
Flutter: subtract status bar height from AppBar
I have moved my AppBar downwards but now it's height is too big. I want to know how I can subtract the status bar's height from my AppBar's height. Here is what it looks like at the moment:

Here is how you can set the AppBar's height:

Flutter: Setting the height of the AppBar

Here is how you can get the status bar height:

How or where do I change the system status bar Flutter framework

```<code>final double statusBarHeight = MediaQuery.of(context).padding.top;
return new Padding(
      padding: new EdgeInsets.only(top: statusBarHeight),
      child: content
);
</code>```

I just don't know how to put these pieces together (I am very new to Flutter so please explain the answer well)

答:
Is this what you are looking for?

```<code>Widget build(BuildContext context) {
  return SafeArea(
    child: Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            height: 70,
            alignment: Alignment.center,
            color: Colors.red,
            child: Text(
              "ADVERTISE HERE!",
              style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 24),
            ),
          ),
          AppBar(title: Text("Main page")),
        ],
      ),
    ),
  );
}
</code>```

Body:
I have moved my AppBar downwards but now it's height is too big. I want to know how I can subtract the status bar's height from my AppBar's height. Here is what it looks like at the moment:

Here is how you can set the AppBar's height:

Flutter: Setting the height of the AppBar

Here is how you can get the status bar height:

How or where do I change the system status bar Flutter framework

final double statusBarHeight = MediaQuery.of(context).padding.top;
return new Padding(
      padding: new EdgeInsets.only(top: statusBarHeight),
      child: content
);

I just don't know how to put these pieces together (I am very new to Flutter so please explain the answer well)

Body:
Is this what you are looking for?

Widget build(BuildContext context) {
  return SafeArea(
    child: Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            height: 70,
            alignment: Alignment.center,
            color: Colors.red,
            child: Text(
              "ADVERTISE HERE!",
              style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 24),
            ),
          ),
          AppBar(title: Text("Main page")),
        ],
      ),
    ),
  );
}


问:
How to package/ distribute python applications
I've spent countless hours trying to understand this and unfortunately I haven't gotten to an answer yet. Or at least I don't think I have.
First up I should say that I am a Java Developer. I've only recently started working with Python and the build-process is a bit...odd for me.

In my mind I write an application, I compile it to run and I package it into a .jar for other people to use. Either as a library or for end-users to execute and have fun with it. (ignoring stuff like maven or gradle...)

I wrote a little CLT in python that consists of ~6 files and I wanted to distribute it. From what I could find I was supposed to write a setup.py and I found some guides on how to do that but ... to be honest I'm not even sure what that did. I could get my source code bundled into a tar.gz with some other meta data or it would create some weird files that I don't know what to do with.

Then I found PyInstaller and it worked great to package everything into a binary. However I've run into some problems trying to create a Debian package and it has made me re-assess and question the fact that there doesn't seem to be something in Python (without having to use an external tool) that lets me package/ bundle/ whatever my application into a single file to be run.

And that's something I can't get my head around. I mean...before there were tools like PyInstaller and P2Exe and what not, how did people distribute their applications? Am I expected to write a C application, somehow include the python code in there and compile that? Sorry if this seems like a stupid question but I'm really asking. I've googled around so much and spent so much time on it and haven't found a satisfactory answer so I hope someone here can help me with this! Thanks.

答:
If you package your Python code for pip, you can include some executable scripts that start your program. I don't know how the situation was 5 years ago when this question got asked, but nowadays pip is pretty much integrated with Python, to the point that there's a standard library module to bootstrap pip in case it's missing:
https://docs.python.org/3/library/ensurepip.html

The situation is different if you want to package an application for some other package manager, like Anaconda or the package managers of various Linux distributions, or as a Windows installer. Obviously, you'll have to create a separate package for each package manager or installation technique you want to support.