问:
useing realloc() many times
which one of the following is preferable

```<code>file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);

while(!feof(file))
{
  ++arr_size;
  arr=(unsigned int *)realloc(arr,arr_size*sizeof(unsigned int)
  fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);
</code>```

or this

```<code>arr=(unsigned int *)malloc(some_size*sizeof(unsigned int));
file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);

while(!feof(file))
{
  ++arr_size;
  fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);
</code>```

答: Why not the third way - work out when you open the file how much memory you require?</p>

Title: useing realloc() many times

Body:
which one of the following is preferable

file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);

while(!feof(file))
{
  ++arr_size;
  arr=(unsigned int *)realloc(arr,arr_size*sizeof(unsigned int)
  fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);

or this

arr=(unsigned int *)malloc(some_size*sizeof(unsigned int));
file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);

while(!feof(file))
{
  ++arr_size;
  fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);


来源: stackexchange

问:
ValueError: check_hostname requires server_hostname
I was going to install pandas and epanettools on my computer using the code shown below with python 3.8.5 and I received one Error exception.

Code:

```<code>pip install epanettools
pip install pandas
</code>```

Actually, I could install epanettools on my old computer and I bought a new computer and I wanted to do the same thing on my new computer, but it didn't work and the error exception shown below after running the code shown above:

Error: Exception:

```<code>ERROR: Exception:
Traceback (most recent call last):
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 180, in _main
    status = self.run(options, args)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\req_command.py", line 204, in wrapper
    return func(self, options, args)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\commands\install.py", line 318, in run
    requirement_set = resolver.resolve(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 127, in resolve
    result = self._result = resolver.resolve(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 473, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 341, in resolve
    name, crit = self._merge_into_criterion(r, parent=None)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _merge_into_criterion
    if not criterion.candidates:
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 139, in __bool__
    return bool(self._sequence)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in __bool__
    return any(self)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 129, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 30, in _iter_built
    for version, func in infos:
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 258, in iter_index_candidate_infos
    result = self._finder.find_best_candidate(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 879, in find_best_candidate
    candidates = self.find_all_candidates(project_name)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 824, in find_all_candidates
    page_candidates = list(page_candidates_it)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates
    yield from self._candidates_from_page(self._link)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 783, in process_project_url
    html_page = self._link_collector.fetch_page(project_url)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 512, in fetch_page
    return _get_html_page(location, session=self.session)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 422, in _get_html_page
    resp = _get_html_response(url, session=session)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 120, in _get_html_response
    resp = session.get(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\network\session.py", line 449, in request
    return super().request(method, url, *args, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\cachecontrol\adapter.py", line 53, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 359, in connect
    conn = self._connect_tls_proxy(hostname, conn)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 500, in _connect_tls_proxy
    return ssl_wrap_socket(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 997, in _create
    raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname
</code>```

Could you please tell me how to resolve this error? Appreicate a lot if any advices!

答:
SSL Trust Issues:

```<code>pip install numpy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
</code>```

https://jhooq.com/pip-install-connection-error/

ContentLicense: CC BY-SA 4.0

Body:
I was going to install pandas and epanettools on my computer using the code shown below with python 3.8.5 and I received one Error exception.

Code:

pip install epanettools
pip install pandas

Actually, I could install epanettools on my old computer and I bought a new computer and I wanted to do the same thing on my new computer, but it didn't work and the error exception shown below after running the code shown above:

Error: Exception:

ERROR: Exception:
Traceback (most recent call last):
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 180, in _main
    status = self.run(options, args)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\req_command.py", line 204, in wrapper
    return func(self, options, args)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\commands\install.py", line 318, in run
    requirement_set = resolver.resolve(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 127, in resolve
    result = self._result = resolver.resolve(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 473, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 341, in resolve
    name, crit = self._merge_into_criterion(r, parent=None)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _merge_into_criterion
    if not criterion.candidates:
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 139, in __bool__
    return bool(self._sequence)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in __bool__
    return any(self)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 129, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 30, in _iter_built
    for version, func in infos:
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 258, in iter_index_candidate_infos
    result = self._finder.find_best_candidate(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 879, in find_best_candidate
    candidates = self.find_all_candidates(project_name)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 824, in find_all_candidates
    page_candidates = list(page_candidates_it)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates
    yield from self._candidates_from_page(self._link)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 783, in process_project_url
    html_page = self._link_collector.fetch_page(project_url)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 512, in fetch_page
    return _get_html_page(location, session=self.session)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 422, in _get_html_page
    resp = _get_html_response(url, session=session)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 120, in _get_html_response
    resp = session.get(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\network\session.py", line 449, in request
    return super().request(method, url, *args, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\cachecontrol\adapter.py", line 53, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 359, in connect
    conn = self._connect_tls_proxy(hostname, conn)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 500, in _connect_tls_proxy
    return ssl_wrap_socket(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 997, in _create
    raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname

Could you please tell me how to resolve this error? Appreicate a lot if any advices!

Body:
SSL Trust Issues:

pip install numpy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

https://jhooq.com/pip-install-connection-error/


问:
Create dropdown in Angular like Google
I want to create dropdown like Google, when we click on our Google account pic/logo it dropdown with information like manage account or sign-out etc.

you can see here

Please do let me know or give me code.

答:
your question is not very clear. You can create a dowpdown menu like this:
https://material.angular.io/components/menu/examples#menu-icons
if you don't want to have a menu but a customizable overlay you can do it like this:
https://material.angular.io/cdk/overlay/examples#cdk-overlay-basic</p>

Title: Create dropdown in Angular like Google


问:
Bitbake service file organization
I have a service created and working. However my current bitbake file makes my folder structure very ugly. To have it work I have to have all of my configuration files in my src folder. I would like to have two folders, src and configfiles.
If my tree is as follows

How can I edit my bb file to pull in my src directory and my configfiles?

```<code>LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "file://src"

S = "${WORKDIR}/src"
CF = "${WORKDIR}/configfiles"

inherit systemd autotools
SYSTEMD_SERVICE_${PN} = "helloworld.service"
do_install_append () {
echo "look at this PN ${PN}"
echo "look at this D ${D}"
echo "look at this S ${S}"
echo "look at this CF ${CF}"
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${CF}/helloworld.service ${D}${systemd_system_unitdir}
    sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_system_unitdir}/helloworld.service
}
</code>```

Update 1:
I added a CF variable. Using bitbake -e helloworld > log.txt I can echo the values of variables and noticed we are not pointing to the config files.

```<code>LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "file://src"

S = "${WORKDIR}/src"
CF = "${WORKDIR}/configfiles"

inherit systemd autotools
SYSTEMD_SERVICE_${PN} = "helloworld.service"
do_install_append () {
echo "look at this PN ${PN}"
echo "look at this D ${D}"
echo "look at this S ${S}"
echo "look at this CF ${CF}"
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${CF}/helloworld.service ${D}${systemd_system_unitdir}
    sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_system_unitdir}/helloworld.service
}
</code>```

Bitbake still can not find my makefile.

Update 2:
The solution given works but I have one more question.
My makefile is very basic:

```<code>ACLOCAL_AMFLAGS = -I m4
AUTOMAKE_OPTIONS = foreign

SUBDIRS = app

CFLAGS = -Wall -pedantic
include_HEADERS = helloworld.h

bin_PROGRAMS = helloworld
helloworld_SOURCES = helloworld.c
</code>```

I want to separate my files by folder. I want my main application in a folder /src/app. I edited my makefile to point to app/helloworld.h and app/helloworld.c However this does not find the files. My updated bb file follows

```<code>LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/src/app:${THISDIR}/files/services:"

SRC_URI = "file://src \
       file://src/app \
       "

SRC_URI += "file://helloworld.service \
    file://autogen.sh \
    file://configure.ac \
    file://Makefile.am"

S = "${WORKDIR}/src"

inherit systemd autotools
SYSTEMD_SERVICE_${PN} = "helloworld.service"
do_install_append () {
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_system_unitdir}
    sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_system_unitdir}/helloworld.service
}
</code>```

I understand the makefile should be packaged with the code, This just does not work when creating larger applications.

答:
You need to let bitbake know where to look for files, it sounds like you want to keep the Makefile in a separate directory but in most cases the Makefile should be with the source files, feel free to play around with this, the concept is still the same as explained below.

Either way, your directory structure should look something like this:

```<code>recipes-core/
  helloworld/
    helloworld_0.1.bb
    files/
      configfiles/
        helloworld.service
      src/
        autogen.sh
        configure.ac
        helloworld.c
        helloworld.h
        Makefile.am
</code>```

And to let bitbake know where to pull files you use the FILESESXTRAPATHS variable [1]:

```<code>FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/configfiles:"
</code>```

At this point bitbake knows WHERE to pull the files from, but it doesn't know which files to pull, for this you use the SRC_URI variable (specifically the file:// fetcher) [2]:

```<code>SRC_URI += "file://helloworld.service \
    file://autogen.sh \
    file://configure.ac \
    file://helloworld.c \
    file://helloworld.h \
    file://Makefile.am"
</code>```

This assumes your Makefile will try to find files in the same directory.

The rest of your recipe is fine, the CF variable is no longer necessary, and you just need to change where you're installing the service file from, since SRC_URI[1] will pull it to ${WORKDIR}:

```<code>install -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_system_unitdir}
</code>```

[1] https://docs.yoctoproject.org/singleindex.html#term-FILESEXTRAPATHS

[2] https://docs.yoctoproject.org/bitbake/singleindex.html#term-SRC_URI

Title: Bitbake service file organization

Body:
I have a service created and working. However my current bitbake file makes my folder structure very ugly. To have it work I have to have all of my configuration files in my src folder. I would like to have two folders, src and configfiles.
If my tree is as follows

How can I edit my bb file to pull in my src directory and my configfiles?

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "file://src"

S = "${WORKDIR}/src"
CF = "${WORKDIR}/configfiles"

inherit systemd autotools
SYSTEMD_SERVICE_${PN} = "helloworld.service"
do_install_append () {
echo "look at this PN ${PN}"
echo "look at this D ${D}"
echo "look at this S ${S}"
echo "look at this CF ${CF}"
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${CF}/helloworld.service ${D}${systemd_system_unitdir}
    sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_system_unitdir}/helloworld.service
}

Update 1:
I added a CF variable. Using bitbake -e helloworld > log.txt I can echo the values of variables and noticed we are not pointing to the config files.

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "file://src"

S = "${WORKDIR}/src"
CF = "${WORKDIR}/configfiles"

inherit systemd autotools
SYSTEMD_SERVICE_${PN} = "helloworld.service"
do_install_append () {
echo "look at this PN ${PN}"
echo "look at this D ${D}"
echo "look at this S ${S}"
echo "look at this CF ${CF}"
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${CF}/helloworld.service ${D}${systemd_system_unitdir}
    sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_system_unitdir}/helloworld.service
}

Bitbake still can not find my makefile.

Update 2:
The solution given works but I have one more question.
My makefile is very basic:

ACLOCAL_AMFLAGS = -I m4
AUTOMAKE_OPTIONS = foreign

SUBDIRS = app

CFLAGS = -Wall -pedantic
include_HEADERS = helloworld.h

bin_PROGRAMS = helloworld
helloworld_SOURCES = helloworld.c

I want to separate my files by folder. I want my main application in a folder /src/app. I edited my makefile to point to app/helloworld.h and app/helloworld.c However this does not find the files. My updated bb file follows

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/src/app:${THISDIR}/files/services:"

SRC_URI = "file://src \
       file://src/app \
       "

SRC_URI += "file://helloworld.service \
    file://autogen.sh \
    file://configure.ac \
    file://Makefile.am"

S = "${WORKDIR}/src"

inherit systemd autotools
SYSTEMD_SERVICE_${PN} = "helloworld.service"
do_install_append () {
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_system_unitdir}
    sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_system_unitdir}/helloworld.service
}

I understand the makefile should be packaged with the code, This just does not work when creating larger applications.

Body:
You need to let bitbake know where to look for files, it sounds like you want to keep the Makefile in a separate directory but in most cases the Makefile should be with the source files, feel free to play around with this, the concept is still the same as explained below.

Either way, your directory structure should look something like this:

recipes-core/
  helloworld/
    helloworld_0.1.bb
    files/
      configfiles/
        helloworld.service
      src/
        autogen.sh
        configure.ac
        helloworld.c
        helloworld.h
        Makefile.am

And to let bitbake know where to pull files you use the FILESESXTRAPATHS variable [1]:

FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/configfiles:"

At this point bitbake knows WHERE to pull the files from, but it doesn't know which files to pull, for this you use the SRC_URI variable (specifically the file:// fetcher) [2]:

SRC_URI += "file://helloworld.service \
    file://autogen.sh \
    file://configure.ac \
    file://helloworld.c \
    file://helloworld.h \
    file://Makefile.am"

This assumes your Makefile will try to find files in the same directory.

The rest of your recipe is fine, the CF variable is no longer necessary, and you just need to change where you're installing the service file from, since SRC_URI[1] will pull it to ${WORKDIR}:

install -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_system_unitdir}

[1] https://docs.yoctoproject.org/singleindex.html#term-FILESEXTRAPATHS

[2] https://docs.yoctoproject.org/bitbake/singleindex.html#term-SRC_URI


问:
How to call VS Code Editor from terminal / command line
The question says it all.

How can I open VS Code editor from

windows cmd

linux and mac terminal

e.g. for notepad++ I write

> start notepad++ test.txt

By the way, the editor is awesome (cross-platform)! Thank you Nadella!

You can download it from microsoft

答:
Windows:

Add  code CLI path in a system environment variable.

in windows default code cli path is (username is you pc username)C:\Users\username\AppData\Local\Programs\Microsoft VS Code\bin

Then you can check it like this by taking your project folder and open new cmd and type code .


问:
Passing context through createPage to use in a query, but a string is converted to a number so the query fails
I have a page creatin function wuth this:

createPage({
  context: { productId: String(productId) },
```
<p>As you see, I even forced the ID to be a string, but the page template still receives a number</p>
<pre class="lang-js prettyprint-override"><code>const Template = ({ pageContext, data }) => {
  console.log(pageContext.productId) // number
</code>```

And the following query that expects a string fails:

export const query = graphql`
    myStuff(filter: {productIdentifier: {eq: $productId}}) {
      nodes {
        id
      }
    }
  }
`
```

Any ideas how I can force the productId to be a string?

答:
Have you tried toString()?

```<code>createPage({
  context: { productId: productId.toString() },
</code>```

Even the productId is not being casted, you can also try defining it as a String or Int:

```<code>export const query = graphql`
   query($productId: String!) {
     myStuff(filter: {productIdentifier: {eq: $productId}}) {
      nodes {
        id
      }
    }
  }
}
</code>```

Use $productId: Int! otherwise but I don't know if this will match the filter though.

Another alternative is casting a new string variable before passing it to the context:

```<code>let productIdStringified = productId.toString()
createPage({
  context: { productId: productIdStringified },
</code>```

Body:
I have a page creatin function wuth this:

createPage({
  context: { productId: String(productId) },

As you see, I even forced the ID to be a string, but the page template still receives a number

const Template = ({ pageContext, data }) => {
  console.log(pageContext.productId) // number

And the following query that expects a string fails:

export const query = graphql`
    myStuff(filter: {productIdentifier: {eq: $productId}}) {
      nodes {
        id
      }
    }
  }
`

Any ideas how I can force the productId to be a string?

Body:
Have you tried toString()?

createPage({
  context: { productId: productId.toString() },

Even the productId is not being casted, you can also try defining it as a String or Int:

export const query = graphql`
   query($productId: String!) {
     myStuff(filter: {productIdentifier: {eq: $productId}}) {
      nodes {
        id
      }
    }
  }
}

Use $productId: Int! otherwise but I don't know if this will match the filter though.

Another alternative is casting a new string variable before passing it to the context:

let productIdStringified = productId.toString()
createPage({
  context: { productId: productIdStringified },


问:
Google Cloud VM Shutdown by "Integrity Event"
It seems like my Gooogle Cloud VM was shutdown by an "integrity event":

```<code>{
  "insertId": "3",
  "jsonPayload": {
    "lateBootReportEvent": {
      "policyEvaluationPassed": false,
      "policyMeasurements": [

      ],
      "actualMeasurements": [

      ]
    },
    "@type": "type.googleapis.com/cloud_integrity.IntegrityEvent",
    "bootCounter": "3"
  },
  "resource": {
    "type": "gce_instance",
    "labels": {
      "zone": "us-central1-a",
      "instance_id": "xxx",
      "project_id": "xxx"
    }
  },
  "timestamp": "2022-02-09T03:58:16.830409192Z",
  "severity": "ERROR",
  "logName": "projects/xxx/logs/compute.googleapis.com%2Fshielded_vm_integrity",
  "receiveTimestamp": "2022-02-09T03:58:18.846995634Z"
}
</code>```

Can those be prevented or even disabled somehow?

答:
Can those be prevented or even disabled somehow?

The answer depends on what you mean. You are using a Shielded VM which protects you from:

Prevent tampering with the guest VM image.

Prevent altering sensitive crypto operations.

Prevent exfiltrating secrets sealed in the vTPM

Prevent modifying the system with UEFI drivers.

Prevent modifying guest firmware.

Prevent modifying the kernel.

Those actions will trigger an integrity event. To prevent an integrity event, do not modify the system.

Refer to logName for more information.

Note: lateBootReportEvent compares the original baseline to the latest boot sequence. The integrity policy baseline is used for comparison with measurements from subsequent VM boots to determine if anything has changed.

What is Shielded VM?

Body:
It seems like my Gooogle Cloud VM was shutdown by an "integrity event":

{
  "insertId": "3",
  "jsonPayload": {
    "lateBootReportEvent": {
      "policyEvaluationPassed": false,
      "policyMeasurements": [

      ],
      "actualMeasurements": [

      ]
    },
    "@type": "type.googleapis.com/cloud_integrity.IntegrityEvent",
    "bootCounter": "3"
  },
  "resource": {
    "type": "gce_instance",
    "labels": {
      "zone": "us-central1-a",
      "instance_id": "xxx",
      "project_id": "xxx"
    }
  },
  "timestamp": "2022-02-09T03:58:16.830409192Z",
  "severity": "ERROR",
  "logName": "projects/xxx/logs/compute.googleapis.com%2Fshielded_vm_integrity",
  "receiveTimestamp": "2022-02-09T03:58:18.846995634Z"
}

Can those be prevented or even disabled somehow?


问:
Program took more time than expected error
Below is a program to reverse a doubly linked list in gfg.

When I try to submit, I get the following error

Your program took more time than expected. Time Limit Exceeded
Expected Time Limit 0.00sec.

Can anyone tell me how to decrease my program's time?

Code

```<code>public static Node reverseDLL(Node  head)
{
   Node p,cur;
   p=head;
   cur=head.next;

   while(cur!=null)
   {
       if(cur.next==null)
       {
           p.next=cur.next;
           cur.next=head;
           head.prev=cur;

           head=cur;
           break;
       }

       p.next=cur.next;
       cur.next.prev=p;

       cur.next=head;
       head.prev=cur;

       head=cur;
       cur=p.next;
   }
   return head;

}
</code>```

答:
this is classic solution for O(N) time, so I guess time constraint for this task is required to. solve it for O(1).
Take a look for this thread: https://www.google.com/url?sa=t&source=web&rct=j&url=https://discuss.codechef.com/t/reverse-a-doubly-linked-list-in-o-1/72850&ved=2ahUKEwjipdrQw_T1AhVYLTQIHahIDx8QFnoECBQQAQ&usg=AOvVaw1c0BDUotM0suEK7I4B9pQs</p>

Body:
Below is a program to reverse a doubly linked list in gfg.

When I try to submit, I get the following error

Your program took more time than expected. Time Limit Exceeded
Expected Time Limit 0.00sec.

Can anyone tell me how to decrease my program's time?

Code

public static Node reverseDLL(Node  head)
{
   Node p,cur;
   p=head;
   cur=head.next;

   while(cur!=null)
   {
       if(cur.next==null)
       {
           p.next=cur.next;
           cur.next=head;
           head.prev=cur;

           head=cur;
           break;
       }

       p.next=cur.next;
       cur.next.prev=p;

       cur.next=head;
       head.prev=cur;

       head=cur;
       cur=p.next;
   }
   return head;

}


问:
How do you inject build-specific configuration into an APK?
I have an Android app which I distribute to several different market providers; the app is functionally the same for each, but requires certain distinct configuration parameters.  Ideally I would like to produce all the individual APKs in one build step.  Is there an "official" way to achieve this?

I am considering an approach in which I have a template file in the project structure, and at build time use ant to interpolate values into an output file such as res/xml/config.xml.

Thanks in advance!

答:
There are a couple ways to approach this:

1) Setup an Android Library Application
(designed for Eclipse)

This is the method suggested in the Android documentation. With this method, you would setup your application to be a "Library Project".

Then, for each specific build you would like to produce, you would setup a new Android project that references the previously created Library Project. This project would need to have its own AndroidManifest which declares the components used from the library application. Since each application has its own manifest, almost any type of customization can be made by swapping out components or changing information. However, while allowing for complex differences, this does create some redundancy in maintenance if there is few differences.

2) Built an ANT script or other build script to manipulate the configuration

An ANT script could at build time manipulate the sources or XML files to allow for custom configuration. The easiest way to do this would be use the unix sed or a python/ruby script to do the customization. This is ideal where the customization is limited to small changes and/or just textual replacements. This is my route of choice in most cases.

I recommend copying the source tree to a temporary directory prior to making the manipulations such that it can be cleared on an "ant clean" and will not affect the working copy of the source.

One warning with this is that I would design the modifications such that the source still builds without running the script (i.e. so you can do standard builds while developing in eclipse or any other environment without requiring the special script to run).

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to list all the people who have worked with 'Art Garfunkel'?
I have 3 tables actor, movie, casting. I have to find the people who have worked with actor "ART Garfunkel".

I have solution but I am not able to understand how the following query works.

```<code>**movie**   **actor**    **casting**
   id          id           movieid
   title       name         actorid
   yr                       ord
   director
   budget
   gross

SELECT a.name
  FROM (SELECT movie.*
          FROM movie
          JOIN casting
            ON casting.movieid = movie.id
          JOIN actor
            ON actor.id = casting.actorid
         WHERE actor.name = 'Art Garfunkel') AS m
  JOIN (SELECT actor.*, casting.movieid
          FROM actor
          JOIN casting
            ON casting.actorid = actor.id
         WHERE actor.name != 'Art Garfunkel') as a
    ON m.id = a.movieid;
</code>```

one more solution:

```<code>  SELECT actor.name  FROM casting
       JOIN movie ON movie.id=casting.movieid
      JOIN actor ON  actor.id=casting.actorid
     WHERE actor.name !='Art Garfunkel'
    AND
       movie.id IN(SELECT movie.id FROM casting
           JOIN movie ON movie.id=casting.movieid
       JOIN actor ON  actor.id=casting.actorid
        WHERE actor.name='Art Garfunkel')
</code>```

答:
This simple solution without any heavy join operation is for those who aim for better performamce</p>
```<code>select name from actor where id in (select actorid from casting where movieid in (select movieid from casting where actorid in (select id from actor where name = 'Art Garfunkel'))) and name != 'Art Garfunkel'

</code>```

Body:
I have 3 tables actor, movie, casting. I have to find the people who have worked with actor "ART Garfunkel".

I have solution but I am not able to understand how the following query works.

**movie**   **actor**    **casting**
   id          id           movieid
   title       name         actorid
   yr                       ord
   director
   budget
   gross

SELECT a.name
  FROM (SELECT movie.*
          FROM movie
          JOIN casting
            ON casting.movieid = movie.id
          JOIN actor
            ON actor.id = casting.actorid
         WHERE actor.name = 'Art Garfunkel') AS m
  JOIN (SELECT actor.*, casting.movieid
          FROM actor
          JOIN casting
            ON casting.actorid = actor.id
         WHERE actor.name != 'Art Garfunkel') as a
    ON m.id = a.movieid;

one more solution:

  SELECT actor.name  FROM casting
       JOIN movie ON movie.id=casting.movieid
      JOIN actor ON  actor.id=casting.actorid
     WHERE actor.name !='Art Garfunkel'
    AND
       movie.id IN(SELECT movie.id FROM casting
           JOIN movie ON movie.id=casting.movieid
       JOIN actor ON  actor.id=casting.actorid
        WHERE actor.name='Art Garfunkel')

Body:
This simple solution without any heavy join operation is for those who aim for better performamce

select name from actor where id in (select actorid from casting where movieid in (select movieid from casting where actorid in (select id from actor where name = 'Art Garfunkel'))) and name != 'Art Garfunkel'


问:
Email verification cause error on flutter? why?
I'm developing a food ordering app for that i want to verify the user through email. For that i'm using email verification. i'm using firebase E-mail verification. come to my point i verified the email after verify the email error is founded on flutter. i'm developed the app on flutter. kindly provide some steps to avoid error. I attached the error message below

```<code>E/flutter ( 9906): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 9906): #0      _verifiyState.checkmail (package:datafound/vvvv.dart:31:44)
E/flutter ( 9906): #1      _verifiyState.initState.<anonymous closure> (package:datafound/vvvv.dart:26:55)
E/flutter ( 9906): #2      _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter ( 9906): #3      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 9906): #4      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 9906): #5      _CustomZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1281:26)
E/flutter ( 9906): #6      _rootRunUnary (dart:async/zone.dart:1444:13)
E/flutter ( 9906): #7      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 9906): #8      _CustomZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1265:26)
E/flutter ( 9906): #9      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
E/flutter ( 9906): #10     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
E/flutter ( 9906): #11     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter ( 9906):
</code>```

this error is showing after email verified
and here my code

```<code>
import 'package:datafound/vvvv.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Emailver extends StatefulWidget {
  const Emailver({Key? key}) : super(key: key);

  @override
  _EmailverState createState() => _EmailverState();
}

class _EmailverState extends State<Emailver> {
  TextEditingController emailCtrl = TextEditingController();
  TextEditingController passCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("email verification"),
      ),
      body: Center(
        child: Column(
          children: [
            const SizedBox(
              height: 10.0,
            ),
            TextFormField(
              controller: emailCtrl,
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(
                border:OutlineInputBorder(
                  borderSide: const BorderSide(width: 1, color: Colors.black),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
            const SizedBox(
              height: 10.0,
            ),
            TextFormField(
              controller: passCtrl,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                border:OutlineInputBorder(
                  borderSide: const BorderSide(width: 1, color: Colors.black),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
            const SizedBox(
              height: 10.0,
            ),
            ElevatedButton(onPressed: (){
              signup();
            },
                child: const Text("Sign Up"))
          ],
        ),
      ),
    );
  }

  Future signup() async{
    await FirebaseAuth.instance.createUserWithEmailAndPassword(email: emailCtrl.text, password: passCtrl.text).then((_){
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const verifiy()),
      );
    });
  }

}
</code>```

the above code is for getting email from user

```<code>

import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class verifiy extends StatefulWidget {

  const verifiy({Key? key}) : super(key: key);

  @override
  _verifiyState createState() => _verifiyState();
}

class _verifiyState extends State<verifiy> {
  bool isvv = false;
  Timer? timer;

  @override
  void initState() {
    isvv = FirebaseAuth.instance.currentUser!.emailVerified;
    !isvv ? sendnotfy() : null;
    Timer.periodic(const Duration(seconds: 3), (_) => checkmail(),);
    super.initState();
  }

  Future checkmail() async{
    await FirebaseAuth.instance.currentUser!.reload();
      setState(() {
        isvv = FirebaseAuth.instance.currentUser!.emailVerified;
      });

      if(isvv) timer?.cancel();
  }

    Future sendnotfy() async{
       final user = FirebaseAuth.instance.currentUser!;
       await user.sendEmailVerification();
    }

    @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
              appBar: AppBar(
                title: const Text("verify"),
              ),
              body:  isvv ? Column(
                children: [
                  const Text("verifiy your email"),
                  ElevatedButton(
                    onPressed: (){
                      FirebaseAuth.instance.signOut().then((_){
                        Navigator.pop(context);
                      });
                    },
                    child: const Text("sign out"),
                  )
                ],
              ) :  Center(
                child: Container(
                  color: Colors.red,
                  child: const Text("Check Your Mail and click it"),
                ),
              ) ,
            );
  }
}
</code>```

the above for email verification
please provide solution as soon as possible.
Thank you

答:
You should check null if your statement nullable. Nullable expression "!" If you use it you will get this error.

import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class verifiy extends StatefulWidget {

  const verifiy({Key? key}) : super(key: key);

  @override
  _verifiyState createState() => _verifiyState();
}

class _verifiyState extends State<verifiy> {
  bool isvv = false;
  Timer? timer;

  @override
  void initState() {
  final currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser != null) {
    final isEmailVerifed = currentUser!.emailVerified;
    if (!isEmailVerifed) {
      sendnotfy()
    }
  }
  Timer.periodic(const Duration(seconds: 3), (_) => checkmail(),);
  super.initState();
  }

Future checkmail() async {
  final currentUser = FirebaseAuth.instance.currentUser;
  var isvv = false;
  if (currentUser != null) {
    await currentUser.reload();
    setState(() {
      isvv = currentUser.emailVerified;
    });
  }

  if (isvv) timer?.cancel();
}

Future sendnotfy() async {
  final currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser != null) {
    await currentUser.sendEmailVerification();
  }
}

    @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
              appBar: AppBar(
                title: const Text("verify"),
              ),
              body:  isvv ? Column(
                children: [
                  const Text("verifiy your email"),
                  ElevatedButton(
                    onPressed: (){
                      FirebaseAuth.instance.signOut().then((_){
                        Navigator.pop(context);
                      });
                    },
                    child: const Text("sign out"),
                  )
                ],
              ) :  Center(
                child: Container(
                  color: Colors.red,
                  child: const Text("Check Your Mail and click it"),
                ),
              ) ,
            );
  }
}
```

Body:
I'm developing a food ordering app for that i want to verify the user through email. For that i'm using email verification. i'm using firebase E-mail verification. come to my point i verified the email after verify the email error is founded on flutter. i'm developed the app on flutter. kindly provide some steps to avoid error. I attached the error message below

E/flutter ( 9906): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 9906): #0      _verifiyState.checkmail (package:datafound/vvvv.dart:31:44)
E/flutter ( 9906): #1      _verifiyState.initState.<anonymous closure> (package:datafound/vvvv.dart:26:55)
E/flutter ( 9906): #2      _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter ( 9906): #3      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 9906): #4      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 9906): #5      _CustomZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1281:26)
E/flutter ( 9906): #6      _rootRunUnary (dart:async/zone.dart:1444:13)
E/flutter ( 9906): #7      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 9906): #8      _CustomZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1265:26)
E/flutter ( 9906): #9      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
E/flutter ( 9906): #10     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
E/flutter ( 9906): #11     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter ( 9906):

this error is showing after email verified
and here my code

import 'package:datafound/vvvv.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class Emailver extends StatefulWidget {
  const Emailver({Key? key}) : super(key: key);

  @override
  _EmailverState createState() => _EmailverState();
}

class _EmailverState extends State<Emailver> {
  TextEditingController emailCtrl = TextEditingController();
  TextEditingController passCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("email verification"),
      ),
      body: Center(
        child: Column(
          children: [
            const SizedBox(
              height: 10.0,
            ),
            TextFormField(
              controller: emailCtrl,
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(
                border:OutlineInputBorder(
                  borderSide: const BorderSide(width: 1, color: Colors.black),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
            const SizedBox(
              height: 10.0,
            ),
            TextFormField(
              controller: passCtrl,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                border:OutlineInputBorder(
                  borderSide: const BorderSide(width: 1, color: Colors.black),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
            const SizedBox(
              height: 10.0,
            ),
            ElevatedButton(onPressed: (){
              signup();
            },
                child: const Text("Sign Up"))
          ],
        ),
      ),
    );
  }

  Future signup() async{
    await FirebaseAuth.instance.createUserWithEmailAndPassword(email: emailCtrl.text, password: passCtrl.text).then((_){
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const verifiy()),
      );
    });
  }

}

the above code is for getting email from user

import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class verifiy extends StatefulWidget {

  const verifiy({Key? key}) : super(key: key);

  @override
  _verifiyState createState() => _verifiyState();
}

class _verifiyState extends State<verifiy> {
  bool isvv = false;
  Timer? timer;

  @override
  void initState() {
    isvv = FirebaseAuth.instance.currentUser!.emailVerified;
    !isvv ? sendnotfy() : null;
    Timer.periodic(const Duration(seconds: 3), (_) => checkmail(),);
    super.initState();
  }

  Future checkmail() async{
    await FirebaseAuth.instance.currentUser!.reload();
      setState(() {
        isvv = FirebaseAuth.instance.currentUser!.emailVerified;
      });

      if(isvv) timer?.cancel();
  }

    Future sendnotfy() async{
       final user = FirebaseAuth.instance.currentUser!;
       await user.sendEmailVerification();
    }

    @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
              appBar: AppBar(
                title: const Text("verify"),
              ),
              body:  isvv ? Column(
                children: [
                  const Text("verifiy your email"),
                  ElevatedButton(
                    onPressed: (){
                      FirebaseAuth.instance.signOut().then((_){
                        Navigator.pop(context);
                      });
                    },
                    child: const Text("sign out"),
                  )
                ],
              ) :  Center(
                child: Container(
                  color: Colors.red,
                  child: const Text("Check Your Mail and click it"),
                ),
              ) ,
            );
  }
}

the above for email verification
please provide solution as soon as possible.
Thank you


答:
Hi I know this is late to the party a little simple offering can never offend I hope

Creating a mini temp table I pop'd the dates offered in the original post

and then selected from it as below

create table #DT(

TS_A datetime, TS_B datetime)

insert into #DT (ts_a) values ('2012-01-07 18:18:29.923'),
('2012-01-14 12:58:13.122'),
('2012-06-09 17:10:30.787'),
('2012-05-31 09:29:43.870'),
('2012-10-22 12:09:47.067'),
('2012-10-15 04:35:11.013')

select TS_A, DATEADD(MONTH, DATEDIFF(MONTH, 0,ts_a), 0) TS_B from #DT

Results - I  hope this is clear

RESULTS

Amazing how times they are a changing :-)

TX

I hope this turns out alright haven't posted any where for over a decade

Title: SQL Server 2012: Round to NEAREST(!) start of month (in timestamp format) from a timestamp column)

Body:
I need to round to NEAREST start of month (in timestamp format) from a timestamp column.

How do one accomplish this?

Examples:

TimestampColumn A:             Rounded to these values
2012-01-07 18:18:29.923        2012-01-01 00:00:00.000
2012-01-14 12:58:13.122        2012-01-01 00:00:00.000
2012-06-09 17:10:30.787        2012-06-01 00:00:00.000
2012-05-31 09:29:43.870        2012-06-01 00:00:00.000
2012-10-22 12:09:47.067        2012-11-01 00:00:00.000
2012-10-15 04:35:11.013        2012-10-01 00:00:00.000


问:
How to tell if a website is static or dynamic?
My prof said that dynamic pages get created by the computer, while static pages are created by the user.

Thank you so much!

答:
Its very simple... Only major two factors matter -

A static website does not have artificial intelligence means it cannot add something automatically the user has to type the code for that is he wants to do so but a dynamic website can do it on its own.

A static website cannot store a information means it only includes frontend no backend no php, node.js or something like that. In simpler words if user signin to your website  you would not able to store his username and password.


问:
Listing ofbiz entity in a form
I am learning Ofbiz and I find it quiet hard as it's not well documented and there are not a lot of tutorials about it.
I'm trying to display information from an entity but only the list titles are showing and the no information is displayed.

```<code>    <form name="ListProfile" type="list" list-name="listIt"
        paginate-target="FeedScreen" default-entity-name=""
        separate-columns="true" odd-row-style="alternate-row"
        header-row-style="header-row-2"
        default-table-style="basic-table
        hover-bar">
    <actions>
       <service service-name="performFind" result-map="result" result-map-list="listIt">
           <field-map field-name="inputFields" from-field="parameters"/>
           <field-map field-name="entityName" value="Person"/>
           <field-map field-name="orderBy" from-field="parameters.sortField"/>
           <field-map field-name="viewIndex" from-field="viewIndex"/>
           <field-map field-name="viewSize" from-field="viewSize"/>
        </service>
    </actions>
    <field name="userLoginId" title="userLogin"><display-entity entity-name="UserLogin"/></field>
    <field name="partyId" title="partyId"><display/></field>
    <field name="lastName" title="lastName" sort-field="true"><display/></field>
    <field name="birthDate" title="birthDate" sort-field="true"><display/></field>

</form>
</code>```

I'm wondering also what does the word 'parameters' refer to.

答:
I think your screen has some issue for not getting partyId, lastName and birthDate. You can edit your code as mine. Change location to your form location inside include-form tag.

```<code>     <screen name="ListProfile">
       <section>
        <actions>
            <set field="headerItem" value="ListProfile"/>
            <set field="entityName" value="Person"/>
            <set field="parameters" from-field="parameters"/>
            <entity-and list="list" entity-name="Person" />
        </actions>
        <widgets>
            <decorator-screen name="main-decorator"
                location="${parameters.mainDecoratorLocation}">
                <decorator-section name="body">
                    <screenlet title="Profile List">
                        <section>
                            <widgets>
                                 <include-form name="ListProfile" location="component://humanres/widget/dataimport/DataImportForms.xml"/>
                            </widgets>
                        </section>
                    </screenlet>
                </decorator-section>
            </decorator-screen>
        </widgets>
    </section>
</screen>
</code>```

Now Edit Your Form as mine to get User Login Id from UserLogin Entity and other information from Person Entity

```<code>    <form name="ListProfile" type="list" list-name="list"
    odd-row-style="alternate-row" header-row-style="header-row-2"
    default-table-style="basic-table hover-bar" >
    <actions>

        <service service-name="performFind" result-map="result" result-map-list="list">
            <field-map field-name="inputFields" from-field="parameters"/>
            <field-map field-name="entityName" value="Person"/>
            <field-map field-name="orderBy" from-field="parameters.sortField"/>
            <field-map field-name="viewIndex" from-field="viewIndex"/>
            <field-map field-name="viewSize" from-field="viewSize"/>
        </service>
    </actions>
    <row-actions>
        <entity-and entity-name="UserLogin" list="userLogin">
            <field-map field-name="partyId" from-field="partyId"/>
        </entity-and>
    </row-actions>
    <field name="userLoginId" title="userLogin"><display description="${userLogin[0].userLoginId}"/></field>
    <field name="partyId" title="partyId"><display/></field>
    <field name="lastName" title="lastName" sort-field="true"><display/></field>
    <field name="birthDate" title="birthDate" sort-field="true"><display/></field>
</form>
</code>```

Output Result of mine:

Title: Listing ofbiz entity in a form

Body:
I am learning Ofbiz and I find it quiet hard as it's not well documented and there are not a lot of tutorials about it.
I'm trying to display information from an entity but only the list titles are showing and the no information is displayed.

    <form name="ListProfile" type="list" list-name="listIt"
        paginate-target="FeedScreen" default-entity-name=""
        separate-columns="true" odd-row-style="alternate-row"
        header-row-style="header-row-2"
        default-table-style="basic-table
        hover-bar">
    <actions>
       <service service-name="performFind" result-map="result" result-map-list="listIt">
           <field-map field-name="inputFields" from-field="parameters"/>
           <field-map field-name="entityName" value="Person"/>
           <field-map field-name="orderBy" from-field="parameters.sortField"/>
           <field-map field-name="viewIndex" from-field="viewIndex"/>
           <field-map field-name="viewSize" from-field="viewSize"/>
        </service>
    </actions>
    <field name="userLoginId" title="userLogin"><display-entity entity-name="UserLogin"/></field>
    <field name="partyId" title="partyId"><display/></field>
    <field name="lastName" title="lastName" sort-field="true"><display/></field>
    <field name="birthDate" title="birthDate" sort-field="true"><display/></field>

</form>

I'm wondering also what does the word 'parameters' refer to.

Body:
I think your screen has some issue for not getting partyId, lastName and birthDate. You can edit your code as mine. Change location to your form location inside include-form tag.

     <screen name="ListProfile">
       <section>
        <actions>
            <set field="headerItem" value="ListProfile"/>
            <set field="entityName" value="Person"/>
            <set field="parameters" from-field="parameters"/>
            <entity-and list="list" entity-name="Person" />
        </actions>
        <widgets>
            <decorator-screen name="main-decorator"
                location="${parameters.mainDecoratorLocation}">
                <decorator-section name="body">
                    <screenlet title="Profile List">
                        <section>
                            <widgets>
                                 <include-form name="ListProfile" location="component://humanres/widget/dataimport/DataImportForms.xml"/>
                            </widgets>
                        </section>
                    </screenlet>
                </decorator-section>
            </decorator-screen>
        </widgets>
    </section>
</screen>

Now Edit Your Form as mine to get User Login Id from UserLogin Entity and other information from Person Entity

    <form name="ListProfile" type="list" list-name="list"
    odd-row-style="alternate-row" header-row-style="header-row-2"
    default-table-style="basic-table hover-bar" >
    <actions>

        <service service-name="performFind" result-map="result" result-map-list="list">
            <field-map field-name="inputFields" from-field="parameters"/>
            <field-map field-name="entityName" value="Person"/>
            <field-map field-name="orderBy" from-field="parameters.sortField"/>
            <field-map field-name="viewIndex" from-field="viewIndex"/>
            <field-map field-name="viewSize" from-field="viewSize"/>
        </service>
    </actions>
    <row-actions>
        <entity-and entity-name="UserLogin" list="userLogin">
            <field-map field-name="partyId" from-field="partyId"/>
        </entity-and>
    </row-actions>
    <field name="userLoginId" title="userLogin"><display description="${userLogin[0].userLoginId}"/></field>
    <field name="partyId" title="partyId"><display/></field>
    <field name="lastName" title="lastName" sort-field="true"><display/></field>
    <field name="birthDate" title="birthDate" sort-field="true"><display/></field>
</form>

Output Result of mine:


问:
rails 6 Cannot find module 'jquery'
whats wrong there?

webpacker says:
Cannot find module 'jquery'

i have running multiple rails apps, but, now, do i not see my eyeglasses before my eyes?

config/webpack/environment.js

```<code>const { environment } = require('@rails/webpacker')

const webpack = require('webpack');
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery',
        Popper: ['popper.js', 'default']
    })
);

const aliasConfig = {
    'jquery': 'jquery-ui-dist/external/jquery/jquery.js',
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
};
environment.config.set('resolve.alias', aliasConfig);

module.exports = environment
</code>```

javascript/packs/application.js

```<code>require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import 'foundation-sites';

//jquery and jquery-ui
require("jquery")
require("jquery-ui")

require("foundation");
</code>```

package.js

```<code>{
  "name": "passwords",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.3.0",
    "foundation-sites": "^6.7.2",
    "jquery": "^3.6.0",
    "jquery-ui": "^1.12.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^4.2.1"
  }
}
</code>```

答:
yes, my webpacker is running well.
differing from above, my settings are:

config/webpack/environment.js like above, but without the line "poper".

packs/application.js

```<code>// jquery and jquery-ui
require("jquery")
require("jquery-ui")
import $ from 'jquery';
global.$ = jQuery;
</code>```

and: Webpacker is not running with current version of node! i am using node -v 12.22.9 (for me the best was is managing node by nvm). yarn should be used at the current version.

jquery is installed by yarn add jquery

note:
now rails 7 will come soon and webpacker will no longer part of rails default package. currently its too early yet.

Title: rails 6 Cannot find module 'jquery'

Body:
whats wrong there?

webpacker says:
Cannot find module 'jquery'

i have running multiple rails apps, but, now, do i not see my eyeglasses before my eyes?

config/webpack/environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack');
environment.plugins.prepend('Provide',
    new webpack.ProvidePlugin({
        $: 'jquery/src/jquery',
        jQuery: 'jquery/src/jquery',
        Popper: ['popper.js', 'default']
    })
);

const aliasConfig = {
    'jquery': 'jquery-ui-dist/external/jquery/jquery.js',
    'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
};
environment.config.set('resolve.alias', aliasConfig);

module.exports = environment

javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import 'foundation-sites';

//jquery and jquery-ui
require("jquery")
require("jquery-ui")

require("foundation");

package.js

{
  "name": "passwords",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.3.0",
    "foundation-sites": "^6.7.2",
    "jquery": "^3.6.0",
    "jquery-ui": "^1.12.1",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^4.2.1"
  }
}

Body:
yes, my webpacker is running well.
differing from above, my settings are:

config/webpack/environment.js like above, but without the line "poper".

packs/application.js

// jquery and jquery-ui
require("jquery")
require("jquery-ui")
import $ from 'jquery';
global.$ = jQuery;

and: Webpacker is not running with current version of node! i am using node -v 12.22.9 (for me the best was is managing node by nvm). yarn should be used at the current version.

jquery is installed by yarn add jquery

note:
now rails 7 will come soon and webpacker will no longer part of rails default package. currently its too early yet.


问:
how to pause and rewind swf flash using SWF Object
i used http://code.google.com/p/swfobject/ SWF object to play the swf file. I am able to embed and play  but i am not getting any api java script to pause,rewind forward API for that any one done this ?</p>

答:
SWFObject is just a tool for embedding Flash content in a webpage.  If you want to control the flow of your SWF with JavaScript you will have to communicate with it using ExternalInterface.

This will require you to to code the functionality you require in Flash, and then expose those functions using ExternalInterface so that you can call them from your page using JavaScript.


问:
Mockito cannot mock this class
I am attempting to mock a public class, however when doing so, Mockito throws an Mockito cannot mock this class exception.

Class I wish to mock: https://github.com/scribejava/scribejava/blob/master/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java

Test code:

```<code>package xyz.jacobclark.adapter;

import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.io.IOException;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsInstanceOf.any;

@RunWith(MockitoJUnitRunner.class)
public class TwitterOAuthAdapterTest {
    @Mock
    ServiceBuilder serviceBuilder;

    @Test
    public void getRequestTokenShouldReturnAValidRequestToken() throws IOException {
        class TwitterOAuthAdapter {
            private final OAuth10aService service;

            public TwitterOAuthAdapter(ServiceBuilder serviceBuilder){
                this.service = serviceBuilder
                    .apiKey("")
                    .apiSecret("")
                    .build(TwitterApi.instance());
            }

            public OAuth1RequestToken getRequestToken() throws IOException {
                return this.service.getRequestToken();
            }
        }

        TwitterOAuthAdapter oAuthAdapter = new TwitterOAuthAdapter(serviceBuilder);
        Assert.assertThat(oAuthAdapter.getRequestToken(), is(any(OAuth1RequestToken.class)));
    }
}
</code>```

Full stacktrace:

```<code>xyz.jacobclark.adapter.TwitterOAuthAdapterTest

org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.github.scribejava.core.builder.ServiceBuilder.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.0-b70
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0-b132
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.11.3

Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class

    at org.mockito.internal.runners.SilentJUnitRunner$1.withBefores(SilentJUnitRunner.java:29)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.SilentJUnitRunner.run(SilentJUnitRunner.java:39)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:103)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3843)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator$Chained.resolve(TypeDescription.java:3468)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3803)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3439)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:4748)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:680)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:663)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType.accept(TypeDescription.java:4656)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:691)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:663)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfParameterizedType.accept(TypeDescription.java:4998)
    at net.bytebuddy.description.type.TypeList$Generic$AbstractBase.accept(TypeList.java:249)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing$RetainedTypeVariable.getUpperBounds(TypeDescription.java:832)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable.asErasure(TypeDescription.java:5373)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asTypeToken(MethodDescription.java:701)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Harmonized.of(MethodGraph.java:881)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Store.registerTopLevel(MethodGraph.java:1074)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:588)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:548)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyzeNullable(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:581)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:521)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:442)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:480)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:160)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:153)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2568)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2670)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:84)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$CachedBytecodeGenerator.getOrGenerateMockClass(TypeCachingBytecodeGenerator.java:91)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:38)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:67)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:38)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:26)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
    at org.mockito.Mockito.mock(Mockito.java:1637)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:39)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:63)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:59)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:43)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:67)
    ... 23 more

Test ignored.
Process finished with exit code 255
</code>```

答:
I had the same issues.

My dependencies:

spring-boot-parent:2.0.5.RELEASE

org.testcontainers:1.16.3

I needed to start the app on Apple M1 with JVM 11

My tests failed with some issue.

I found in logs what used ~[mockito-core-2.15.0.jar:na]

After read the topic, I added one lib for fix my issue

```<code>        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.18.0</version>
            <scope>test</scope>
        </dependency>
</code>```

And for start testcontainers on Apple M1 is used fresh JNA

```<code>        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>5.10.0</version>
            <scope>test</scope>
        </dependency>
</code>```

Title: Mockito cannot mock this class

Body:
I am attempting to mock a public class, however when doing so, Mockito throws an Mockito cannot mock this class exception.

Class I wish to mock: https://github.com/scribejava/scribejava/blob/master/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java

Test code:

package xyz.jacobclark.adapter;

import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.io.IOException;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsInstanceOf.any;

@RunWith(MockitoJUnitRunner.class)
public class TwitterOAuthAdapterTest {
    @Mock
    ServiceBuilder serviceBuilder;

    @Test
    public void getRequestTokenShouldReturnAValidRequestToken() throws IOException {
        class TwitterOAuthAdapter {
            private final OAuth10aService service;

            public TwitterOAuthAdapter(ServiceBuilder serviceBuilder){
                this.service = serviceBuilder
                    .apiKey("")
                    .apiSecret("")
                    .build(TwitterApi.instance());
            }

            public OAuth1RequestToken getRequestToken() throws IOException {
                return this.service.getRequestToken();
            }
        }

        TwitterOAuthAdapter oAuthAdapter = new TwitterOAuthAdapter(serviceBuilder);
        Assert.assertThat(oAuthAdapter.getRequestToken(), is(any(OAuth1RequestToken.class)));
    }
}

Full stacktrace:

xyz.jacobclark.adapter.TwitterOAuthAdapterTest

org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.github.scribejava.core.builder.ServiceBuilder.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.0-b70
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0-b132
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.11.3

Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class

    at org.mockito.internal.runners.SilentJUnitRunner$1.withBefores(SilentJUnitRunner.java:29)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.SilentJUnitRunner.run(SilentJUnitRunner.java:39)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:103)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3843)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator$Chained.resolve(TypeDescription.java:3468)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3803)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3439)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:4748)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:680)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:663)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType.accept(TypeDescription.java:4656)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:691)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:663)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfParameterizedType.accept(TypeDescription.java:4998)
    at net.bytebuddy.description.type.TypeList$Generic$AbstractBase.accept(TypeList.java:249)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing$RetainedTypeVariable.getUpperBounds(TypeDescription.java:832)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable.asErasure(TypeDescription.java:5373)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asTypeToken(MethodDescription.java:701)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Harmonized.of(MethodGraph.java:881)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Store.registerTopLevel(MethodGraph.java:1074)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:588)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:548)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyzeNullable(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:581)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:521)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:442)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:480)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:160)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:153)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2568)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2670)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:84)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$CachedBytecodeGenerator.getOrGenerateMockClass(TypeCachingBytecodeGenerator.java:91)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:38)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:67)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:38)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:26)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
    at org.mockito.Mockito.mock(Mockito.java:1637)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:39)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:63)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:59)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:43)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:67)
    ... 23 more

Test ignored.
Process finished with exit code 255

Body:
I had the same issues.

My dependencies:

spring-boot-parent:2.0.5.RELEASE

org.testcontainers:1.16.3

I needed to start the app on Apple M1 with JVM 11

My tests failed with some issue.

I found in logs what used ~[mockito-core-2.15.0.jar:na]

After read the topic, I added one lib for fix my issue

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.18.0</version>
            <scope>test</scope>
        </dependency>

And for start testcontainers on Apple M1 is used fresh JNA

        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>5.10.0</version>
            <scope>test</scope>
        </dependency>


问:
Google Cloud Functions Deploy "allow unauthenticated invocations..."
Whenever I have to deploy a new python function using the gcloud sdk I get this message

Allow unauthenticated invocations of new function  [function-name]?

(y/N)?

WARNING: Function created with limited-access IAM policy. To enable unauthorized access consider

"gcloud alpha functions add-iam-policy-binding function-name --region=europe-west1 --member=allUsers --role=roles/cloudfunctions.invoker"

Is there any flag I can add to the command to make it a NO when deploying?

This is a sample command I use to deploy one function:

```<code>gcloud functions deploy function-name --region=europe-west1 --entry-point function-entry-point --trigger-resource "projects/my-project/databases/(default)/documents/user_ids/{user_id}" --trigger-event providers/cloud.firestore/eventTypes/document.create --runtime python37 --timeout 60 --project my-project
</code>```

答:
I just encountered this problem as well and discovered that you can supply --no-allow-unauthenticated to pre-emptively answer "no" to this question.

```<code>gcloud functions deploy MyFunction \
  --runtime=go116 --trigger-http --no-allow-unauthenticated
</code>```

Body:
Whenever I have to deploy a new python function using the gcloud sdk I get this message

Allow unauthenticated invocations of new function  [function-name]?

(y/N)?

WARNING: Function created with limited-access IAM policy. To enable unauthorized access consider

"gcloud alpha functions add-iam-policy-binding function-name --region=europe-west1 --member=allUsers --role=roles/cloudfunctions.invoker"

Is there any flag I can add to the command to make it a NO when deploying?

This is a sample command I use to deploy one function:

gcloud functions deploy function-name --region=europe-west1 --entry-point function-entry-point --trigger-resource "projects/my-project/databases/(default)/documents/user_ids/{user_id}" --trigger-event providers/cloud.firestore/eventTypes/document.create --runtime python37 --timeout 60 --project my-project

Body:
I just encountered this problem as well and discovered that you can supply --no-allow-unauthenticated to pre-emptively answer "no" to this question.

gcloud functions deploy MyFunction \
  --runtime=go116 --trigger-http --no-allow-unauthenticated


问:
dotfiles (zsh setup) in GitHub Codespaces: no effect
I'm trying to get GitHub codespaces to recognize my dotfiles, to auto-setup zsh shell.

When I enter a codespace, either on the web or from VSCode the dotfiles have no effect. No error message either.

Here's what I've done

Created a public dotfiles repo on GitHub, containing .zshrc and setup.sh (contents below).  Added the files directly via the "add file" on github.com, then copy/paste.

Enabled auto-run dotfiles in Codespaces via github.com > settings > codespaces > use dotfiles = true (checkbox)

VSCode > settings > linux default shell > zsh

setup.sh

```<code>#!/bin/bash

git clone git://github.com/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-history-substring-search ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-history-substring-search
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting

cat .zshrc > $HOME/.zshrc
</code>```

.zshrc

```<code>export ZSH="${HOME}/.oh-my-zsh"

ZSH_THEME="robbyrussell"

DISABLE_UNTRACKED_FILES_DIRTY="true"

plugins=(zsh-autosuggestions history-substring-search zsh-syntax-highlighting)

source $ZSH/oh-my-zsh.sh

PROMPT="*** zsh *** %~   "

</code>```

答:
I have noticed that dotfiles don't get applied to the zsh shell that first comes up right after re-building the codespace. I'm still looking into this to understand it better. Starting a new zsh shell fixes the issue for me -- the dotfiles get applied. Does that fix the issue for you?

Also, I recommend doing a symlink instead of cat, in the setup.sh. See my blog post for more details: https://bea.stollnitz.com/blog/codespaces-terminal/

Body:
I'm trying to get GitHub codespaces to recognize my dotfiles, to auto-setup zsh shell.

When I enter a codespace, either on the web or from VSCode the dotfiles have no effect. No error message either.

Here's what I've done

Created a public dotfiles repo on GitHub, containing .zshrc and setup.sh (contents below).  Added the files directly via the "add file" on github.com, then copy/paste.

Enabled auto-run dotfiles in Codespaces via github.com > settings > codespaces > use dotfiles = true (checkbox)

VSCode > settings > linux default shell > zsh

setup.sh

#!/bin/bash

git clone git://github.com/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-history-substring-search ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-history-substring-search
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting

cat .zshrc > $HOME/.zshrc

.zshrc

export ZSH="${HOME}/.oh-my-zsh"

ZSH_THEME="robbyrussell"

DISABLE_UNTRACKED_FILES_DIRTY="true"

plugins=(zsh-autosuggestions history-substring-search zsh-syntax-highlighting)

source $ZSH/oh-my-zsh.sh

PROMPT="*** zsh *** %~   "


问:
Why does the passport.js create an Unauthorized page on its own when authentication fails? how can I redirect it to a special page?
here is my router:

```<code>  router.post('/login',
  passport.authenticate('local'),
  (req, res, next) => {
    body('backurl').trim().escape();
    let referrer = req.get('Referrer')
    if (!req.user) {
      return res.render('login', {
        message: 'Unable to login, the password or the username are wrong',
        backUrl: referrer
      });
    }
    if (req.body.backurl == null || req.body.backurl == 'http://localhost:3000/signup' || req.body.backurl == 'http://localhost:3000/login') {
      return res.redirect('/yourcourses');
    }

    return res.redirect(req.body.backurl);
  }
);
</code>```

When the user and the local authentication works it does work perfectly, however on fail I want to render the login page again with a message and a variable, however on failure the website simply makes an empty page with the word "unauthorized" on it without anything else, how do I fix it?
thanks!

答:
When authentication in Passport fails, the next() function is not called, the middleware chain is stopped and a generic error is returned, that's why your code isn't executing.

The solution could be to create another route, for example '/loginfail', and moving in there the code that re-renders the 'login' page with the referrer and the error message.

Then, modify the call to passport.authenticate to include an options object, like this:

passport.authenticate('local', { failureRedirect: '/loginfail' });
```

So, when authentication fails, Passport calls the route you specified.

Body:
here is my router:

  router.post('/login',
  passport.authenticate('local'),
  (req, res, next) => {
    body('backurl').trim().escape();
    let referrer = req.get('Referrer')
    if (!req.user) {
      return res.render('login', {
        message: 'Unable to login, the password or the username are wrong',
        backUrl: referrer
      });
    }
    if (req.body.backurl == null || req.body.backurl == 'http://localhost:3000/signup' || req.body.backurl == 'http://localhost:3000/login') {
      return res.redirect('/yourcourses');
    }

    return res.redirect(req.body.backurl);
  }
);

When the user and the local authentication works it does work perfectly, however on fail I want to render the login page again with a message and a variable, however on failure the website simply makes an empty page with the word "unauthorized" on it without anything else, how do I fix it?
thanks!

Body:
When authentication in Passport fails, the next() function is not called, the middleware chain is stopped and a generic error is returned, that's why your code isn't executing.

The solution could be to create another route, for example '/loginfail', and moving in there the code that re-renders the 'login' page with the referrer and the error message.

Then, modify the call to passport.authenticate to include an options object, like this:

passport.authenticate('local', { failureRedirect: '/loginfail' });

So, when authentication fails, Passport calls the route you specified.


问:
Where can I find high-quality artwork for my app?
I am looking especially for tab bar icons, buttons and backgrounds. Are there any websites intended for this purpose?</p>

答: Glyphish have great icons I use in lots of apps. Their pro series are well worth the modest cost.</p>


问:
how to check if video is landscape or portrait using ffmpeg php?
I have to check the video is landscape or portrait before rotate using ffmpge .
please help me.</p>

答:
Sometimes we are getting 2 types of output "640x268 [SAR 1:1 DAR 160:67]" and "640x268"</p>
```<code>$output = shell_exec("FFmpeg -i ".$localVideoPath." -vstats 2>&1");
            $out_arr = explode("\n", $output);
            foreach($out_arr as $line) {
                if( preg_match('/^Stream.*Video:/', trim($line)) ) {
                    $line_arr = explode(',', $line);

                    if (str_contains($line_arr[2], 'x')) {
                        //540x960
                        $target_arr = explode(' ', $line_arr[2]);
                        $dims = explode('x', $target_arr[1]);
                    }else{
                        //640x268 [SAR 1:1 DAR 160:67]
                        $target_arr = explode(' ', $line_arr[3]);
                        $dims = explode('x', $target_arr[1]);
                    }
                    $res_x = $dims[0];
                    $res_y = $dims[1];
                }
            }

            if(!(isset($res_x) && isset($res_y))){
                //die('Could not get dimensions');
            } else {
                $orientation = ($res_x < $res_y) ? 'Portrait' : 'Landscape';
            }
</code>```

Body:
Sometimes we are getting 2 types of output "640x268 [SAR 1:1 DAR 160:67]" and "640x268"

$output = shell_exec("FFmpeg -i ".$localVideoPath." -vstats 2>&1");
            $out_arr = explode("\n", $output);
            foreach($out_arr as $line) {
                if( preg_match('/^Stream.*Video:/', trim($line)) ) {
                    $line_arr = explode(',', $line);

                    if (str_contains($line_arr[2], 'x')) {
                        //540x960
                        $target_arr = explode(' ', $line_arr[2]);
                        $dims = explode('x', $target_arr[1]);
                    }else{
                        //640x268 [SAR 1:1 DAR 160:67]
                        $target_arr = explode(' ', $line_arr[3]);
                        $dims = explode('x', $target_arr[1]);
                    }
                    $res_x = $dims[0];
                    $res_y = $dims[1];
                }
            }

            if(!(isset($res_x) && isset($res_y))){
                //die('Could not get dimensions');
            } else {
                $orientation = ($res_x < $res_y) ? 'Portrait' : 'Landscape';
            }


问:
How to get current timezone region (tz database name) in Flutter
I am new to flutter and my rest api takes current timezone as Europe/london. I don't know to get current timezone in flutter. There is a question in stackoverflow about this topic but no user gave the answer.

Flutter Timezone (as ZoneId)

Can anyone guide me, how can i get the current timezone in flutter using dart.

答:
```<code>import 'package:intl/intl.dart';

DateTime startDate = DateTime.now().toLocal();
var date = DateFormat.yMMMd().format(startDate);
</code>```