问:
How to serialize Firestore TimeStamp in Android Java?
I am passing a Class as Extras and the class has TimeStamp as a member and getting the following error, how to serialize TimeStamp?

Error:

```<code>java.io.NotSerializableException: com.google.firebase.Timestamp
</code>```

答: Timestamp contains just two numbers, seconds and nanoseconds.  You can serialize them each separately, then recreate the Timestamp using its constructor that takes both values.  Or you can take advantage of the fact that it's Parcelable.</p>

Body:
I am passing a Class as Extras and the class has TimeStamp as a member and getting the following error, how to serialize TimeStamp?

Error:

java.io.NotSerializableException: com.google.firebase.Timestamp


来源: stackexchange

问:
Used kotlin-spring plugin, still getting class not open error
I am getting a class cannot be final, needs to be open, despite adding the kotlin-spring plugin. The whole purpose of the plugin is to not manually add the open keyword to every class.

Please guide me on getting the Kotling-Spring plugin to work with code below.

build.gradle

```<code>buildscript {
    ext.kotlin_version = "1.1.2"

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
    }
}

apply plugin: "kotlin"
apply plugin: "kotlin-spring"
apply plugin: "kotlin-noarg"
apply plugin: "idea"

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile"org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "org.springframework:spring-context:4.3.8.RELEASE"
    testCompile "org.springframework:spring-test:4.3.8.RELEASE"
    testCompile "junit:junit:4.11"
}
</code>```

AppConfig.java

```<code>@Configuration
class AppConfig {

    @Bean
    fun game(): Game {
        return BaseballGame(redSox(),cubs())
    }

    @Bean
    fun redSox(): Team {
        return RedSox()
    }

    @Bean
    fun cubs(): Team {
        return Cubs()
    }
}
</code>```

Error:

```<code>Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Configuration class 'AppConfig' may not be final. Remove the final modifier to continue.
Offending resource: AppConfig
</code>```

REF: https://kotlinlang.org/docs/reference/using-gradle.html#plugin-and-versions

答:
I too faced Similar Issue while Running Springboot Application . Finally I learnt that Kotlin Class are final by Default . You need to add open before class Name

So , you need to change class modifier as follows :

open class AppConfig {

Reference :

http://engineering.pivotal.io/post/spring-boot-application-with-kotlin/

ContentLicense: CC BY-SA 3.0

Body:
I am getting a class cannot be final, needs to be open, despite adding the kotlin-spring plugin. The whole purpose of the plugin is to not manually add the open keyword to every class.

Please guide me on getting the Kotling-Spring plugin to work with code below.

build.gradle

buildscript {
    ext.kotlin_version = "1.1.2"

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
    }
}

apply plugin: "kotlin"
apply plugin: "kotlin-spring"
apply plugin: "kotlin-noarg"
apply plugin: "idea"

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile"org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "org.springframework:spring-context:4.3.8.RELEASE"
    testCompile "org.springframework:spring-test:4.3.8.RELEASE"
    testCompile "junit:junit:4.11"
}

AppConfig.java

@Configuration
class AppConfig {

    @Bean
    fun game(): Game {
        return BaseballGame(redSox(),cubs())
    }

    @Bean
    fun redSox(): Team {
        return RedSox()
    }

    @Bean
    fun cubs(): Team {
        return Cubs()
    }
}

Error:

Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Configuration class 'AppConfig' may not be final. Remove the final modifier to continue.
Offending resource: AppConfig

REF: https://kotlinlang.org/docs/reference/using-gradle.html#plugin-and-versions

ContentLicense: CC BY-SA 4.0


问:
How do I interpolate a variable as a key in a JavaScript object?
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

```<code>var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`
</code>```

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?

答:
Try this:

```<code>var a = "whatever";
var c = "something";
var b = {whatever : 20, something: 37};
alert(b[a]); // Shows 20
alert(b[c]); // Shows 37
</code>```

Here is the fiddle.

Or if I understand from the below comments correctly, try this:

```<code>var a = "whatever";
var b = {a : 20};
alert(b.a); // Shows 20
</code>```

Body:
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?

Body:
Try this:

var a = "whatever";
var c = "something";
var b = {whatever : 20, something: 37};
alert(b[a]); // Shows 20
alert(b[c]); // Shows 37

Here is the fiddle.

Or if I understand from the below comments correctly, try this:

var a = "whatever";
var b = {a : 20};
alert(b.a); // Shows 20


问:
modify/access python instance from external script or command
I have a main python code running (at startup) with an instance of a class in it. I would like to be able to modify this instance (its arguments) when I want (as a user). The idea is to be able to modify it without disturbing the main code or forcing it to read an external script every 2 seconds.  So, I would be able to run a bash command or a new python script that will modify this instance created in the main running script.

I use python 3 and already though/tried different things:

write a method with an opened socket listening in the class corresponding to the instance. Seems overkill to me.

be able to access the instance from its memory address with some tools such as ctypes and id. But I got errors in this way (Segmentation fault)

from terminal 1:

```<code>>>> a='c'
>>> hex(id(a))
'0x7fc9f825a378'
</code>```

from terminal 2:

```<code>>>> import ctypes
>>> d = (ctypes.c_char).from_address(0x7fc9f825a378)
>>> d
Segmentation fault (core dumped)
</code>```

So, how can I modify an instance in a running script from my archlinux os as a user?

Thanks a lot for your time

答:
I did have a look at everything I could find about python share memory. But I did not find any solution to just share a dictionary or a "normal" array on my POSIX system.

sysv_ipc or posix_ipc use buffers for strings, complicating everything (needs parsing).

multiprocessing permits to do it but from the same script, there is no id/key to access it from another python instance.

SharedArray do it but with numpy arrays.

Do you know a shared memory python library that permits to simply share an object such as dictionary or normal list?

Thanks for your time.

Body:
I have a main python code running (at startup) with an instance of a class in it. I would like to be able to modify this instance (its arguments) when I want (as a user). The idea is to be able to modify it without disturbing the main code or forcing it to read an external script every 2 seconds.  So, I would be able to run a bash command or a new python script that will modify this instance created in the main running script.

I use python 3 and already though/tried different things:

write a method with an opened socket listening in the class corresponding to the instance. Seems overkill to me.

be able to access the instance from its memory address with some tools such as ctypes and id. But I got errors in this way (Segmentation fault)

from terminal 1:

>>> a='c'
>>> hex(id(a))
'0x7fc9f825a378'

from terminal 2:

>>> import ctypes
>>> d = (ctypes.c_char).from_address(0x7fc9f825a378)
>>> d
Segmentation fault (core dumped)

So, how can I modify an instance in a running script from my archlinux os as a user?

Thanks a lot for your time


问:
Could not use os.fork() bind several process to one socket server when using asyncio
We all know that using asyncio substantially improves the performance of a socket server, and obviously things get even more awesome if we could take advantage of all cores in our cpu (maybe via multiprocessing module or os.fork() etc.)

I'm now trying to build a multicore socket server demo, with a asynchronous socket server listening on each core and all binding to one port. Simply by creating a async server and then use os.fork(), let processes work competitively.

However the single-core-fine code runs into some trouble when I'm trying to fork. Seems like there's some problem with registering same filedescriptors from different processes in epoll selector module.

I'm showing some code below, can anyone help me out?

Here's a simple, logically clear code of echo server using asyncio:

import os
import asyncio #,uvloop
from socket import *

# hendler sends back incoming message directly
async def handler(loop, client):
    with client:
        while True:
            data = await loop.sock_recv(client, 64)
            if not data:
                break
            await loop.sock_sendall(client, data)

# create tcp server
async def create_server(loop):
    sock = socket(AF_INET ,SOCK_STREAM)
    sock.setsockopt(SOL_SOCKET , SO_REUSEADDR ,1)
    sock.bind(('',25000))
    sock.listen()
    sock.setblocking(False)
    return sock

# whenever accept a request, create a handler task in eventloop
async def serving(loop, sock):
    while True:
        client ,addr = await loop.sock_accept(sock)
        loop.create_task(handler(loop ,client))

loop = asyncio.get_event_loop()
sock = loop.run_until_complete(create_server(loop))
loop.create_task(serving(loop, sock))
loop.run_forever()

```

<p>It works fine until I'm trying to fork, after the socket was bounl and before server starts serving. (This logic works fine in synchronous -- threading based code.)</p>

<hr>

<p>When I'm trying this:</p>

<pre class="lang-py prettyprint-override"><code>loop = asyncio.get_event_loop()
sock = loop.run_until_complete(create_server(loop))

from multiprocessing import cpu_count
for num in range(cpu_count() - 1):
    pid = os.fork()
    if pid <= 0:            # fork process as the same number as
        break               # my cpu cores

loop.create_task(serving(loop, sock))
loop.run_forever()
</code>```

Theoretically forked process are bounl to a same socket? And run in a same event loop? then work just fine?

However I'm getting these error messages:

```<code>Task exception was never retrieved
future: <Task finished coro=<serving() done, defined at /home/new/LinuxDemo/temp1.py:21> exception=FileExistsError(17, 'File exists')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 262, in _add_reader
    key = self._selector.get_key(fd)
  File "/usr/local/lib/python3.7/selectors.py", line 192, in get_key
    raise KeyError("{!r} is not registered".format(fileobj)) from None
KeyError: '6 is not registered'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/test/temp1.py", line 23, in serving
    client ,addr = await loop.sock_accept(sock)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 525, in sock_accept
    self._sock_accept(fut, False, sock)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 538, in _sock_accept
    self.add_reader(fd, self._sock_accept, fut, True, sock)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 335, in add_reader
    return self._add_reader(fd, callback, *args)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 265, in _add_reader
    (handle, None))
  File "/usr/local/lib/python3.7/selectors.py", line 359, in register
    self._selector.register(key.fd, poller_events)
FileExistsError: [Errno 17] File exists

</code>```

Python version 3.7.3,

I'm totally confused about what's going on.

Could anybody help? thanks

答:
According to the tracker issue, it is not supported to fork an existing asyncio event loop and attempt to use it from multiple processes. However, according to Yury's comment on the same issue, multi-processing can be implemented by forking before starting a loop, therefore running fully independent asyncio loops in each child.

Your code actually confirms this possibility: while create_server is async def, it doesn't await anything, nor does it use the loop argument. So we can implement Yury's approach by by making create_server a regular function, removing the loop argument, and calling it before os.fork(), and only running event loops after forking:

```<code>import os, asyncio, socket, multiprocessing

async def handler(loop, client):
    with client:
        while True:
            data = await loop.sock_recv(client, 64)
            if not data:
                break
            await loop.sock_sendall(client, data)

# create tcp server
def create_server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 25000))
    sock.listen()
    sock.setblocking(False)
    return sock

# whenever accept a request ,create a handler task in eventloop
async def serving(loop, sock):
    while True:
        client, addr = await loop.sock_accept(sock)
        loop.create_task(handler(loop, client))

sock = create_server()

for num in range(multiprocessing.cpu_count() - 1):
    pid = os.fork()
    if pid <= 0:            # fork process as the same number as
        break               # my cpu cores

loop = asyncio.get_event_loop()
loop.create_task(serving(loop, sock))
loop.run_forever()
</code>```

Body:
We all know that using asyncio substantially improves the performance of a socket server, and obviously things get even more awesome if we could take advantage of all cores in our cpu (maybe via multiprocessing module or os.fork() etc.)

I'm now trying to build a multicore socket server demo, with a asynchronous socket server listening on each core and all binding to one port. Simply by creating a async server and then use os.fork(), let processes work competitively.

However the single-core-fine code runs into some trouble when I'm trying to fork. Seems like there's some problem with registering same filedescriptors from different processes in epoll selector module.

I'm showing some code below, can anyone help me out?

Here's a simple, logically clear code of echo server using asyncio:

import os
import asyncio #,uvloop
from socket import *

# hendler sends back incoming message directly
async def handler(loop, client):
    with client:
        while True:
            data = await loop.sock_recv(client, 64)
            if not data:
                break
            await loop.sock_sendall(client, data)

# create tcp server
async def create_server(loop):
    sock = socket(AF_INET ,SOCK_STREAM)
    sock.setsockopt(SOL_SOCKET , SO_REUSEADDR ,1)
    sock.bind(('',25000))
    sock.listen()
    sock.setblocking(False)
    return sock

# whenever accept a request, create a handler task in eventloop
async def serving(loop, sock):
    while True:
        client ,addr = await loop.sock_accept(sock)
        loop.create_task(handler(loop ,client))

loop = asyncio.get_event_loop()
sock = loop.run_until_complete(create_server(loop))
loop.create_task(serving(loop, sock))
loop.run_forever()

It works fine until I'm trying to fork, after the socket was bounl and before server starts serving. (This logic works fine in synchronous -- threading based code.)

When I'm trying this:

loop = asyncio.get_event_loop()
sock = loop.run_until_complete(create_server(loop))

from multiprocessing import cpu_count
for num in range(cpu_count() - 1):
    pid = os.fork()
    if pid <= 0:            # fork process as the same number as
        break               # my cpu cores

loop.create_task(serving(loop, sock))
loop.run_forever()

Theoretically forked process are bounl to a same socket? And run in a same event loop? then work just fine?

However I'm getting these error messages:

Task exception was never retrieved
future: <Task finished coro=<serving() done, defined at /home/new/LinuxDemo/temp1.py:21> exception=FileExistsError(17, 'File exists')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 262, in _add_reader
    key = self._selector.get_key(fd)
  File "/usr/local/lib/python3.7/selectors.py", line 192, in get_key
    raise KeyError("{!r} is not registered".format(fileobj)) from None
KeyError: '6 is not registered'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/test/temp1.py", line 23, in serving
    client ,addr = await loop.sock_accept(sock)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 525, in sock_accept
    self._sock_accept(fut, False, sock)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 538, in _sock_accept
    self.add_reader(fd, self._sock_accept, fut, True, sock)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 335, in add_reader
    return self._add_reader(fd, callback, *args)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 265, in _add_reader
    (handle, None))
  File "/usr/local/lib/python3.7/selectors.py", line 359, in register
    self._selector.register(key.fd, poller_events)
FileExistsError: [Errno 17] File exists

Python version 3.7.3,

I'm totally confused about what's going on.

Could anybody help? thanks

Body:
According to the tracker issue, it is not supported to fork an existing asyncio event loop and attempt to use it from multiple processes. However, according to Yury's comment on the same issue, multi-processing can be implemented by forking before starting a loop, therefore running fully independent asyncio loops in each child.

Your code actually confirms this possibility: while create_server is async def, it doesn't await anything, nor does it use the loop argument. So we can implement Yury's approach by by making create_server a regular function, removing the loop argument, and calling it before os.fork(), and only running event loops after forking:

import os, asyncio, socket, multiprocessing

async def handler(loop, client):
    with client:
        while True:
            data = await loop.sock_recv(client, 64)
            if not data:
                break
            await loop.sock_sendall(client, data)

# create tcp server
def create_server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 25000))
    sock.listen()
    sock.setblocking(False)
    return sock

# whenever accept a request ,create a handler task in eventloop
async def serving(loop, sock):
    while True:
        client, addr = await loop.sock_accept(sock)
        loop.create_task(handler(loop, client))

sock = create_server()

for num in range(multiprocessing.cpu_count() - 1):
    pid = os.fork()
    if pid <= 0:            # fork process as the same number as
        break               # my cpu cores

loop = asyncio.get_event_loop()
loop.create_task(serving(loop, sock))
loop.run_forever()


问:
How to Insert a Row to a Sorted Table While Maintaining Order
The problem is that it will not allow me to insert a row into my table using jQuery. I tried using .eq() with index to find the correct position to insert and .after() to insert the row. However, it will not add the row.

This is the HTML:

```<code><table class="ResultsTable" hidden="hidden">
    <thead class="header">
        <tr>
            <td class="rankColumn"></td>
            <td class="nameColumn"></td>
            <td class="ageColumn"></td>
        </tr>
    </thead>
    <tbody id="resultsTableBody"></tbody>
</table>
</code>```

This is my jQuery:

```<code>function insert(data){
    $('#resultsTableBody > tr')
    .eq(data['Status'] - 1).after('<tr>' +
    '<td class=\'rankColumn ' + data['Rank'] + ' \' ></td>' +
    '<td class=\'nameColumn\'>' + data['Name'] + '</td>' +
    '<td class=\'ageColumn\'>' + data['Age'] + '</td>' +
    '</tr>');
}
</code>```

Why is it that it wont insert anything into the table body? Rank is like an index which represents how high up the list a row should be. With rank being from 1 to 3. So this code should insert a row into the correct position in the table. The table is empty to start with.

Expected result is:

```<code>1 | John      | 24
1 | Bob       | 19
1 | Misha     | 27
2 | Laura     | 22
3 | Hannah    | 31
3 | Paul      | 43
</code>```

They should be placed in order like above based on their rank. However, the table just shows the header and the body is blank. Where am I going wrong?

The data will all not be available when inserting they will be retrieved one at a time and it will find its place in the table based on the others.

答:
You can use a data attribute to specify the rank on the rows (i.e. data-rank), then sort the table on every insert based on that:

```<code>function insert({Status, Rank, Name, Age}) {
    const html = `<tr data-rank="${Rank}">
        <td class="rankColumn">${Rank}</td>
        <td class="nameColumn">${Name}</td>
        <td class="ageColumn">${Age}</td>
    </tr>`;

    $('#resultsTableBody').append(html);

    // Sort the rows based on rank
    $('#resultsTableBody > tr')
    .sort((a, b) => $(a).attr('data-rank') - $(b).attr('data-rank'))
    .appendTo('#resultsTableBody');
}
</code>```

Also, using Template Literals and Object Destructuring will make your code more readable.

Here's a fiddle.

A More Performant Algorithm

As noted in the comments the above function rerenders the entire table on every insert, which is a resource-heavy operation.

To overcome that, we can maintain an array with all the current ranks in the table. Every time a new row is to be inserted, we check against that array to find the last occurrence of the rank and use that as the index.

```<code>let ranks = [];

// Find the next index at which the given rank can be
// inserted while maintaining the order of ranks
// See https://stackoverflow.com/a/21822316/1096470
function findNextIndex(rank) {
    var low = 0,
        high = ranks.length;

    while (low < high) {
        var mid = (low + high) >>> 1;
        if (ranks[mid] < rank) low = mid + 1;
        else high = mid;
    }
    return low;
}

function insert({Status, Rank, Name, Age}) {
    const html = `<tr>
        <td class="rankColumn">${Rank}</td>
        <td class="nameColumn">${Name}</td>
        <td class="ageColumn">${Age}</td>
    </tr>`;

    const index = findNextIndex(Rank);

    if (index === 0) {
        $(`#resultsTableBody`).prepend(html);
    } else {
        $(`#resultsTableBody > tr:nth-child(${index})`).after(html);
    }

    // Insert the given rank to the ranks array while keeping it sorted
    ranks.splice(index, 0, Rank);
}
</code>```

Here's another fiddle.

Body:
The problem is that it will not allow me to insert a row into my table using jQuery. I tried using .eq() with index to find the correct position to insert and .after() to insert the row. However, it will not add the row.

This is the HTML:

This is my jQuery:

function insert(data){
    $('#resultsTableBody > tr')
    .eq(data['Status'] - 1).after('
' +
    '	' +
    '' + data['Name'] + '	' +
    '' + data['Age'] + '	' +
    '
');
}

Why is it that it wont insert anything into the table body? Rank is like an index which represents how high up the list a row should be. With rank being from 1 to 3. So this code should insert a row into the correct position in the table. The table is empty to start with.

Expected result is:

1 | John      | 24
1 | Bob       | 19
1 | Misha     | 27
2 | Laura     | 22
3 | Hannah    | 31
3 | Paul      | 43

They should be placed in order like above based on their rank. However, the table just shows the header and the body is blank. Where am I going wrong?

The data will all not be available when inserting they will be retrieved one at a time and it will find its place in the table based on the others.

Body:
You can use a data attribute to specify the rank on the rows (i.e. data-rank), then sort the table on every insert based on that:

function insert({Status, Rank, Name, Age}) {
    const html = `<tr data-rank="${Rank}">
        <td class="rankColumn">${Rank}</td>
        <td class="nameColumn">${Name}</td>
        <td class="ageColumn">${Age}</td>
    </tr>`;

    $('#resultsTableBody').append(html);

    // Sort the rows based on rank
    $('#resultsTableBody > tr')
    .sort((a, b) => $(a).attr('data-rank') - $(b).attr('data-rank'))
    .appendTo('#resultsTableBody');
}

Also, using Template Literals and Object Destructuring will make your code more readable.

Here's a fiddle.

A More Performant Algorithm

As noted in the comments the above function rerenders the entire table on every insert, which is a resource-heavy operation.

To overcome that, we can maintain an array with all the current ranks in the table. Every time a new row is to be inserted, we check against that array to find the last occurrence of the rank and use that as the index.

let ranks = [];

// Find the next index at which the given rank can be
// inserted while maintaining the order of ranks
// See https://stackoverflow.com/a/21822316/1096470
function findNextIndex(rank) {
    var low = 0,
        high = ranks.length;

    while (low < high) {
        var mid = (low + high) >>> 1;
        if (ranks[mid] < rank) low = mid + 1;
        else high = mid;
    }
    return low;
}

function insert({Status, Rank, Name, Age}) {
    const html = `<tr>
        <td class="rankColumn">${Rank}</td>
        <td class="nameColumn">${Name}</td>
        <td class="ageColumn">${Age}</td>
    </tr>`;

    const index = findNextIndex(Rank);

    if (index === 0) {
        $(`#resultsTableBody`).prepend(html);
    } else {
        $(`#resultsTableBody > tr:nth-child(${index})`).after(html);
    }

    // Insert the given rank to the ranks array while keeping it sorted
    ranks.splice(index, 0, Rank);
}

Here's another fiddle.


问:
Spring, Hibernate, EntityManager and class inheritance
I'm pretty much new to Spring & Hibernate. In our team, we are building a web application using Struts 2 for the presentation layer, with Spring 3 and Hibernate 3 (with Annotations) underneath. We are still debating on whether to use DAOs or not and Session's or EntityManager's for CRUD operations. Setting aside the question of which is better than the other, I ran into another problem using EntityManager.

My goal is to create an abstract (generic) Service which will expose 4 basic operations: save, delete, find by ID and find all by class. Other services will inherit from this and just implement custom finds or updates (this may change in the future). Problem is, I'm unsure where to put the annotated EntityManager. I understand that if I call save() in a service from my Action, i.e. Bob, which inherits the save() from the Person parent Service, the system will fail to inject the EntityManager because the Service Person has not been called and the @PersistenceContext annotation was not parsed.

Is there a way around this problem? I'd like to use inheritance for my services because that would reduce the amount of code needed for simple operations.

答:
This link may be helpful.

If you end up using Session objects you'll want to look into HibernateDaoSupport which will function nicely as base class for your generic service class.

ContentLicense: CC BY-SA 2.5


问:
Re-Applying Course Completion Criteria
I have a course that has been completed by a number of users. I would like to reduce the number of activities that are required to be completed for the course to be deemed complete. When I unlock the course completion settings and uncheck the activity and re-apply the course completion criteria, everyone's course completion turns to incomplete. How do I re-apply the new course completion criteria to all those users who have already completed the course?</p>

答:
I believe even if you modify the course completion criteria to less activities, once your cronjob (scheduled tasks) runs the completion will be stored for the users that previously had the completion.

e.g.

Initial course completion criteria: A, B and C activities.

Users: 123
and 456 completed A, B and C activities.

New course completion
criteria: A and B, hence the completion records for the course will
be removed and recalculated in the next cronjob (Moodle scheduled
tasks) run.

Title: Re-Applying Course Completion Criteria


问:
Why can't I set Values in my state using hooks?
I'm trying to set data in my state over a function... the state is called as values and this is the code that I have

```<code> const [values, setValues] = useState({
     about:'',ourServiceBuyer:'',ourServiceSupplier:'',faq:[],products:[]
 });

 useEffect(() => {

   async function handleData() {
     try {
       const result = await LandingData()

       console.log('algo',result.data.landing.about_us )

       setValues({
         about:result.data.landing.about_us,
         ourServiceBuyer:result.data.landing.our_services_supplier,
         ourServiceSupplier :result.data.landing.our_services_supplier,
         faq : result.data.landing_page_faq,
         products:result.data.products,
       });

       console.log("resultado de useEffect mostrando los values",values)
       console.log("resultado de useEffect", result);

     } catch (e) {

       console.error('error in obatin the return of LandingData: ', e.message);

       handleRedirect('/WrongRequest');
     }
   }
   handleData()

 }, []);
</code>```

landingData() provides me with the data that I need, and I can see it with a console.log() But, when I try to set the data to the state I don't get anything only the same initial state...

答:
i put "await" before this sentence

console.log("resultado de useEffect mostrando los values",values)

Body:
I'm trying to set data in my state over a function... the state is called as values and this is the code that I have

 const [values, setValues] = useState({
     about:'',ourServiceBuyer:'',ourServiceSupplier:'',faq:[],products:[]
 });

 useEffect(() => {

   async function handleData() {
     try {
       const result = await LandingData()

       console.log('algo',result.data.landing.about_us )

       setValues({
         about:result.data.landing.about_us,
         ourServiceBuyer:result.data.landing.our_services_supplier,
         ourServiceSupplier :result.data.landing.our_services_supplier,
         faq : result.data.landing_page_faq,
         products:result.data.products,
       });

       console.log("resultado de useEffect mostrando los values",values)
       console.log("resultado de useEffect", result);

     } catch (e) {

       console.error('error in obatin the return of LandingData: ', e.message);

       handleRedirect('/WrongRequest');
     }
   }
   handleData()

 }, []);

landingData() provides me with the data that I need, and I can see it with a console.log() But, when I try to set the data to the state I don't get anything only the same initial state...


问:
loadChildren is deprecated in angular8
I just noticed that Angular 8 (which will be released soon), has deprecated "string-typed router loadChildren". (ticket)

Do I understand correctly that they are refering to ...

```<code>const routes = [
  {
    path: 'production',
    loadChildren: './production/production.module#ProductionModule' // <<--this
  }],
</code>```

To migrate to Angular 8, what is the solution ?

In the ticket they are refering to "dynamic imports". Am I correct that this refers to the following proposal:

```<code>let module = await import('/modules/my-module.js');
</code>```

Could somebody give a preview of what the routing file should actually look like if we wanted to use lazy loading in the future ?

答:
As loadChildren:string is deprecated in angular 8 Change your loadChildren declarations

From

```<code>loadChildren: './production/production.module#ProductionModule'
</code>```

To

```<code>loadChildren: () => import('./production/production.module').then(m => m.ProductionModule)
</code>```

For more you can ref angular official git link and commit

Title: loadChildren is deprecated in angular8

Body:
I just noticed that Angular 8 (which will be released soon), has deprecated "string-typed router loadChildren". (ticket)

Do I understand correctly that they are refering to ...

const routes = [
  {
    path: 'production',
    loadChildren: './production/production.module#ProductionModule' // <<--this
  }],

To migrate to Angular 8, what is the solution ?

In the ticket they are refering to "dynamic imports". Am I correct that this refers to the following proposal:

let module = await import('/modules/my-module.js');

Could somebody give a preview of what the routing file should actually look like if we wanted to use lazy loading in the future ?

Body:
As loadChildren:string is deprecated in angular 8 Change your loadChildren declarations

From

loadChildren: './production/production.module#ProductionModule'

To

loadChildren: () => import('./production/production.module').then(m => m.ProductionModule)

For more you can ref angular official git link and commit


问:
How to set global innodb_buffer_pool_size?
How to set the global innodb_buffer_pool_size mySQL variable? When I set it to system display I get this error:

```<code>ERROR 1238 (HY000): Variable 'innodb_buffer_pool_size' is a read only variable
</code>```

答:
To temporarily increase buffer pool size:

```<code>SET GLOBAL innodb_buffer_pool_size= (SELECT @@innodb_buffer_pool_size)*10
#check via this:
#SELECT @@innodb_buffer_pool_size/1024/1024/1024
</code>```

To permanently increase, you will need to edit my.cnf file.  Here are my go to commands for ubuntu + mysql 8.

```<code>sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
</code>```

add in this at the bottom of the file

```<code>innodb_buffer_pool_size        = 8G
</code>```

save and exit. restart MySQL.

```<code>sudo systemctl restart mysql
</code>```

Body:
How to set the global innodb_buffer_pool_size mySQL variable? When I set it to system display I get this error:

ERROR 1238 (HY000): Variable 'innodb_buffer_pool_size' is a read only variable

Body:
To temporarily increase buffer pool size:

SET GLOBAL innodb_buffer_pool_size= (SELECT @@innodb_buffer_pool_size)*10
#check via this:
#SELECT @@innodb_buffer_pool_size/1024/1024/1024

To permanently increase, you will need to edit my.cnf file.  Here are my go to commands for ubuntu + mysql 8.

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

add in this at the bottom of the file

innodb_buffer_pool_size        = 8G

save and exit. restart MySQL.

sudo systemctl restart mysql


问:
Module and classes handling (dynamic linking)
Run into a bit of an issue, and I'm looking for the best solution concept/theory.

I have a system that needs to use objects. Each object that the system uses has a known interface, likely implemented as an abstract class. The interfaces are known at build time, and will not change. The exact implementation to be used will vary and I have no idea ahead of time what module will be providing it. The only guarantee is that they will provide the interface. The class name and module (DLL) come from a config file or may be changed programmatically.

Now, I have all that set up at the moment using a relatively simple system, set up something like so (rewritten pseudo-code, just to show the basics):

```<code>struct ClassID
{
    Module * module;
    int number;
};

class Module
{
    HMODULE module;
    function<void * (int)> * createfunc;

    static Module * Load(String filename);

    IObject * CreateClass(int number)
    {
        return createfunc(number);
    }
};

class ModuleManager
{
    bool LoadModule(String filename);

    IObject * CreateClass(String classname)
    {
        ClassID class = AvailableClasses.find(classname);
        return class.module->CreateObject(class.number);
    }

    vector<Module*> LoadedModules;
    map<String, ClassID> AvailableClasses;
};
</code>```

Modules have a few exported functions to give the number of classes they provide and the names/IDs of those, which are then stored. All classes derive from IObject, which has a virtual destructor, stores the source module and has some methods to get the class' ID, what interface it implements and such.

The only issue with this is each module has to be manually loaded somewhere (listed in the config file, at the moment). I would like to avoid doing this explicitly (outside of the ModuleManager, inside that I'm not really concerned as to how it's implemented).

I would like to have a similar system without having to handle loading the modules, just create an object and (once it's all set up) it magically appears.

I believe this is similar to what COM is intended to do, in some ways. I looked into the COM system briefly, but it appears to be overkill beyond belief. I only need the classes known within my system and don't need all the other features it handles, just implementations of interfaces coming from somewhere.

My other idea is to use the registry and keep a key with all the known/registered classes and their source modules and numbers, so I can just look them up and it will appear that Manager::CreateClass finds and makes the object magically. This seems like a viable solution, but I'm not sure if it's optimal or if I'm reinventing something.

So, after all that, my question is: How to handle this? Is there an existing technology, if not, how best to set it up myself? Are there any gotchas that I should be looking out for?

答:
I don't know if any technology exists to do this.

I do know that I worked with a system very similar to this. We used XML files to describe the various classes that different modules made available. Our equivalent of ModuleManager would parse the xml files to determine what to create for the user at run time based on the class name they provided and the configuration of the system. (Requesting an object that implemented interface 'I' could give back any of objects 'A', 'B' or 'C' depending on how the system was configured.)

The big gotcha we found was that the system was very brittle and at times hard to debug/understand. Just reading through the code, it was often near impossible to see what concrete class was being instantiated. We also found that maintaining the XML created more bugs and overhead than expected.

If I was to do this again, I would keep the design pattern of exposing classes from DLL's through interfaces, but I would not try to build a central registry of classes, nor would I derive everything from a base class such as IObject.

I would instead make each module responsible for exposing its own factory functions(s) to instantiate objects.

Body:
Run into a bit of an issue, and I'm looking for the best solution concept/theory.

I have a system that needs to use objects. Each object that the system uses has a known interface, likely implemented as an abstract class. The interfaces are known at build time, and will not change. The exact implementation to be used will vary and I have no idea ahead of time what module will be providing it. The only guarantee is that they will provide the interface. The class name and module (DLL) come from a config file or may be changed programmatically.

Now, I have all that set up at the moment using a relatively simple system, set up something like so (rewritten pseudo-code, just to show the basics):

struct ClassID
{
    Module * module;
    int number;
};

class Module
{
    HMODULE module;
    function<void * (int)> * createfunc;

    static Module * Load(String filename);

    IObject * CreateClass(int number)
    {
        return createfunc(number);
    }
};

class ModuleManager
{
    bool LoadModule(String filename);

    IObject * CreateClass(String classname)
    {
        ClassID class = AvailableClasses.find(classname);
        return class.module->CreateObject(class.number);
    }

    vector<Module*> LoadedModules;
    map<String, ClassID> AvailableClasses;
};

Modules have a few exported functions to give the number of classes they provide and the names/IDs of those, which are then stored. All classes derive from IObject, which has a virtual destructor, stores the source module and has some methods to get the class' ID, what interface it implements and such.

The only issue with this is each module has to be manually loaded somewhere (listed in the config file, at the moment). I would like to avoid doing this explicitly (outside of the ModuleManager, inside that I'm not really concerned as to how it's implemented).

I would like to have a similar system without having to handle loading the modules, just create an object and (once it's all set up) it magically appears.

I believe this is similar to what COM is intended to do, in some ways. I looked into the COM system briefly, but it appears to be overkill beyond belief. I only need the classes known within my system and don't need all the other features it handles, just implementations of interfaces coming from somewhere.

My other idea is to use the registry and keep a key with all the known/registered classes and their source modules and numbers, so I can just look them up and it will appear that Manager::CreateClass finds and makes the object magically. This seems like a viable solution, but I'm not sure if it's optimal or if I'm reinventing something.

So, after all that, my question is: How to handle this? Is there an existing technology, if not, how best to set it up myself? Are there any gotchas that I should be looking out for?


问:
Button set to visibility Gone is still clickable
In my activity I have a switch, which when checked creates an animation and a button appears on the screen. When the switch disabled the button disappears also with an animation. When the button disappears I set the visibility to gone and when it appears I set the visibility to visible.
The initial state of the button is gone and when I try to click the location it supposed to be nothing happens. When the buttons appears it becomes clickable. If I make it disappear again, it's still clickable. Why is that? I thought that setting visibility to gone prevents the button from being triggered. I know I can set the button to setEnabled(false), but I'm curious why the button is still clickable when I set it visibility to gone.

Here's my onCreate():

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler();
        show = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.show);
        hide = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.hide);
        ((SwitchCompat)findViewById(R.id.animation_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ((AppCompatButton)findViewById(R.id.animated_button)).startAnimation(show);
                            ((AppCompatButton)findViewById(R.id.animated_button)).setVisibility(View.VISIBLE);
                        }
                    }, 3000);

                }else{
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ((AppCompatButton)findViewById(R.id.animated_button)).startAnimation(hide);
                            ((AppCompatButton)findViewById(R.id.animated_button)).setVisibility(View.GONE);
                        }
                    },3000);
                }
            }
        });

        ((AppCompatButton)findViewById(R.id.animated_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_LONG).show();
            }
        });
</code>```

Here is the Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="36dp"
        android:layout_marginTop="32dp"
        android:text="Animataion"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/animation_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginTop="24dp"
        android:checked="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/notification_switch" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/animated_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="176dp"
        android:text="click me"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>
</android.support.constraint.ConstraintLayout>
</code>```

Here's the show animation:

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">
    <scale
    android:duration="450"
    android:fromXScale="0.0"
    android:fromYScale="0.0"
    android:toXScale="1.0"
    android:toYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"
    />
</set>
</code>```

Here's the hide animation:

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">
    <scale
    android:duration="300"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:toXScale="0.0"
    android:toYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    />
</set>
</code>```

答:
try something like this</p>

```<code>hide = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.hide);
hide.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {}

    @Override
    public void onAnimationEnd(Animation animation) {
        ((AppCompatButton)findViewById(R.id.animated_button)).setVisibility(View.GONE);
        ((AppCompatButton)findViewById(R.id.animated_button)).setEnabled(false);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {}
});
</code>```

Body:
In my activity I have a switch, which when checked creates an animation and a button appears on the screen. When the switch disabled the button disappears also with an animation. When the button disappears I set the visibility to gone and when it appears I set the visibility to visible.
The initial state of the button is gone and when I try to click the location it supposed to be nothing happens. When the buttons appears it becomes clickable. If I make it disappear again, it's still clickable. Why is that? I thought that setting visibility to gone prevents the button from being triggered. I know I can set the button to setEnabled(false), but I'm curious why the button is still clickable when I set it visibility to gone.

Here's my onCreate():

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler();
        show = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.show);
        hide = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.hide);
        ((SwitchCompat)findViewById(R.id.animation_switch)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ((AppCompatButton)findViewById(R.id.animated_button)).startAnimation(show);
                            ((AppCompatButton)findViewById(R.id.animated_button)).setVisibility(View.VISIBLE);
                        }
                    }, 3000);

                }else{
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ((AppCompatButton)findViewById(R.id.animated_button)).startAnimation(hide);
                            ((AppCompatButton)findViewById(R.id.animated_button)).setVisibility(View.GONE);
                        }
                    },3000);
                }
            }
        });

        ((AppCompatButton)findViewById(R.id.animated_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_LONG).show();
            }
        });

Here is the Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="36dp"
        android:layout_marginTop="32dp"
        android:text="Animataion"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/animation_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginTop="24dp"
        android:checked="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/notification_switch" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/animated_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="176dp"
        android:text="click me"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>
</android.support.constraint.ConstraintLayout>

Here's the show animation:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">
    <scale
    android:duration="450"
    android:fromXScale="0.0"
    android:fromYScale="0.0"
    android:toXScale="1.0"
    android:toYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"
    />
</set>

Here's the hide animation:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true">
    <scale
    android:duration="300"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:toXScale="0.0"
    android:toYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    />
</set>

Body:
try something like this

hide = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.hide);
hide.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) {}

    @Override
    public void onAnimationEnd(Animation animation) {
        ((AppCompatButton)findViewById(R.id.animated_button)).setVisibility(View.GONE);
        ((AppCompatButton)findViewById(R.id.animated_button)).setEnabled(false);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {}
});


问:
The most correct way to iterate over a list in haskell, and return the element for which a condition is true
I have a function which takes some argument and calls another function which returns a list of the form [a_1, a_2, ..., a_n].

What I am trying to do is call a predicate p on each item in the list, and return the item for which p(a_i)=True.

If not, then I will recursively repeat the algorithm for all a_i.

The structure is as follows:

```<code>f :: t -> t
f =  (g t) --this is a list
     (p ?) -- p is a predicate on each element
</code>```

I want to call this  predicate p on each item on the list then return the item if the predicate is true.

If the predicate does not hold for all items, then I recursively call f on each item in the list which I realize will give me multiple "t" which I know how to combine into a single t to match my signature.

I found this:

How to get out of iterate loop when a condition is met?

But the structure of the condition looks different than what I am trying to do.

Could someone possibly point me to the right direction?

答:
How about if you define

```<code>satisfies:: [t]-> (t -> Bool) -> Maybe t
</code>```

which means that satisifies takes a list and a predicate, and returns a Maybe of an element. This is one way of indicating that there might not be an element satisfying the predicate (it makes the function total, meaning, it is always defined).

Now if the list is empty, the return is Nothing:

```<code>satisfies [] _ = Nothing
</code>```

Finally,

```<code>satisfies (x:xs) p = case p x of
    True -> Just x
    False -> satisfies xs p
</code>```

Body:
I have a function which takes some argument and calls another function which returns a list of the form [a_1, a_2, ..., a_n].

What I am trying to do is call a predicate p on each item in the list, and return the item for which p(a_i)=True.

If not, then I will recursively repeat the algorithm for all a_i.

The structure is as follows:

f :: t -> t
f =  (g t) --this is a list
     (p ?) -- p is a predicate on each element

I want to call this  predicate p on each item on the list then return the item if the predicate is true.

If the predicate does not hold for all items, then I recursively call f on each item in the list which I realize will give me multiple "t" which I know how to combine into a single t to match my signature.

I found this:

How to get out of iterate loop when a condition is met?

But the structure of the condition looks different than what I am trying to do.

Could someone possibly point me to the right direction?

Body:
How about if you define

satisfies:: [t]-> (t -> Bool) -> Maybe t

which means that satisifies takes a list and a predicate, and returns a Maybe of an element. This is one way of indicating that there might not be an element satisfying the predicate (it makes the function total, meaning, it is always defined).

Now if the list is empty, the return is Nothing:

satisfies [] _ = Nothing

Finally,

satisfies (x:xs) p = case p x of
    True -> Just x
    False -> satisfies xs p


问:
Select random element based on numeric attribute value
I have an array of agents which each have the attribute rate which is their accepted calls minus their declined calls. I order these agents in the array based on the rate. I'd like to give agents with a better rate a higher chance to be selected for a call than other agents with a lower rate to make things fair. I understand how to select a random element from an array but I can't wrap my head around this problem.</p>

答:
In this code, there is a 2/15 chance to get 2, 3/15 chance to get 3, and so on.

15 is based on the total rate of all the agents.

var aoa = [{rate: 2},{rate: 3},{rate: 6},{rate: 4}];
var r = Math.random() * aoa.map(e => e.rate).reduce((ac,c) => ac+c,0);
var sa;
aoa.forEach((a,i) => {
    var pt = aoa.slice(0,i).map(e => e.rate).reduce((ac,c) => ac+c,0);
    if (r >= pt && r < pt+a.rate) sa = a;
    console.log(`${r} has to be between ${pt} and ${pt+a.rate} if chosen rate =  ${a.rate}`);
});
console.log(sa);```


问:
wxPython version issue
Running Ubuntu 14.04 with Eclipse Kepler Service Release 2 which has Pydev 4.4.0.2... and Pydev Mylyn Integration 0.6.0.  My program runs with no issues. Porting it over to my new platform running Ubuntu 16.04 with Eclipse Oxygen 1A release 4.7.1A and Pydev 6.0.0... with Pydev Integration at 0.6.0 and get the following error: </p>

```<code>from wxPython._gdi import wxBitmapFromImage
ImportError: No module named wxPython._gdi
</code>```

<p>I can import wx either in Eclipse (Console) or on a terminal shell in the new ubuntu version but get the 2nd line error when I type the 1st line. My 14.04 is running wxpython 2.8 while my new 16.04 is running 3.0 not sure if this is it however.   </p>

答:
I had the same issue except I got it on unpiclikg an instane of _gdi.Colour class. Following advice from Unpickling python objects with a changed module path I was saved with:

```<code>import wx as _wx
from wx import _core
sys.modules['wx._gdi'] = _core
</code>```

This is a hack of course and you should be better off with a try-except as in (untested)

```<code>try:
   from wxPython._gdi import wxBitmapFromImage
except ImportError:
   from wx import BitmapFromImage as wxBitmapFromImage
</code>```

Title: wxPython version issue

Body:
Running Ubuntu 14.04 with Eclipse Kepler Service Release 2 which has Pydev 4.4.0.2... and Pydev Mylyn Integration 0.6.0.  My program runs with no issues. Porting it over to my new platform running Ubuntu 16.04 with Eclipse Oxygen 1A release 4.7.1A and Pydev 6.0.0... with Pydev Integration at 0.6.0 and get the following error:

from wxPython._gdi import wxBitmapFromImage
ImportError: No module named wxPython._gdi

I can import wx either in Eclipse (Console) or on a terminal shell in the new ubuntu version but get the 2nd line error when I type the 1st line. My 14.04 is running wxpython 2.8 while my new 16.04 is running 3.0 not sure if this is it however.

Body:
I had the same issue except I got it on unpiclikg an instane of _gdi.Colour class. Following advice from Unpickling python objects with a changed module path I was saved with:

import wx as _wx
from wx import _core
sys.modules['wx._gdi'] = _core

This is a hack of course and you should be better off with a try-except as in (untested)

try:
   from wxPython._gdi import wxBitmapFromImage
except ImportError:
   from wx import BitmapFromImage as wxBitmapFromImage


问:
Most 'functional' way to sum pairs of elements from a vector using C++17 or later?
I'd like some suggestions for the most terse and 'functional' way to gather pairs of successive elements from a vector (1st and 2nd, 3rd and 4th, etc.) using modern C++.  Assume the vector is of arbitrary but even length.  For the examples I'm pulling together, I'm summing the elements of each pair but that's not the main problem.  I should add I'll use STL only, no Boost.

In Python I can zip them into 2-tuples via an iterator with

s = range(1,11)
print([(x + y) for x,y in zip(*[iter(s)] * 2)])
```

<p>In Perl 5 I can peel off pairs with</p>

<pre class="lang-perl prettyprint-override"><code>use List::Util qw/pairs sum/;
use feature 'say';
@s = 1 .. 10;
say sum @$_ foreach (pairs @s);
</code>```

In Perl 6 I can shove them two at a time into a block with

my @s = 1 .. 10;
for @s -> $x, $y { say $x + $y; }
```

<p>and in R I can wrap the vector into a 2-column array and sum the rows with</p>

<pre class="lang-r prettyprint-override"><code>s <- 1:10
print(apply(matrix(s, ncol=2, byrow=TRUE), 1, sum))
</code>```

I am not fluent in C++ and my solution uses for(;;).  That feels too much like C.

#include <iostream>
#include <vector>
#include <numeric>  // std::iota

int main() {
    std::vector<int> s(10);
    std::iota(s.begin(), s.end(), 1);
    for (auto p = s.cbegin(); p != s.cend(); p += 2)
        std::cout << (*p + *(p + 1)) << std::endl;
}
```

<p>The output of course should be some variant of </p>

```3
7
11
15
19
```

答:
At the risk of sounding like I'm trying to be clever or annoying, I say this is the answer:

```<code>print(sums(successive_pairs(range(1,11))));
</code>```

Now, of course, those aren't built-in functions, so you would have to define them, but I don't think that is a bad thing.  The code clearly expresses what you want in a functional style.  Also, the responsibility of each of those functions is well separated, easily testable, and reusable.  It isn't necessary to use a lot of tricky specialized syntax to write code in a functional style.

Body:
I'd like some suggestions for the most terse and 'functional' way to gather pairs of successive elements from a vector (1st and 2nd, 3rd and 4th, etc.) using modern C++.  Assume the vector is of arbitrary but even length.  For the examples I'm pulling together, I'm summing the elements of each pair but that's not the main problem.  I should add I'll use STL only, no Boost.

In Python I can zip them into 2-tuples via an iterator with

s = range(1,11)
print([(x + y) for x,y in zip(*[iter(s)] * 2)])

In Perl 5 I can peel off pairs with

use List::Util qw/pairs sum/;
use feature 'say';
@s = 1 .. 10;
say sum @$_ foreach (pairs @s);

In Perl 6 I can shove them two at a time into a block with

my @s = 1 .. 10;
for @s -> $x, $y { say $x + $y; }

and in R I can wrap the vector into a 2-column array and sum the rows with

s <- 1:10
print(apply(matrix(s, ncol=2, byrow=TRUE), 1, sum))

I am not fluent in C++ and my solution uses for(;;).  That feels too much like C.

#include <iostream>
#include <vector>
#include <numeric>  // std::iota

int main() {
    std::vector<int> s(10);
    std::iota(s.begin(), s.end(), 1);
    for (auto p = s.cbegin(); p != s.cend(); p += 2)
        std::cout << (*p + *(p + 1)) << std::endl;
}

The output of course should be some variant of

3
7
11
15
19

Body:
At the risk of sounding like I'm trying to be clever or annoying, I say this is the answer:

print(sums(successive_pairs(range(1,11))));

Now, of course, those aren't built-in functions, so you would have to define them, but I don't think that is a bad thing.  The code clearly expresses what you want in a functional style.  Also, the responsibility of each of those functions is well separated, easily testable, and reusable.  It isn't necessary to use a lot of tricky specialized syntax to write code in a functional style.


问:
Generating class datamembers from a Vector
Please consider this C++ question:

```<code>#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

class ParseURL{
    private:
        int qualify; // 0 means we qualify
    public:
        string node;
        string service;
        bool primary;
        bool health;
        string epoch;
        // methods
        ParseURL(string URL);
        ~ParseURL();
};

ParseURL::ParseURL(string URL){
    vector<string> g2 = {"node", "service", "primary", "health", "epoch"};

    for (string tag : g2){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + tag.size() ;
            auto meh = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            // is there a way we can avoid these lines below?
            if (tag.find("node",0) == 0){
                this->node = meh;
            } else if (tag.find("service",0) == 0 ){
                this->service = meh;
            } else if (tag.find("epoch",0) == 0) {
                this->epoch = meh;
            } else if (tag.find("health",0) == 0){
                this->health = (meh == "OK");
            } else if (tag.find("primary",0) == 0 ){
                this->primary == (this->node == meh);
            }
        }
    }

}

ParseURL::~ParseURL(){
    cout << "Tearing Down the class\n";
}
int main(){
    char req[] = "GET /register?node=hostrpi3&service=potatoservice&primary=node1&health=OK&epoch=1559345106 HTTP";
    string Request = req;
    Request = Request.substr(Request.find_first_of(" ") );
    Request = Request.substr(0, Request.find(" HTTP"));
    ParseURL *a = new ParseURL(Request);

    cout.width(12);
    cout << "a->node: " << a->node << endl;
    cout.width(12);
    cout << "a->service: " << a->service << endl;
    cout.width(12);
    cout << "a->epoch: " << a->epoch << endl;
    cout.width(12);
    cout << "a->health: " << a->health << endl;
    cout.width(12);
    cout << "a->primary: " << a->primary << endl;

    delete(a);

    return 0;
}
</code>```

I need to represent a object based on URL Query Strings, the tags I need are represented in vector g2, and as you can see, I make datamembers for ParseURL out of those tags.

The o/p looks like:

```<code>   a->node: hostrpi3
a->service: potatoservice
  a->epoch: 1559345106
 a->health: 1
a->primary: 0
Tearing Down the class
</code>```

Although this version works, it feels this can be improved much. Despite having it all in the Vector, I am repeatedly doing tag.find for each of those attributes. There must be a better way, I hope. Could you please point in the right direction? Thanks!

Edit 1

Thanks, I updated the constructor following the suggestions:

```<code>ParseURL::ParseURL(string URL){
    char tags[10][100] = {"node", "service", "primary", "health", "epoch"};

    int i = 0;
    for (auto tag : tags){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + strlen(tag);
            auto tag_info = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            switch (i){
                case 0:
                    this->node = tag_info;
                    break;
                case 1:
                    this->service = tag_info;
                    break;
                case 2:
                    this->primary = (this->node == tag_info);
                    break;
                case 3:
                    this->health = (tag_info == "OK");
                    break;
                case 4:
                    this->epoch = tag_info;
                    break;
            }
        }
    i++;
    }
}
</code>```

bash for example, offers indirect reference of variables - that is, one variable may contain the name of another variable:

```<code>$ cat indirect.sh
#!/bin/bash

values="value1 value2"
value1="this is value1"
value2="this is value2"

for i in $values; do
    echo "$i has value ${!i}"
done

$ ./indirect.sh
value1 has value this is value1
value2 has value this is value2
</code>```

I was hoping something similar exists for cases like this, nevertheless, I learned valuable lessons here. thank you!

答:
I didn't exactly understand what you want to use that indirection for in you example, but here's how it can be done:

```<code>vector<string> values{"value1", "value2"}
map<const string, const string> fields_and_values{{"value1", "this is value1"}, {"value2", "this is value2"}};
for (value: values)
     cout << value << " have value " << fields_and_values[value] << endl;
</code>```

This code allows you to dynamically add more fields. If you have a predefined number of fields, this is an overkill, and a simple array would do.
i.e.

```<code>array<const string, 2> values{"this is value1", "this is value2"};
for (int i = 0; i < 2; ++i)
    cout << "value" << i << " have value " << values[i] << endl;
</code>```

Hope that answers your question.

In general about your code:

Why did you go from vector<string> to char[10][100]? (esp. when you only have 5 strings, and none of them take up 100 chars?)   array<string, 5>  is the way to go for your case.

Also, don't use new and delete.. There's no reason to do a heap allocation, just use ParseURL parse(request)  (and even if there was a good reason - use unique_ptr instead).

And finally, if you don't want to go over the string multiple times looking for different keywords, you could use regex.

Body:
Please consider this C++ question:

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

class ParseURL{
    private:
        int qualify; // 0 means we qualify
    public:
        string node;
        string service;
        bool primary;
        bool health;
        string epoch;
        // methods
        ParseURL(string URL);
        ~ParseURL();
};

ParseURL::ParseURL(string URL){
    vector<string> g2 = {"node", "service", "primary", "health", "epoch"};

    for (string tag : g2){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + tag.size() ;
            auto meh = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            // is there a way we can avoid these lines below?
            if (tag.find("node",0) == 0){
                this->node = meh;
            } else if (tag.find("service",0) == 0 ){
                this->service = meh;
            } else if (tag.find("epoch",0) == 0) {
                this->epoch = meh;
            } else if (tag.find("health",0) == 0){
                this->health = (meh == "OK");
            } else if (tag.find("primary",0) == 0 ){
                this->primary == (this->node == meh);
            }
        }
    }

}

ParseURL::~ParseURL(){
    cout << "Tearing Down the class\n";
}
int main(){
    char req[] = "GET /register?node=hostrpi3&service=potatoservice&primary=node1&health=OK&epoch=1559345106 HTTP";
    string Request = req;
    Request = Request.substr(Request.find_first_of(" ") );
    Request = Request.substr(0, Request.find(" HTTP"));
    ParseURL *a = new ParseURL(Request);

    cout.width(12);
    cout << "a->node: " <node << endl;
    cout.width(12);
    cout << "a->service: " <service << endl;
    cout.width(12);
    cout << "a->epoch: " <epoch << endl;
    cout.width(12);
    cout << "a->health: " <health << endl;
    cout.width(12);
    cout << "a->primary: " <primary << endl;

    delete(a);

    return 0;
}

I need to represent a object based on URL Query Strings, the tags I need are represented in vector g2, and as you can see, I make datamembers for ParseURL out of those tags.

The o/p looks like:

   a->node: hostrpi3
a->service: potatoservice
  a->epoch: 1559345106
 a->health: 1
a->primary: 0
Tearing Down the class

Although this version works, it feels this can be improved much. Despite having it all in the Vector, I am repeatedly doing tag.find for each of those attributes. There must be a better way, I hope. Could you please point in the right direction? Thanks!

Edit 1

Thanks, I updated the constructor following the suggestions:

ParseURL::ParseURL(string URL){
    char tags[10][100] = {"node", "service", "primary", "health", "epoch"};

    int i = 0;
    for (auto tag : tags){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + strlen(tag);
            auto tag_info = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            switch (i){
                case 0:
                    this->node = tag_info;
                    break;
                case 1:
                    this->service = tag_info;
                    break;
                case 2:
                    this->primary = (this->node == tag_info);
                    break;
                case 3:
                    this->health = (tag_info == "OK");
                    break;
                case 4:
                    this->epoch = tag_info;
                    break;
            }
        }
    i++;
    }
}

bash for example, offers indirect reference of variables - that is, one variable may contain the name of another variable:

$ cat indirect.sh
#!/bin/bash

values="value1 value2"
value1="this is value1"
value2="this is value2"

for i in $values; do
    echo "$i has value ${!i}"
done

$ ./indirect.sh
value1 has value this is value1
value2 has value this is value2

I was hoping something similar exists for cases like this, nevertheless, I learned valuable lessons here. thank you!

Body:
I didn't exactly understand what you want to use that indirection for in you example, but here's how it can be done:

vector<string> values{"value1", "value2"}
map<const string, const string> fields_and_values{{"value1", "this is value1"}, {"value2", "this is value2"}};
for (value: values)
     cout << value << " have value " << fields_and_values[value] << endl;

This code allows you to dynamically add more fields. If you have a predefined number of fields, this is an overkill, and a simple array would do.
i.e.

array<const string, 2> values{"this is value1", "this is value2"};
for (int i = 0; i < 2; ++i)
    cout << "value" << i << " have value " << values[i] << endl;

Hope that answers your question.

In general about your code:

Why did you go from vector<string> to char[10][100]? (esp. when you only have 5 strings, and none of them take up 100 chars?)   array<string, 5>  is the way to go for your case.

Also, don't use new and delete.. There's no reason to do a heap allocation, just use ParseURL parse(request)  (and even if there was a good reason - use unique_ptr instead).

And finally, if you don't want to go over the string multiple times looking for different keywords, you could use regex.


问:
PHP Function "... Days Ago" In "While Loop" Doesn't Work
I want to add a description of the posting time for each of my articles on the homepage. So there are some content published at different times, and I want to make it appear clearer by adding a description of the date of publication.

But I found a complicated problem. In my code example below, it produces the wrong time. I have tried several times but failed. Can I still fix this with this code or maybe there is another code that is more perfect.

PHP CODE:

```<code>$sql = $DBcon->query("SELECT content, post_date FROM article");
$row = $sql->fetch_array();
$post_date = $row['post_date']; // 2019-06-01 16:29:07

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

do {
// .......

echo $row['content'];
echo time_elapsed_string( $post_date );

// .......
} while ($row = $sql->fetch_array());
</code>```

The above code produces the same time for all content. Even though my content was made at different times. Obviously this is something wrong. So how do you fix it?

答:
Move this line:

```<code>$post_date = $row['post_date']; // 2019-06-01 16:29:07
</code>```

inside of the do ... while loop or, as shown below, remove the variable completely.

```<code>do {
// .......

echo $row['content'];
echo time_elapsed_string($row['post_date']);

// .......
} while ($row = $sql->fetch_array());
</code>```

Body:
I want to add a description of the posting time for each of my articles on the homepage. So there are some content published at different times, and I want to make it appear clearer by adding a description of the date of publication.

But I found a complicated problem. In my code example below, it produces the wrong time. I have tried several times but failed. Can I still fix this with this code or maybe there is another code that is more perfect.

PHP CODE:

$sql = $DBcon->query("SELECT content, post_date FROM article");
$row = $sql->fetch_array();
$post_date = $row['post_date']; // 2019-06-01 16:29:07

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

do {
// .......

echo $row['content'];
echo time_elapsed_string( $post_date );

// .......
} while ($row = $sql->fetch_array());

The above code produces the same time for all content. Even though my content was made at different times. Obviously this is something wrong. So how do you fix it?

Body:
Move this line:

$post_date = $row['post_date']; // 2019-06-01 16:29:07

inside of the do ... while loop or, as shown below, remove the variable completely.

do {
// .......

echo $row['content'];
echo time_elapsed_string($row['post_date']);

// .......
} while ($row = $sql->fetch_array());


问:
Is there any possibility to deal with larger precision of Complex data type in c#?
I'm writing program which use complex data type, but it's too small for my problem. I know it's just double data type for both real and imaginary members, but is it possible to keep numbers as big as 10^30? I was thinking about about connecting complex struct with big integer type (because I don't use floating-point numbers), but don't know how to do it.</p>

答: Operate on the number as a string and work out calculations long form digit by digit.</p>


问:
Spring Tool Suite: @Configuration class may not be final. Remove the final modifier to continue
I am unable to launch my spring boot kotlin app, due to the following:

```<code>org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Configuration class 'TestApplication' may not be final. Remove the final modifier to continue.
</code>```

I know that @configuration and @bean classes cannot be final so I add the allopen plugin in my pom file:

```<code><build>
    <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
    <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-plugin</artifactId>
            <configuration>
                <args>
                    <arg>-Xjsr305=strict</arg>
                </args>
                <compilerPlugins>
                    <plugin>spring</plugin>
                </compilerPlugins>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-maven-allopen</artifactId>
                    <version>${kotlin.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
</code>```

If I package my application and run it (java -jar) it works, but when I try to launch it from STS it won't work.

Kotlin version: 1.2.71
Kotlin eclipse plugin: 0.8.13
STS: 3.9.5

答:
This Question Can be Duplicate of :

IntelliJ Idea 2017.3 unable to start Kotlin Spring Boot App - @Configuration class may not be final

or

Used kotlin-spring plugin, still getting class not open error

.
Anyways , I Just found Solution

You Just need to add open modifier to TestApplication kotlin class

```<code>@SpringBootApplication
open class TestApplication
</code>```

might Solve your Issue .

Body:
I am unable to launch my spring boot kotlin app, due to the following:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: @Configuration class 'TestApplication' may not be final. Remove the final modifier to continue.

I know that @configuration and @bean classes cannot be final so I add the allopen plugin in my pom file:

<build>
    <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
    <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-plugin</artifactId>
            <configuration>
                <args>
                    <arg>-Xjsr305=strict</arg>
                </args>
                <compilerPlugins>
                    <plugin>spring</plugin>
                </compilerPlugins>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-maven-allopen</artifactId>
                    <version>${kotlin.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

If I package my application and run it (java -jar) it works, but when I try to launch it from STS it won't work.

Kotlin version: 1.2.71
Kotlin eclipse plugin: 0.8.13
STS: 3.9.5

Body:
This Question Can be Duplicate of :

IntelliJ Idea 2017.3 unable to start Kotlin Spring Boot App - @Configuration class may not be final

or

Used kotlin-spring plugin, still getting class not open error

.
Anyways , I Just found Solution

You Just need to add open modifier to TestApplication kotlin class

@SpringBootApplication
open class TestApplication

might Solve your Issue .


问:
GCP: List grantable roles per resource
I am going thru a Qwicklabs tutorial on GCP IAM.

At some point, it mentions that

Use the gcloud iam list-grantable-roles command to return a list of
  all roles that can be applied to a given resource.

However the example cited lists the grantable roles by going throughout the entire project:

```<code>gcloud iam list-grantable-roles //cloudresourcemanager.googleapis.com/projects/$DEVSHELL_PROJECT_ID
</code>```

Is there a way to run the above command but only on a specific resource, say Stackdriver or BigQuery ?

答:
Is there a way to run the above command but only on a specific
  resource, say Stackdriver or BigQuery ?

Yes. From the following examples, you should notice a naming pattern.

This link is Google's document on resource naming.

If you want to go deeper than the project then you must specify an actual resource. You cannot just specify BigQuery, you must specify the dataset in BigQuery. For Stackdriver you must specify an actual log name.

For some resources, gcloud provides the command-line option --uri. This will display the resource name:

```<code>gcloud compute instances list --uri
</code>```

Note: The command line option --uri is not supported for all commands. Neither logging nor Biquery support --uri.

Compute Engine:

```<code>gcloud iam list-grantable-roles //compute.googleapis.com/projects/[PROJECT_ID]/zones/[ZONE]/instances/[VM_NAME]
</code>```

BigQuery:

```<code>gcloud iam list-grantable-roles //bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET_ID]
</code>```

Stackdriver Logging:

```<code>gcloud iam list-grantable-roles //logging.googleapis.com/projects/[PROJECT_ID]/logs/cloudbuild
</code>```

Title: GCP: List grantable roles per resource

Body:
I am going thru a Qwicklabs tutorial on GCP IAM.

At some point, it mentions that

Use the gcloud iam list-grantable-roles command to return a list of
  all roles that can be applied to a given resource.

However the example cited lists the grantable roles by going throughout the entire project:

gcloud iam list-grantable-roles //cloudresourcemanager.googleapis.com/projects/$DEVSHELL_PROJECT_ID

Is there a way to run the above command but only on a specific resource, say Stackdriver or BigQuery ?

Body:
Is there a way to run the above command but only on a specific
  resource, say Stackdriver or BigQuery ?

Yes. From the following examples, you should notice a naming pattern.

This link is Google's document on resource naming.

If you want to go deeper than the project then you must specify an actual resource. You cannot just specify BigQuery, you must specify the dataset in BigQuery. For Stackdriver you must specify an actual log name.

For some resources, gcloud provides the command-line option --uri. This will display the resource name:

gcloud compute instances list --uri

Note: The command line option --uri is not supported for all commands. Neither logging nor Biquery support --uri.

Compute Engine:

gcloud iam list-grantable-roles //compute.googleapis.com/projects/[PROJECT_ID]/zones/[ZONE]/instances/[VM_NAME]

BigQuery:

gcloud iam list-grantable-roles //bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET_ID]

Stackdriver Logging:

gcloud iam list-grantable-roles //logging.googleapis.com/projects/[PROJECT_ID]/logs/cloudbuild


问:
Removing a string that starts with a substring
I want to remove all the words that contain a specific substring.</p>

```<code>Sentence = 'walking my dog https://github.com/'
substring = 'http'

# Remove all words that start with the substring
#...

result = 'walking my dog'
</code>```

答:
This respects the original spacing in the string without having to fiddle around too much.

import re
string = "a suspect http://string.com   with spaces before and after"
starts = "http"
re.sub(f"\\b{starts}[^ ]*[ ]+", "", string)
'a suspect with spaces before and after'
```

Body:
I want to remove all the words that contain a specific substring.

Sentence = 'walking my dog https://github.com/'
substring = 'http'

# Remove all words that start with the substring
#...

result = 'walking my dog'


问:
KnexJS How to create multiple inner join
I need to transform this SQL query to KnexJS query

```<code>SELECT
    Book.Title,
    Book.Number,
    Author.Name,
    Author_1.Name,
    Author_2.Name,
    Author_3.Name
FROM
    ((((Book)
INNER JOIN Author ON Book.AuthName = Author.Name)
INNER JOIN Author AS Author_1 ON Book.AuthName = Author_1.Name)
INNER JOIN Author AS Author_2 ON Book.AuthName = Author_2.Name)
INNER JOIN Author AS Author_3 ON Book.AuthName = Author_3.Name
WHERE Book.Title = "HelpMe" ORDER BY Book.Number;
</code>```

I have read the doc here https://knexjs.org/#Builder-join but I barely understood how to use the given example to meet my need because there is no example for such multiple inner join.

Help me please

答:
Knex joins are chainable, so you can do this kind of thing:

```<code>knex
  .select('title', 'author1', 'author2')
  .from('books')
  .join('authors as author1', 'books.author_name', '=', 'author1.name')
  .join('authors as author2', 'books.author_name', '=', 'author2.name')
</code>```

I suspect there's a problem with your example though, in that you're running basically the same comparison over and over again. Normally you would link to an authors table using a series of foreign keys (author1id, author2id) or more properly a join table since this is a MANY to MANY relationship:

```<code>knex
  .select('books.title', 'authors.name')
  .from('books')
  .join('books_authors', 'books.id', '=', 'books_authors.book_id')
  .join('authors', 'authors.id', '=', 'books_authors.author_id')
</code>```

This grabs all the authors for the book, no matter how many there are, but requires an additional table consisting of only ids:

```<code>exports.up = knex =>
  knex.schema.createTable('books_authors', t => {
    t.integer('book_id').references('books.id')
    t.integer('author_id').references('authors.id')
  })

exports.down = knex => knex.schema.dropTable('books_authors')
</code>```

Each time you add an author to a book, you'd also add the book's id and the author's id to the join table so that a relationship exists between the two. This way, each book can have one author or a hundred.

Body:
I need to transform this SQL query to KnexJS query

SELECT
    Book.Title,
    Book.Number,
    Author.Name,
    Author_1.Name,
    Author_2.Name,
    Author_3.Name
FROM
    ((((Book)
INNER JOIN Author ON Book.AuthName = Author.Name)
INNER JOIN Author AS Author_1 ON Book.AuthName = Author_1.Name)
INNER JOIN Author AS Author_2 ON Book.AuthName = Author_2.Name)
INNER JOIN Author AS Author_3 ON Book.AuthName = Author_3.Name
WHERE Book.Title = "HelpMe" ORDER BY Book.Number;

I have read the doc here https://knexjs.org/#Builder-join but I barely understood how to use the given example to meet my need because there is no example for such multiple inner join.

Help me please

Body:
Knex joins are chainable, so you can do this kind of thing:

knex
  .select('title', 'author1', 'author2')
  .from('books')
  .join('authors as author1', 'books.author_name', '=', 'author1.name')
  .join('authors as author2', 'books.author_name', '=', 'author2.name')

I suspect there's a problem with your example though, in that you're running basically the same comparison over and over again. Normally you would link to an authors table using a series of foreign keys (author1id, author2id) or more properly a join table since this is a MANY to MANY relationship:

knex
  .select('books.title', 'authors.name')
  .from('books')
  .join('books_authors', 'books.id', '=', 'books_authors.book_id')
  .join('authors', 'authors.id', '=', 'books_authors.author_id')

This grabs all the authors for the book, no matter how many there are, but requires an additional table consisting of only ids:

exports.up = knex =>
  knex.schema.createTable('books_authors', t => {
    t.integer('book_id').references('books.id')
    t.integer('author_id').references('authors.id')
  })

exports.down = knex => knex.schema.dropTable('books_authors')

Each time you add an author to a book, you'd also add the book's id and the author's id to the join table so that a relationship exists between the two. This way, each book can have one author or a hundred.


问:
multiply numpy ndarray with 1d array along a given axis
It seems I am getting lost in something potentially silly.
 I have an n-dimensional numpy array, and I want to multiply it with a vector (1d array) along some dimension (which can change!).
As an example, say I want to multiply a 2d array by a 1d array along axis 0 of the first array, I can do something like this:

```<code>a=np.arange(20).reshape((5,4))
b=np.ones(5)
c=a*b[:,np.newaxis]
</code>```

Easy, but I would like to extend this idea to n-dimensions (for a, while b is always 1d) and to any axis. In other words, I would like to know how to generate a slice with the np.newaxis at the right place. Say that a is 3d and I want to multiply along axis=1, I would like to generate the slice which would correctly give:

```<code>c=a*b[np.newaxis,:,np.newaxis]
</code>```

I.e. given the number of dimensions of a (say 3), and the axis along which I want to multiply (say axis=1), how do I generate and pass the slice:

```<code>np.newaxis,:,np.newaxis
</code>```

Thanks.

答:
I got a similar demand when I was working on some numerical calculation.

Let's assume we have two arrays (A and B) and a user-specified 'axis'.
A is a multi-dimensional array.
B is a 1-d array.

The basic idea is to expand B so that A and B have the same shape. Here is the solution code

```<code>import numpy as np
from numpy.core._internal import AxisError

def multiply_along_axis(A, B, axis):
    A = np.array(A)
    B = np.array(B)
    # shape check
    if axis >= A.ndim:
        raise AxisError(axis, A.ndim)
    if A.shape[axis] != B.size:
        raise ValueError("'A' and 'B' must have the same length along the given axis")
    # Expand the 'B' according to 'axis':
    # 1. Swap the given axis with axis=0 (just need the swapped 'shape' tuple here)
    swapped_shape = A.swapaxes(0, axis).shape
    # 2. Repeat:
    # loop through the number of A's dimensions, at each step:
    # a) repeat 'B':
    #    The number of repetition = the length of 'A' along the
    #    current looping step;
    #    The axis along which the values are repeated. This is always axis=0,
    #    because 'B' initially has just 1 dimension
    # b) reshape 'B':
    #    'B' is then reshaped as the shape of 'A'. But this 'shape' only
    #     contains the dimensions that have been counted by the loop
    for dim_step in range(A.ndim-1):
        B = B.repeat(swapped_shape[dim_step+1], axis=0)\
             .reshape(swapped_shape[:dim_step+2])
    # 3. Swap the axis back to ensure the returned 'B' has exactly the
    # same shape of 'A'
    B = B.swapaxes(0, axis)
    return A * B
</code>```

And here is an example

```<code>In [33]: A = np.random.rand(3,5)*10; A = A.astype(int); A
Out[33]:
array([[7, 1, 4, 3, 1],
       [1, 8, 8, 2, 4],
       [7, 4, 8, 0, 2]])

In [34]: B = np.linspace(3,7,5); B
Out[34]: array([3., 4., 5., 6., 7.])

In [35]: multiply_along_axis(A, B, axis=1)
Out[34]:
array([[21.,  4., 20., 18.,  7.],
       [ 3., 32., 40., 12., 28.],
       [21., 16., 40.,  0., 14.]])
</code>```

Body:
It seems I am getting lost in something potentially silly.
 I have an n-dimensional numpy array, and I want to multiply it with a vector (1d array) along some dimension (which can change!).
As an example, say I want to multiply a 2d array by a 1d array along axis 0 of the first array, I can do something like this:

a=np.arange(20).reshape((5,4))
b=np.ones(5)
c=a*b[:,np.newaxis]

Easy, but I would like to extend this idea to n-dimensions (for a, while b is always 1d) and to any axis. In other words, I would like to know how to generate a slice with the np.newaxis at the right place. Say that a is 3d and I want to multiply along axis=1, I would like to generate the slice which would correctly give:

c=a*b[np.newaxis,:,np.newaxis]

I.e. given the number of dimensions of a (say 3), and the axis along which I want to multiply (say axis=1), how do I generate and pass the slice:

np.newaxis,:,np.newaxis

Thanks.

Body:
I got a similar demand when I was working on some numerical calculation.

Let's assume we have two arrays (A and B) and a user-specified 'axis'.
A is a multi-dimensional array.
B is a 1-d array.

The basic idea is to expand B so that A and B have the same shape. Here is the solution code

import numpy as np
from numpy.core._internal import AxisError

def multiply_along_axis(A, B, axis):
    A = np.array(A)
    B = np.array(B)
    # shape check
    if axis >= A.ndim:
        raise AxisError(axis, A.ndim)
    if A.shape[axis] != B.size:
        raise ValueError("'A' and 'B' must have the same length along the given axis")
    # Expand the 'B' according to 'axis':
    # 1. Swap the given axis with axis=0 (just need the swapped 'shape' tuple here)
    swapped_shape = A.swapaxes(0, axis).shape
    # 2. Repeat:
    # loop through the number of A's dimensions, at each step:
    # a) repeat 'B':
    #    The number of repetition = the length of 'A' along the
    #    current looping step;
    #    The axis along which the values are repeated. This is always axis=0,
    #    because 'B' initially has just 1 dimension
    # b) reshape 'B':
    #    'B' is then reshaped as the shape of 'A'. But this 'shape' only
    #     contains the dimensions that have been counted by the loop
    for dim_step in range(A.ndim-1):
        B = B.repeat(swapped_shape[dim_step+1], axis=0)\
             .reshape(swapped_shape[:dim_step+2])
    # 3. Swap the axis back to ensure the returned 'B' has exactly the
    # same shape of 'A'
    B = B.swapaxes(0, axis)
    return A * B

And here is an example

In [33]: A = np.random.rand(3,5)*10; A = A.astype(int); A
Out[33]:
array([[7, 1, 4, 3, 1],
       [1, 8, 8, 2, 4],
       [7, 4, 8, 0, 2]])

In [34]: B = np.linspace(3,7,5); B
Out[34]: array([3., 4., 5., 6., 7.])

In [35]: multiply_along_axis(A, B, axis=1)
Out[34]:
array([[21.,  4., 20., 18.,  7.],
       [ 3., 32., 40., 12., 28.],
       [21., 16., 40.,  0., 14.]])