问:
How to get level(depth) number of two connected nodes in neo4j
I'm using neo4j as a graph database to store user's connections detail into this. here I want to show the level of one user with respect to another user in their connections like Linkedin. for example- first layer connection, second layer connection, third layer and above the third layer shows 3+. but I don't know how this happens using neo4j. i searched for this but couldn't find any solution for this. if anybody knows about this then please help me to implement this functionality.</p>

答:
it would be something like this</p>

```<code>// get all persons  (or users)
MATCH (p:Person)

// create a set of unique combinations , assuring that you do
// not do double work
WITH COLLECT(p) AS personList
UNWIND personList AS personA
UNWIND personList AS personB

WITH personA,personB
WHERE id(personA) < id(personB)

// find the shortest path between any two nodes
MATCH path=shortestPath( (personA)-[:LINKED_TO*]-(personB) )

// return the distance  ( = path length) between the two nodes
RETURN personA.name AS nameA,
       personB.name AS nameB,
       CASE WHEN length(path) > 3 THEN '3+'
            ELSE toString(length(path))
       END AS distance
</code>```

Body:
it would be something like this

// get all persons  (or users)
MATCH (p:Person)

// create a set of unique combinations , assuring that you do
// not do double work
WITH COLLECT(p) AS personList
UNWIND personList AS personA
UNWIND personList AS personB

WITH personA,personB
WHERE id(personA) < id(personB)

// find the shortest path between any two nodes
MATCH path=shortestPath( (personA)-[:LINKED_TO*]-(personB) )

// return the distance  ( = path length) between the two nodes
RETURN personA.name AS nameA,
       personB.name AS nameB,
       CASE WHEN length(path) > 3 THEN '3+'
            ELSE toString(length(path))
       END AS distance


来源: stackexchange

问:
Firebase Database rules - wildcard for dynamic key
I have this usecase where I want to give permission to other users read data under my ID key only if there is a key === to their Id.

Let’s say I have user 123 and 456 who writes json object under “

```<code>orders-
              I
               -123
                        I
                         -456
</code>```

And I want only user 123 and 456 to be able to read the 456 nodes. With the rules that I provide only 123 is able to read the node:

```<code>"orders": {
    "$uid": {
        ".read": "auth.uid  === $uid || root.child('orders').child($uid).child(auth.uid).exists()",
        ".write": "auth.uid != null",
    }
}
</code>```

What am I doing wrong here? Can anyone help me with this, please?

EDIT: Two screenshots of the simulator

答:
I solved it setting these rules (note $id is nested in $uid):

```<code>{
  "rules": {
          "orders": {
          "$uid": {
            ".read": "auth.uid  === $uid",
        ".write": "auth.uid === $uid",
          "$id": {
            ".read": "auth.uid  === $id",
            ".write": "auth.uid === $id"
          },
          }
        }
  }
}
</code>```

Previously I tought this line should do the work:

```<code> ".read": "auth.uid  === $uid || root.child('orders').child($uid).child(auth.uid).exists()",
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this usecase where I want to give permission to other users read data under my ID key only if there is a key === to their Id.

Let’s say I have user 123 and 456 who writes json object under “

orders-
              I
               -123
                        I
                         -456

And I want only user 123 and 456 to be able to read the 456 nodes. With the rules that I provide only 123 is able to read the node:

"orders": {
    "$uid": {
        ".read": "auth.uid  === $uid || root.child('orders').child($uid).child(auth.uid).exists()",
        ".write": "auth.uid != null",
    }
}

What am I doing wrong here? Can anyone help me with this, please?

EDIT: Two screenshots of the simulator

Body:
I solved it setting these rules (note $id is nested in $uid):

{
  "rules": {
          "orders": {
          "$uid": {
            ".read": "auth.uid  === $uid",
        ".write": "auth.uid === $uid",
          "$id": {
            ".read": "auth.uid  === $id",
            ".write": "auth.uid === $id"
          },
          }
        }
  }
}

Previously I tought this line should do the work:

 ".read": "auth.uid  === $uid || root.child('orders').child($uid).child(auth.uid).exists()",


问:
Extract particular value from column and exit from loop
I want to extract column dispstatus from below command and if all the entries are GREEN then i should come out of the loop.

```<code>sapcontrol -nr 01 -function GetProcessList

17.02.2020 01:40:34
GetProcessList
OK
name, description, dispstatus, textstatus, starttime, elapsedtime, pid
disp+work, Dispatcher, GREEN, Running, 2020 02 16 03:50:28, 21:50:06, 59404
igswd_mt, IGS Watchdog, GREEN, Running, 2020 02 16 03:50:28, 21:50:06, 59405
gwrd, Gateway, GREEN, Running, 2020 02 16 03:50:30, 21:50:04, 59423
icman, ICM, GREEN, Running, 2020 02 16 03:50:30, 21:50:04, 59424
</code>```

For now i have used below command where instead of getting all the values i'm checking the counts of GREEN and exiting which is currently not what i intend to do. Can you please help me?

```<code>while true ; do status=`sapcontrol -nr 01 -function GetProcessList |awk -F ',' '{if ($3) print $3;}'|grep -i GREEN | wc -l`; sleep 2; if [[ $status -ge 2 ]]; then break ;fi; done
</code>```

EDIT: some command in different lines.

```<code>while true ; do
   status=`sapcontrol -nr 01 -function GetProcessList |
      awk -F ',' '{if ($3) print $3;}'|
      grep -i GREEN |
      wc -l`
   sleep 2
   if [[ $status -ge 2 ]]; then
      break
   fi
done
</code>```

Thanks,
Anup

答:
Try this</p>

```<code>while true ; do
    status=$(sapcontrol -nr 01 -function GetProcessList)
    case $status in
        *GREEN*GREEN*GREEN*GREEN*) break;;
    esac
done
</code>```

Body:
I want to extract column dispstatus from below command and if all the entries are GREEN then i should come out of the loop.

sapcontrol -nr 01 -function GetProcessList

17.02.2020 01:40:34
GetProcessList
OK
name, description, dispstatus, textstatus, starttime, elapsedtime, pid
disp+work, Dispatcher, GREEN, Running, 2020 02 16 03:50:28, 21:50:06, 59404
igswd_mt, IGS Watchdog, GREEN, Running, 2020 02 16 03:50:28, 21:50:06, 59405
gwrd, Gateway, GREEN, Running, 2020 02 16 03:50:30, 21:50:04, 59423
icman, ICM, GREEN, Running, 2020 02 16 03:50:30, 21:50:04, 59424

For now i have used below command where instead of getting all the values i'm checking the counts of GREEN and exiting which is currently not what i intend to do. Can you please help me?

while true ; do status=`sapcontrol -nr 01 -function GetProcessList |awk -F ',' '{if ($3) print $3;}'|grep -i GREEN | wc -l`; sleep 2; if [[ $status -ge 2 ]]; then break ;fi; done

EDIT: some command in different lines.

while true ; do
   status=`sapcontrol -nr 01 -function GetProcessList |
      awk -F ',' '{if ($3) print $3;}'|
      grep -i GREEN |
      wc -l`
   sleep 2
   if [[ $status -ge 2 ]]; then
      break
   fi
done

Thanks,
Anup

Body:
Try this

while true ; do
    status=$(sapcontrol -nr 01 -function GetProcessList)
    case $status in
        *GREEN*GREEN*GREEN*GREEN*) break;;
    esac
done


问:
I am getting TypeError: unhashable type: 'list', while trying to find the word frequency
I am getting

```<code>TypeError: unhashable type: 'list'
</code>```

when I am trying this piece of code:

```<code>from nltk import FreqDist
fd = FreqDist()
token_words = data['tweet_split'].apply(lambda tweet: tweet.split())
for i in token_words:

 fd[i] += 1
print(fd)
</code>```

答:
Although you didn't specify exactly what data is, data['tweet_split'] is likely returning a list of lists, and FreqDist is a probably a dictionary-like object.

So when you do fd[i] += 1 you are indexing fd with a list, which with a dictionary or something that uses dictionaries in their implementation is not possible, because lists are not hashable.  It's possible you can convert i here to a tuple like tuple(i), but it's not clear if this is exactly what you intended either.

This is because Python dicts can only be indexed with immutable objects which, by nature of being immutable, have an immutable hash value.  tuples are like lists in that they are a collection of elements, but one of the main differences is that they cannot be modified, so as long as their contents are also immutable, the tuple's hash is constant:

```<code>>>> t = ('a', 'b', 'c')
>>> hash(t)
6876511439064834292
>>> l = ['a', 'b', 'c']
>>> hash(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
</code>```

lists could in principle be hashed, but the problem is that elements of a list can be added, removed, or modified in-place, so the hash of the list would not be constant, and thus would not be useful as a dictionary key.

Body:
I am getting

TypeError: unhashable type: 'list'

when I am trying this piece of code:

from nltk import FreqDist
fd = FreqDist()
token_words = data['tweet_split'].apply(lambda tweet: tweet.split())
for i in token_words:

 fd[i] += 1
print(fd)

Body:
Although you didn't specify exactly what data is, data['tweet_split'] is likely returning a list of lists, and FreqDist is a probably a dictionary-like object.

So when you do fd[i] += 1 you are indexing fd with a list, which with a dictionary or something that uses dictionaries in their implementation is not possible, because lists are not hashable.  It's possible you can convert i here to a tuple like tuple(i), but it's not clear if this is exactly what you intended either.

This is because Python dicts can only be indexed with immutable objects which, by nature of being immutable, have an immutable hash value.  tuples are like lists in that they are a collection of elements, but one of the main differences is that they cannot be modified, so as long as their contents are also immutable, the tuple's hash is constant:

>>> t = ('a', 'b', 'c')
>>> hash(t)
6876511439064834292
>>> l = ['a', 'b', 'c']
>>> hash(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

lists could in principle be hashed, but the problem is that elements of a list can be added, removed, or modified in-place, so the hash of the list would not be constant, and thus would not be useful as a dictionary key.


问:
Duplicate persistence units with name *PU
I'm trying to install a WAR file generated by Maven to a Weblogic server, but I get the following error messages from weblogic while trying to deploy:

```<code>Duplicate persistence units with name DummyPU.
First PU location:
file:/home/weblogic/middleware/user_projects/domains/middleware_domain/servers/AdminServer/tmp/_WL_user/ichipscreens/l4qn3z/lib/jps-internal.jar.

Second PU location:
 file:/home/weblogic/middleware/user_projects/domains/middleware_domain/servers/AdminServer/tmp/_WL_user/ichipscreens/wo22a/war/WEB-INF/lib/jps-internal.jar
</code>```

What does this mean? and how can i overcome this?

答:
I got similar issue.
However the cause of the issue is different.
In my ear file's application.xml, I have <library-directory>jars-dir</library-directory> element.I have commented it out since there's no ear jars needed by my application.
It worked !

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to install a WAR file generated by Maven to a Weblogic server, but I get the following error messages from weblogic while trying to deploy:

Duplicate persistence units with name DummyPU.
First PU location:
file:/home/weblogic/middleware/user_projects/domains/middleware_domain/servers/AdminServer/tmp/_WL_user/ichipscreens/l4qn3z/lib/jps-internal.jar.

Second PU location:
 file:/home/weblogic/middleware/user_projects/domains/middleware_domain/servers/AdminServer/tmp/_WL_user/ichipscreens/wo22a/war/WEB-INF/lib/jps-internal.jar

What does this mean? and how can i overcome this?


问:
Celery doesn't take multiple tasks when worker started from service
My Python Flask application supports some long-running tasks, which are invoked using API or CURL calls from some other systems.

When I execute the following command by manually entering it into a terminal, it works great.

celery worker -A manage.celery --loglevel=info -f log/celery.log

Now, I want to create a service for the server, where if the system restarts, this celery worker should start on its own. But, when following command is executed from service, it doesn't take any new tasks from the queue.

celery worker -A manage.celery --pool=solo --loglevel=info -f log/celery.log

I can see CURL call hitting server, but the underlying tasks are not getting started in celery.

Any idea on how this can be resolved?

答:
There was an issue in command written in services file. My command in services file was celery worker -A manage.celery --pool=solo --loglevel=info -f log/celery.log

Whereas, on terminal I had used celery worker -A manage.celery --loglevel=info -f log/celery.log command. Here --pool=solo wasn't used, and thus multiple tasks could be executed.

Updated the command in services file, and it started executing multiple tasks there as well.

In-depth understanding of execution pools can be taken from this link.


问:
Page Not Found Error occured while trying to render form in django
I've been following the instructions here.

This is the error it gives me, when i try to run it on localhost:

```<code>Page not found (404)
Request Method:     GET
Request URL:    http://localhost:7000/account.html

Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this
order:

[name='index']
[name='account']
db/ [name='db']
admin/
^celery-progress/

The current path, account.html, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change
that to False, and Django will display a standard 404 page.
</code>```

This is what i have in my urls.py

```<code> urlpatterns = [
 path("", hello.views.index, name="index"),
 path("", hello.views.account, name="account"),
 path("db/", hello.views.db, name="db"),
 path("admin/", admin.site.urls),
 re_path(r'^celery-progress/', include('celery_progress.urls'))
 ]
</code>```

This is what i have in views.py

```<code>def account(request):
if request.method == 'POST':
    form = AccountForm(request.POST)

    if form.is_valid():
        return HttpResponseRedirect('loading.html')

else:
    form = Nameform()

return render(request, 'account.html', {'form': form})
</code>```

Finally this is the form itself(account.html):

```<code><form action="/account/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</code>```

I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated.

答:
First, you need to change the URL patterns, because multiple views (hello.views.index and hello.views.account) are pointing towards the same pattern

```<code>urlpatterns = [
    <b>path("index/", hello.views.index, name="index"),
    path("account/", hello.views.account, name="account"),</b>
    path("db/", hello.views.db, name="db"),
    path("admin/", admin.site.urls),
    re_path(r'^celery-progress/', include('celery_progress.urls'))
]</code>```

then, access the URL, http://localhost:7000/account/

Body:
I've been following the instructions here.

This is the error it gives me, when i try to run it on localhost:

Page not found (404)
Request Method:     GET
Request URL:    http://localhost:7000/account.html

Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this
order:

[name='index']
[name='account']
db/ [name='db']
admin/
^celery-progress/

The current path, account.html, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change
that to False, and Django will display a standard 404 page.

This is what i have in my urls.py

 urlpatterns = [
 path("", hello.views.index, name="index"),
 path("", hello.views.account, name="account"),
 path("db/", hello.views.db, name="db"),
 path("admin/", admin.site.urls),
 re_path(r'^celery-progress/', include('celery_progress.urls'))
 ]

This is what i have in views.py

def account(request):
if request.method == 'POST':
    form = AccountForm(request.POST)

    if form.is_valid():
        return HttpResponseRedirect('loading.html')

else:
    form = Nameform()

return render(request, 'account.html', {'form': form})

Finally this is the form itself(account.html):

<form action="/account/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated.

Body:
First, you need to change the URL patterns, because multiple views (hello.views.index and hello.views.account) are pointing towards the same pattern

urlpatterns = [
    path("index/", hello.views.index, name="index"),
    path("account/", hello.views.account, name="account"),
    path("db/", hello.views.db, name="db"),
    path("admin/", admin.site.urls),
    re_path(r'^celery-progress/', include('celery_progress.urls'))
]

then, access the URL, http://localhost:7000/account/


问:
Serving different webflux endpoints on different eventloops
I have ported a large spring-web codebase to spring-webflux. There two sets of endpoints, some critical endpoints that must be fast, and some others that are not vital if they end up blocking in production. I can validate that none of the critical endpoints block on the eventloop thread, but validating all the other endpoints is not feasible. I would like to run them on a different threadpool or eventloop, so if they block, they do not affect the critical endpoints.

How would I go about this?

I've tried using reflection to find all the handlers that either should or shouldn't be on a secondary eventloop, but can't think of a way to assign them to it. Alternatively, is it possible to run both spring-web and spring-webflux, and have spring-web serve the non-critical endpoints?

I've managed to get the handlers from the handler registry like so:

```<code>@Component
class HandlerFinder(val requestMappingHandlerMappings: List<RequestMappingHandlerMapping>) {

    @PostConstruct
    fun start() {
        for (rmhm : RequestMappingHandlerMapping in requestMappingHandlerMappings) {
            val handlerMethods: Map<RequestMappingInfo, HandlerMethod> = rmhm.handlerMethods

            for ((mapping, method) in handlerMethods) {
                for (urlPattern in mapping.patternsCondition.patterns) {
                    log.info("${method.beanType.name}#${method.method.name} <-- ${urlPattern}")
                }
            }
        }
    }

    companion object {
        private val log = LoggerFactory.getLogger(HandlerFinder::class.java)
    }
}
</code>```

I think the next step would be to somehow change the handlers to be wrapped in something like below, but I'm not sure how to change this in the handler registry:

Mono.fromCallable(() -> { ... handler method goes here ...}).publishOn(Schedulers.elastic());
```

I know I can unregister the mapping with rmhm.ungreisterMapping(mapping) and then re-register it with something like rmhm.registerMapping(mapping, method.bean, method.method), but I'll need to create new methods to wrap the existing ones somehow.

答:
I solved this by creating a WebFilter and changing subscribeOn as Thomas' answer suggests.

```<code>@Component
class SchedulerWebFilter(): WebFilter {
    val executorService = Executors.newFixedThreadPool(32)
    private val pathsWhitelist: Set<String> = ...

    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        val path = exchange.request.path.toString()
        return if (!pathsWhitelist.contains(path)) {
            chain.filter(exchange).subscribeOn(Schedulers.fromExecutor(executorService))
        } else {
            chain.filter(exchange)
        }
    }
}
</code>```

Body:
I have ported a large spring-web codebase to spring-webflux. There two sets of endpoints, some critical endpoints that must be fast, and some others that are not vital if they end up blocking in production. I can validate that none of the critical endpoints block on the eventloop thread, but validating all the other endpoints is not feasible. I would like to run them on a different threadpool or eventloop, so if they block, they do not affect the critical endpoints.

How would I go about this?

I've tried using reflection to find all the handlers that either should or shouldn't be on a secondary eventloop, but can't think of a way to assign them to it. Alternatively, is it possible to run both spring-web and spring-webflux, and have spring-web serve the non-critical endpoints?

I've managed to get the handlers from the handler registry like so:

@Component
class HandlerFinder(val requestMappingHandlerMappings: List<RequestMappingHandlerMapping>) {

    @PostConstruct
    fun start() {
        for (rmhm : RequestMappingHandlerMapping in requestMappingHandlerMappings) {
            val handlerMethods: Map<RequestMappingInfo, HandlerMethod> = rmhm.handlerMethods

            for ((mapping, method) in handlerMethods) {
                for (urlPattern in mapping.patternsCondition.patterns) {
                    log.info("${method.beanType.name}#${method.method.name} <-- ${urlPattern}")
                }
            }
        }
    }

    companion object {
        private val log = LoggerFactory.getLogger(HandlerFinder::class.java)
    }
}

I think the next step would be to somehow change the handlers to be wrapped in something like below, but I'm not sure how to change this in the handler registry:

Mono.fromCallable(() -> { ... handler method goes here ...}).publishOn(Schedulers.elastic());

I know I can unregister the mapping with rmhm.ungreisterMapping(mapping) and then re-register it with something like rmhm.registerMapping(mapping, method.bean, method.method), but I'll need to create new methods to wrap the existing ones somehow.

Body:
I solved this by creating a WebFilter and changing subscribeOn as Thomas' answer suggests.

@Component
class SchedulerWebFilter(): WebFilter {
    val executorService = Executors.newFixedThreadPool(32)
    private val pathsWhitelist: Set<String> = ...

    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        val path = exchange.request.path.toString()
        return if (!pathsWhitelist.contains(path)) {
            chain.filter(exchange).subscribeOn(Schedulers.fromExecutor(executorService))
        } else {
            chain.filter(exchange)
        }
    }
}


问:
Issues trying to SSH into a fresh EC2 instance with Paramiko
I'm working on a script that spins up a fresh EC2 instance with boto and uses the Paramiko SSH client to execute remote commands on the instance. For whatever reason, the Paramiko client is unabled to connect, I get the error:

```<code>Traceback (most recent call last):
  File "scripts/sconfigure.py", line 29, in <module>
    ssh.connect(instance.ip_address, username='ubuntu', key_filename=os.path.expanduser('~/.ssh/test'))
  File "build/bdist.macosx-10.3-fat/egg/paramiko/client.py", line 291, in connect
  File "<string>", line 1, in connect
socket.error: [Errno 61] Connection refused
</code>```

I can ssh in fine manually using the same key file and user. Has anyone run into issues using Paramiko? My full code is below. Thanks.

```<code>import boto.ec2, time, paramiko, os
# Connect to the us-west-1 region
ec2 = boto.ec2.regions()[3].connect()
image_id = 'ami-ad7e2ee8'
image_name = 'Ubuntu 10.10 (Maverick Meerkat) 32-bit EBS'
new_reservation = ec2.run_instances(
    image_id=image_id,
    key_name='test',
    security_groups=['web'])

instance = new_reservation.instances[0]

print "Spinning up instance for '%s' - %s. Waiting for it to boot up." % (image_id, image_name)
while instance.state != 'running':
    print "."
    time.sleep(1)
    instance.update()

print "Instance is running, ip: %s" % instance.ip_address

print "Connecting to %s as user %s" % (instance.ip_address, 'ubuntu')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(instance.ip_address, username='ubuntu', key_filename=os.path.expanduser('~/.ssh/test'))
stdin, stdout, stderr = ssh.exec_command('echo "TEST"')
print stdout.readlines()
ssh.close()
</code>```

答: I seem to have figured this out by trial and error. Even though the instance status is "running" according to boto, there is a delay for when it will actually allow an SSH connection. Adding a "time.sleep(30)" before the "ssh.connect(...)" seems to do the trick for me, though this may vary.</p>

Body:
I'm working on a script that spins up a fresh EC2 instance with boto and uses the Paramiko SSH client to execute remote commands on the instance. For whatever reason, the Paramiko client is unabled to connect, I get the error:

Traceback (most recent call last):
  File "scripts/sconfigure.py", line 29, in <module>
    ssh.connect(instance.ip_address, username='ubuntu', key_filename=os.path.expanduser('~/.ssh/test'))
  File "build/bdist.macosx-10.3-fat/egg/paramiko/client.py", line 291, in connect
  File "<string>", line 1, in connect
socket.error: [Errno 61] Connection refused

I can ssh in fine manually using the same key file and user. Has anyone run into issues using Paramiko? My full code is below. Thanks.

import boto.ec2, time, paramiko, os
# Connect to the us-west-1 region
ec2 = boto.ec2.regions()[3].connect()
image_id = 'ami-ad7e2ee8'
image_name = 'Ubuntu 10.10 (Maverick Meerkat) 32-bit EBS'
new_reservation = ec2.run_instances(
    image_id=image_id,
    key_name='test',
    security_groups=['web'])

instance = new_reservation.instances[0]

print "Spinning up instance for '%s' - %s. Waiting for it to boot up." % (image_id, image_name)
while instance.state != 'running':
    print "."
    time.sleep(1)
    instance.update()

print "Instance is running, ip: %s" % instance.ip_address

print "Connecting to %s as user %s" % (instance.ip_address, 'ubuntu')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(instance.ip_address, username='ubuntu', key_filename=os.path.expanduser('~/.ssh/test'))
stdin, stdout, stderr = ssh.exec_command('echo "TEST"')
print stdout.readlines()
ssh.close()


问:
Animate cursor following already animated element
I have an element which has an animation for scaling up and down (like breathing effect) and I want to add cursor following.

My code works only If I delete the animation in CSS.

What I'm doing wrong?

looks like your post is mostly code; please add some more details.

class FollowCursor {
  constructor(element, window) {
    this.element = element;
    this.w = window;
    this.w.onmousemove = this.move.bind(this);
  }

  move(e) {
    this.element.setAttribute(
      "style",
      `transform: translate(${e.clientX}px, ${e.clientY}px);`
    );
  }
}

const el = document.querySelector(".el")

const cursorFollowing = new FollowCursor(el, window)```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .el {
   position: absolute;
   animation: a-breathing 8s infinite forwards;
   left: 0;
   top: 0;
   width: 30px;
   height: 30px;
   background-color: yellow;
 }

 div {
   position: relative
 }

 @keyframes a-breathing {
   0% {
     transform: scale(1);
   }

   60% {
     transform: scale(1.8);
   }

   100% {
     transform: scale(1);
   }
 }

``````
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div class="el">
</div>
</div></code>```

jsfiddle snippet

答:
I believe you'll get your expected behavior if you change this line

transform: translate(${e.clientX}px, ${e.clientY}px);

for this:

position: absolute; top: ${e.clientY}px; left: ${e.clientX}px

E.g.:  https://jsfiddle.net/cxszqdka/

Body:
I have an element which has an animation for scaling up and down (like breathing effect) and I want to add cursor following.

My code works only If I delete the animation in CSS.

What I'm doing wrong?

looks like your post is mostly code; please add some more details.

class FollowCursor {
  constructor(element, window) {
    this.element = element;
    this.w = window;
    this.w.onmousemove = this.move.bind(this);
  }

  move(e) {
    this.element.setAttribute(
      "style",
      `transform: translate(${e.clientX}px, ${e.clientY}px);`
    );
  }
}

const el = document.querySelector(".el")

const cursorFollowing = new FollowCursor(el, window)

 .el {
   position: absolute;
   animation: a-breathing 8s infinite forwards;
   left: 0;
   top: 0;
   width: 30px;
   height: 30px;
   background-color: yellow;
 }

 div {
   position: relative
 }

 @keyframes a-breathing {
   0% {
     transform: scale(1);
   }

   60% {
     transform: scale(1.8);
   }

   100% {
     transform: scale(1);
   }
 }

```

jsfiddle snippet


问:
Passing values from one fragment to another
I'm working in Kotlin and using retrofit. I have a recycler view, which consists of cards. Each card has a typeName and an image associated to it which for now I have added statically using dataclass. Now, I need to pass the typeName only from the CategoryFragment to the LocationFragment once the user clicks on a particular card. And at the LocationFragment I want to check the latitude, longitude and typeName from the database if it already exists.

Here's my code for the dataclass of Category:
data class Category_dataclass ( val category_image : Int , val typeName: String)

Here's my code for the CategoryFragment:

```<code>package com.example.atry.MakeComplaint

import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.Complaints
import com.example.atry.History.MyComplainRecyclerViewAdapter

import com.example.atry.R
import kotlinx.android.synthetic.main.existing_complaint_popup.*

class CategoryFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val v = inflater.inflate(R.layout.fragment_category, container, false)
        val recyclerView = v.findViewById(R.id.category_list) as RecyclerView

        recyclerView.apply {
            layoutManager = GridLayoutManager(context!!, 2)
        }

        //creating an arraylist to store category using the data class user
        val category = ArrayList<Category_dataclass>()

        //adding some dummy data to the list of categories
        category.add(Category_dataclass((R.drawable.trash) , "Water"))
        category.add(Category_dataclass((R.drawable.fire) , "Sewerage"))
        category.add(Category_dataclass((R.drawable.dustbin) , "load"))

        //creating our adapter
        val adapter = CategoryRecyclerViewAdapter(category)

        //now adding the adapter to recyclerview
        recyclerView.adapter = adapter

        // Inflate the layout for this fragment
        return v

    }

    }
</code>```

Here's the CategoryRecyclerViewAdapter:

```<code>package com.example.atry.MakeComplaint

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.ComplaintDetailsFragment
import com.example.atry.History.Complaints
import com.example.atry.MakeComplaint.Category_dataclass
import com.example.atry.MakeComplaint.CategoryRecyclerViewAdapter
import com.example.atry.R
import java.util.*
import kotlin.collections.ArrayList

class CategoryRecyclerViewAdapter(val categoryList: ArrayList<Category_dataclass>) : RecyclerView.Adapter<CategoryRecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryRecyclerViewAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.fragment_category_single, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItems(categoryList[position])
        holder.mView.setOnClickListener{view->

            val lFragment = LocationFragment()
            val oldFragment = CategoryFragment()
            val manager = (holder.mView.context as AppCompatActivity).supportFragmentManager
            val transaction =  manager.beginTransaction()
            transaction.replace(
                R.id.first_screen_of_makecomplaint,
                lFragment
            ) // give your fragment container id in first parameter
            transaction.show(lFragment)
            transaction.hide(oldFragment)
            transaction.isAddToBackStackAllowed
            transaction.addToBackStack(oldFragment.fragmentManager.toString())  // if written, this transaction will be added to backstack
            transaction.commit()

        }
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return categoryList.size
    }

    inner class ViewHolder(val mView : View) : RecyclerView.ViewHolder(mView) {
        fun bindItems(cat:Category_dataclass) {
            val imageViewName = mView.findViewById(R.id.category_image) as ImageView
            val textViewtext = mView.findViewById(R.id.category_text) as TextView

            imageViewName.setImageResource(cat.category_image)
            textViewtext.text = cat.typeName

        }

    }

}
</code>```

And this is my retrofit:

```<code> //to check existing complaint

    @GET("api/existingComplain")
    @FormUrlEncoded
    fun checkExistingComplain(@Query("typeName") typeName:String,
                              @Query("longitude") longitude:String,
                              @Query("latitude") latitude:String):Observable<Observables.checkExistingResult>

</code>```

I've created and object where i stored the dataclass which will return the following:

```<code>data class checkExistingResult(val description:String , val Complain:String)
</code>```

if the typeName and location already exists in the database I want the description and Complain to be displayed on a material styled dialog.

答:
You can try this:

1st Step:-

```<code>val dashboard = "Dashboard"
</code>```

take variable like this you can take it's name as your fragment name so page name you can check like this MainActivity().dashboard

Now, 2nd Step:-

create one class and write function like this in that class

```<code> fun openPage(
    activity: Activity,
    pagename: String?, model: PaymentDetails
) {
    when (pagename) {

            MainActivity().dashboard -> {
                val mfragment = DashboardFragment()
                (activity as MainActivity).fragmentManager.beginTransaction()
                    .replace(R.id.nav_host, mfragment).commit()

                val a = Bundle()
                a.putSerializable("model", model)
                mfragment.arguments = a
            }
        }
    }
</code>```

take key value pair as I take my whole model and key is model in my code you can write any thing.

3rd Step:-

Make your model Serializable

4th Step:- When you are adding your values into model add details and add your model for method in which you want to use these values like following

```<code>val payment = PaymentDetails(
            type,
            price,
            name,
            id,
         )
        paymentData!!.add(payment)
        CustomMethods().openPagePaymentDetails(
            activity!!,
            MainActivity().sessionPaymentFragment, payment
        )
</code>```

5th Step:-

Declare and initialise your object with type of your model like following:

```<code> //Declare
 private var model: PaymentDetails? = null

//initialise
 model = arguments!!.getSerializable("model") as PaymentDetails?
</code>```

And now finally you can access value of previous fragment into your next fragment like this,

```<code>var type: String
type = model!!.type
</code>```

Note:- please do no forgot to make your model class Serializable

Hope so it will help you.

Body:
I'm working in Kotlin and using retrofit. I have a recycler view, which consists of cards. Each card has a typeName and an image associated to it which for now I have added statically using dataclass. Now, I need to pass the typeName only from the CategoryFragment to the LocationFragment once the user clicks on a particular card. And at the LocationFragment I want to check the latitude, longitude and typeName from the database if it already exists.

Here's my code for the dataclass of Category:
data class Category_dataclass ( val category_image : Int , val typeName: String)

Here's my code for the CategoryFragment:

package com.example.atry.MakeComplaint

import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.Complaints
import com.example.atry.History.MyComplainRecyclerViewAdapter

import com.example.atry.R
import kotlinx.android.synthetic.main.existing_complaint_popup.*

class CategoryFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val v = inflater.inflate(R.layout.fragment_category, container, false)
        val recyclerView = v.findViewById(R.id.category_list) as RecyclerView

        recyclerView.apply {
            layoutManager = GridLayoutManager(context!!, 2)
        }

        //creating an arraylist to store category using the data class user
        val category = ArrayList<Category_dataclass>()

        //adding some dummy data to the list of categories
        category.add(Category_dataclass((R.drawable.trash) , "Water"))
        category.add(Category_dataclass((R.drawable.fire) , "Sewerage"))
        category.add(Category_dataclass((R.drawable.dustbin) , "load"))

        //creating our adapter
        val adapter = CategoryRecyclerViewAdapter(category)

        //now adding the adapter to recyclerview
        recyclerView.adapter = adapter

        // Inflate the layout for this fragment
        return v

    }

    }

Here's the CategoryRecyclerViewAdapter:

package com.example.atry.MakeComplaint

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.atry.History.ComplaintDetailsFragment
import com.example.atry.History.Complaints
import com.example.atry.MakeComplaint.Category_dataclass
import com.example.atry.MakeComplaint.CategoryRecyclerViewAdapter
import com.example.atry.R
import java.util.*
import kotlin.collections.ArrayList

class CategoryRecyclerViewAdapter(val categoryList: ArrayList<Category_dataclass>) : RecyclerView.Adapter<CategoryRecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryRecyclerViewAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.fragment_category_single, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItems(categoryList[position])
        holder.mView.setOnClickListener{view->

            val lFragment = LocationFragment()
            val oldFragment = CategoryFragment()
            val manager = (holder.mView.context as AppCompatActivity).supportFragmentManager
            val transaction =  manager.beginTransaction()
            transaction.replace(
                R.id.first_screen_of_makecomplaint,
                lFragment
            ) // give your fragment container id in first parameter
            transaction.show(lFragment)
            transaction.hide(oldFragment)
            transaction.isAddToBackStackAllowed
            transaction.addToBackStack(oldFragment.fragmentManager.toString())  // if written, this transaction will be added to backstack
            transaction.commit()

        }
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return categoryList.size
    }

    inner class ViewHolder(val mView : View) : RecyclerView.ViewHolder(mView) {
        fun bindItems(cat:Category_dataclass) {
            val imageViewName = mView.findViewById(R.id.category_image) as ImageView
            val textViewtext = mView.findViewById(R.id.category_text) as TextView

            imageViewName.setImageResource(cat.category_image)
            textViewtext.text = cat.typeName

        }

    }

}

And this is my retrofit:

 //to check existing complaint

    @GET("api/existingComplain")
    @FormUrlEncoded
    fun checkExistingComplain(@Query("typeName") typeName:String,
                              @Query("longitude") longitude:String,
                              @Query("latitude") latitude:String):Observable<Observables.checkExistingResult>

I've created and object where i stored the dataclass which will return the following:

data class checkExistingResult(val description:String , val Complain:String)

if the typeName and location already exists in the database I want the description and Complain to be displayed on a material styled dialog.

Body:
You can try this:

1st Step:-

val dashboard = "Dashboard"

take variable like this you can take it's name as your fragment name so page name you can check like this MainActivity().dashboard

Now, 2nd Step:-

create one class and write function like this in that class

 fun openPage(
    activity: Activity,
    pagename: String?, model: PaymentDetails
) {
    when (pagename) {

            MainActivity().dashboard -> {
                val mfragment = DashboardFragment()
                (activity as MainActivity).fragmentManager.beginTransaction()
                    .replace(R.id.nav_host, mfragment).commit()

                val a = Bundle()
                a.putSerializable("model", model)
                mfragment.arguments = a
            }
        }
    }

take key value pair as I take my whole model and key is model in my code you can write any thing.

3rd Step:-

Make your model Serializable

4th Step:- When you are adding your values into model add details and add your model for method in which you want to use these values like following

val payment = PaymentDetails(
            type,
            price,
            name,
            id,
         )
        paymentData!!.add(payment)
        CustomMethods().openPagePaymentDetails(
            activity!!,
            MainActivity().sessionPaymentFragment, payment
        )

5th Step:-

Declare and initialise your object with type of your model like following:

 //Declare
 private var model: PaymentDetails? = null

//initialise
 model = arguments!!.getSerializable("model") as PaymentDetails?

And now finally you can access value of previous fragment into your next fragment like this,

var type: String
type = model!!.type

Note:- please do no forgot to make your model class Serializable

Hope so it will help you.


问:
Regex to match a word with at least one letter and any number of digits (no lookaround)
I'm new to regular expressions and I'm trying to come up with a regex which matches a word which contains at least one letter and zero or more digits.

Example:

users - match

u343sers - match

13123123 - not match

I cannot use lookarounds because I need to use the regex in Go and the regexp package doesn't support them.

Is this possible without lookarounds?

答:
If you are using Java, the regex for your requirement is [\\p{L}0-9]*\\p{L}[\\p{L}0-9]*

Explanation:

\p{L} matches any single letter (e.g. A-Za-z, a letter from Greek, German etc. locales)

[\\p{L}0-9]* matches any number of letters or digits because of the quantifier * applied on the character classes consisting of letter and digits.

Thus, the pattern [\\p{L}0-9]*\\p{L}[\\p{L}0-9]* means Any number of letters or digits + A single letter + Any number of letters or digits

Check java.util.regex.Pattern to learn more about these patterns.

Demo:

```<code>public class Main {
    public static void main(String[] args) {
        String[] testStrings = { "A1ö1", "_a_", "1Ωω2", "123", "1", "a", "abc", "ABC", "aBc123", "123abc", "123abc123",
                "aBc123aBc", "_123", "123_", "123_123", "1_a", "_", "a_", "a_1.", "123.a", "12.56" };
        for (String s : testStrings) {
            System.out.println(s.matches("[\\p{L}0-9]*\\p{L}[\\p{L}0-9]*") ? s + " matches" : s + " does not match");
        }
    }
}
</code>```

Output:

```<code>A1ö1 matches
_a_ does not match
1Ωω2 matches
123 does not match
1 does not match
a matches
abc matches
ABC matches
aBc123 matches
123abc matches
123abc123 matches
aBc123aBc matches
_123 does not match
123_ does not match
123_123 does not match
1_a does not match
_ does not match
a_ does not match
a_1. does not match
123.a does not match
12.56 does not match
</code>```

Body:
If you are using Java, the regex for your requirement is [\\p{L}0-9]*\\p{L}[\\p{L}0-9]*

Explanation:

\p{L} matches any single letter (e.g. A-Za-z, a letter from Greek, German etc. locales)

[\\p{L}0-9]* matches any number of letters or digits because of the quantifier * applied on the character classes consisting of letter and digits.

Thus, the pattern [\\p{L}0-9]*\\p{L}[\\p{L}0-9]* means Any number of letters or digits + A single letter + Any number of letters or digits

Check java.util.regex.Pattern to learn more about these patterns.

Demo:

public class Main {
    public static void main(String[] args) {
        String[] testStrings = { "A1ö1", "_a_", "1Ωω2", "123", "1", "a", "abc", "ABC", "aBc123", "123abc", "123abc123",
                "aBc123aBc", "_123", "123_", "123_123", "1_a", "_", "a_", "a_1.", "123.a", "12.56" };
        for (String s : testStrings) {
            System.out.println(s.matches("[\\p{L}0-9]*\\p{L}[\\p{L}0-9]*") ? s + " matches" : s + " does not match");
        }
    }
}

Output:

A1ö1 matches
_a_ does not match
1Ωω2 matches
123 does not match
1 does not match
a matches
abc matches
ABC matches
aBc123 matches
123abc matches
123abc123 matches
aBc123aBc matches
_123 does not match
123_ does not match
123_123 does not match
1_a does not match
_ does not match
a_ does not match
a_1. does not match
123.a does not match
12.56 does not match


答:
You're overwriting your transform attribute since you can only have one per element, so you need an element to move around and another div element to do the breathing; here is the solution:

class FollowCursor {
  constructor(element, window) {
    this.element = element;
    this.w = window;
    this.w.onmousemove = this.move.bind(this);
  }

  move(e) {
    this.element.setAttribute(
      "style",
      `transform: translate(${e.clientX}px, ${e.clientY}px);`
    );
  }
}

const el = document.querySelector(".el")

const cursorFollowing = new FollowCursor(el, window)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.el {
   position: absolute;
   left: 0;
   top: 0;
   width: 30px;
   height: 30px;
   background-color: yellow;
 }
.breathing-element {
  animation: a-breathing 8s infinite forwards;
  width: 100%;
  height: 100%;
  background: red;
}
 div {
   position: relative
 }

 @keyframes a-breathing {
   0% {
     transform: scale(1);
   }

   60% {
     transform: scale(1.8);
   }

   100% {
     transform: scale(1);
   }
 }</code>```

```
</div>
</div>
</p>

<p>You can also combine multiple values for the transform attribute following this pattern:</p>

```transform: translate | transform | scale | rotate
```

Title: Animate cursor following already animated element

Body:
You're overwriting your transform attribute since you can only have one per element, so you need an element to move around and another div element to do the breathing; here is the solution:

class FollowCursor {
  constructor(element, window) {
    this.element = element;
    this.w = window;
    this.w.onmousemove = this.move.bind(this);
  }

  move(e) {
    this.element.setAttribute(
      "style",
      `transform: translate(${e.clientX}px, ${e.clientY}px);`
    );
  }
}

const el = document.querySelector(".el")

const cursorFollowing = new FollowCursor(el, window)

.el {
   position: absolute;
   left: 0;
   top: 0;
   width: 30px;
   height: 30px;
   background-color: yellow;
 }
.breathing-element {
  animation: a-breathing 8s infinite forwards;
  width: 100%;
  height: 100%;
  background: red;
}
 div {
   position: relative
 }

 @keyframes a-breathing {
   0% {
     transform: scale(1);
   }

   60% {
     transform: scale(1.8);
   }

   100% {
     transform: scale(1);
   }
 }

<div>
<div class="el">
  <div class="breathing-element"></div>
</div>
</div>

You can also combine multiple values for the transform attribute following this pattern:

transform: translate | transform | scale | rotate


问:
How to add a item on title bar in SwiftUI?
I have a navigation bar, and I want to custom it. Here is I want:
navigationBar
I tried the navigationBarItems, but it’s not working.</p>

答:
Hello i have attached the code for your needs ! Kindly adjust the image according to your need . </p>

```<code>\\call this function in viewdidLoad()
 func addNavBarImage() {

        let navController = navigationController!

        let image = UIImage(named: "Image.png") //Your logo url here
        let imageView = UIImageView(image: image)

        let bannerWidth = navController.navigationBar.frame.size.width
        let bannerHeight = navController.navigationBar.frame.size.height

        let bannerX = bannerWidth / 2.5 - (image?.size.width)! / 2.5
        let bannerY = bannerHeight / 2 - (image?.size.height)! / 2

        imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
        imageView.contentMode = .scaleAspectFit

        navigationItem.titleView = imageView
}
</code>```

Body:
Hello i have attached the code for your needs ! Kindly adjust the image according to your need .

\\call this function in viewdidLoad()
 func addNavBarImage() {

        let navController = navigationController!

        let image = UIImage(named: "Image.png") //Your logo url here
        let imageView = UIImageView(image: image)

        let bannerWidth = navController.navigationBar.frame.size.width
        let bannerHeight = navController.navigationBar.frame.size.height

        let bannerX = bannerWidth / 2.5 - (image?.size.width)! / 2.5
        let bannerY = bannerHeight / 2 - (image?.size.height)! / 2

        imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
        imageView.contentMode = .scaleAspectFit

        navigationItem.titleView = imageView
}


问:
Flyway placeholder when exist value if not exit it will skip replaceholder
I would like to replaceholder only value that exist if not exist I want skip it.

Example:

1 V1__customer.sql

```<code>insert into customer(id,name) values(1, ${name});
</code>```

2 V2__staff.sql

```<code>insert into staff(id,age) values(1, ${age});
</code>```

in code

```<code>            ThreadLocalContextUtil.setInstance(instance);
            final var flyway = new Flyway();
            flyway.setDataSource(Datasource.class);
            flyway.setLocations("instance_db");
            flyway.setOutOfOrder(true);
            flyway.setValidateOnMigrate(false);
            flyway.getPlaceholders().put("name", "mr empty");
            applyProperties(flyway);
            flyway.migrate();
</code>```

Question :How to replace on name only and for age skip it.

答:
This use case isn't really supported. Flyway will produce an error if it finds a placeholder token without a corresponding value. I can think of a workaround however.

You could 'seed' your placeholders with empty strings. This will stop Flyway producing an error for unset values.

Inside your migration scripts you could then introduce guard conditions that only run when values are provided.

For instance, in Java:

```<code>// Seed with empty strings
flyway.getPlaceholders().put("name", "");
flyway.getPlaceholders().put("id", "");
...
// Overwrite some of the placeholders
flyway.getPlaceholders().put("name", "mr empty");
</code>```

Then in your script (pseudo code):

```<code>IF '${name}' NOT EQUAL TO '' THEN
insert into customer(id,name) values(1, ${name});
</code>```

If you want built in support you should create an issue on Flyway's GitHub page.

Body:
I would like to replaceholder only value that exist if not exist I want skip it.

Example:

1 V1__customer.sql

insert into customer(id,name) values(1, ${name});

2 V2__staff.sql

insert into staff(id,age) values(1, ${age});

in code

            ThreadLocalContextUtil.setInstance(instance);
            final var flyway = new Flyway();
            flyway.setDataSource(Datasource.class);
            flyway.setLocations("instance_db");
            flyway.setOutOfOrder(true);
            flyway.setValidateOnMigrate(false);
            flyway.getPlaceholders().put("name", "mr empty");
            applyProperties(flyway);
            flyway.migrate();

Question :How to replace on name only and for age skip it.

Body:
This use case isn't really supported. Flyway will produce an error if it finds a placeholder token without a corresponding value. I can think of a workaround however.

You could 'seed' your placeholders with empty strings. This will stop Flyway producing an error for unset values.

Inside your migration scripts you could then introduce guard conditions that only run when values are provided.

For instance, in Java:

// Seed with empty strings
flyway.getPlaceholders().put("name", "");
flyway.getPlaceholders().put("id", "");
...
// Overwrite some of the placeholders
flyway.getPlaceholders().put("name", "mr empty");

Then in your script (pseudo code):

IF '${name}' NOT EQUAL TO '' THEN
insert into customer(id,name) values(1, ${name});

If you want built in support you should create an issue on Flyway's GitHub page.


问:
How to open an external Excel macro file as read-only using a ribbon button?
I've got an Excel add-in file (.xlam) stored in a shared location, and a bunch of custom Ribbon buttons linking to the macros in that file. When user clicks on the button, the add-in is opened for them, and the macro from that add-in runs. There are many users of that add-in, and they constantly have Excel open, so when I need to make an update to the add-in, I have to ask everyone to close all Excel files and wait for me to complete the update. Therefore, I'm wondering if it's possible to always make the add-in open as read-only when called from the Ribbon? </p>

答:
Not exactly answering the question in the header, but I solved my problem, and maybe someone finds it useful as well.

Solution is very simple: right click on the .xlam file in question, select "Properties" and tick "Read-Only". It will always open as read-only, not just when called from Ribbon, but you can make changes to the file by saving it in another location, and then replacing the original file.


问:
How to convert string to bool and evaluate the condition?
I have to convert a string to bool and evaluate the string condition.
For example:

```<code>string condition = "8 > 9 || !8";
</code>```

then the condition has to evaluate and return true;

if string condition = "!8"; then condition has to return true.

Suggest me how to evaluate the condition.

答:
Try using the IValueConverter interface provided by .net

https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.ivalueconverter?view=netframework-4.8

Where u define 2 methods Convert and ConvertBack
Each method takes a parameter of type object and return the type object

so u can input the string and return the Boolean.
As for the conversion from a string to expression you can checkout this link
https://expressiontree-tutorial.net/knowledge-base/5029699/csharp-convert-string-expression-to-a-boolean-expression
which have the required code cleared out.

Body:
I have to convert a string to bool and evaluate the string condition.
For example:

string condition = "8 > 9 || !8";

then the condition has to evaluate and return true;

if string condition = "!8"; then condition has to return true.

Suggest me how to evaluate the condition.


问:
How to wait until file is uploaded using Axios
I'm working on a Reactjs project where I can upload and download files.

But when I upload a file, the request PUT from Axios is completed before the file is fully uploaded to my database.
I use the onUploadProgress from Axios and it shows directly 100% after I click on the upload button whereas the file is not uploaded yet.

It even seems that the upload of the file on the back side is only starts once the progress bar reaches 100%.
I don't know how to correctly synchronize the progress bar with the file uploading.

My code

Front

```<code>  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .put("http://localhost:5000/api/files/upload", data, {
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }
</code>```

Back

```<code>export const uploadFile = (req, res) => {
  const myFile = (Array.isArray(req.files.file)
    ? req.files.file
    : [req.files.file]
  ).filter(e => e);
  // upload file(s) to directory
  for (let i = 0; i < myFile.length; i++) {
    myFile[i].mv("./src/uploads/" + myFile[i].name, function(err) {
      if (err) {
        return res.status(500).send(err);
      }
    });
    // save file(s) to database
    Upload.create({
      type: myFile[i].mimetype,
      name: myFile[i].name,
      data: myFile[i].data
    });
  }
  res.send("file uploaded !");
};
</code>```

By the way I'm using https://www.npmjs.com/package/express-fileupload for file upload

EDIT

```<code>  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .post("http://localhost:5000/api/files/upload", data, {
        headers: {
          "Content-type": "multipart/form-data"
        },
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }
</code>```

答:
```<code>onUpload() {
const data = new FormData();
for (var i = 0; i < this.state.selectedFile.length; i++) {
  data.append("file", this.state.selectedFile[i]);
}
axios
  .post("http://localhost:5000/api/files/upload", data, {
    headers: {
      "Content-type": "multipart/form-data"
    },
    onUploadProgress: ProgressEvent => {
      this.setState({
        loaded: 95
      });
    }
  })
  .then(res => {
   this.setState({
        loaded: 100
      });
    console.log("File(s) uploaded", res);
  });
</code>```

<p>}</p>

Body:
I'm working on a Reactjs project where I can upload and download files.

But when I upload a file, the request PUT from Axios is completed before the file is fully uploaded to my database.
I use the onUploadProgress from Axios and it shows directly 100% after I click on the upload button whereas the file is not uploaded yet.

It even seems that the upload of the file on the back side is only starts once the progress bar reaches 100%.
I don't know how to correctly synchronize the progress bar with the file uploading.

My code

Front

  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .put("http://localhost:5000/api/files/upload", data, {
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }

Back

export const uploadFile = (req, res) => {
  const myFile = (Array.isArray(req.files.file)
    ? req.files.file
    : [req.files.file]
  ).filter(e => e);
  // upload file(s) to directory
  for (let i = 0; i < myFile.length; i++) {
    myFile[i].mv("./src/uploads/" + myFile[i].name, function(err) {
      if (err) {
        return res.status(500).send(err);
      }
    });
    // save file(s) to database
    Upload.create({
      type: myFile[i].mimetype,
      name: myFile[i].name,
      data: myFile[i].data
    });
  }
  res.send("file uploaded !");
};

By the way I'm using https://www.npmjs.com/package/express-fileupload for file upload

EDIT

  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .post("http://localhost:5000/api/files/upload", data, {
        headers: {
          "Content-type": "multipart/form-data"
        },
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }

Body:
onUpload() {
const data = new FormData();
for (var i = 0; i < this.state.selectedFile.length; i++) {
  data.append("file", this.state.selectedFile[i]);
}
axios
  .post("http://localhost:5000/api/files/upload", data, {
    headers: {
      "Content-type": "multipart/form-data"
    },
    onUploadProgress: ProgressEvent => {
      this.setState({
        loaded: 95
      });
    }
  })
  .then(res => {
   this.setState({
        loaded: 100
      });
    console.log("File(s) uploaded", res);
  });

}


问:
Spatial index/query (finding k nearest points)
I have +10k points (latitude, longitude) and I'm building an app that shows you the k nearest points to a user's location.

I think this is a very common problem and I don't want to reinvent the wheel. I'm learning about Quadtrees. It seems to be a good approach to solve this spatial problem.

I'm using these tools:

Python 2.5

MySQL

MongoDb

Building the Quadtree is not that hard: http://donar.umiacs.umd.edu/quadtree/points/pointquad.html But once I've created the tree and saved it to a db (MySQL or MongoDb), how I run the query?

I need to run queries like these:

Find all points within 10 km of the user's location.

Find the 6 (or at least 6) nearest points to the
user's location.

What's the standard and common approach to do it?

EDIT 1:

I've loaded the +10k points into MongoDB (Geospatial indexing) and it works fine at first glance. Anyway I've found PostGis:

PostGIS is an extension to the PostgreSQL object-relational database system which allows GIS (Geographic Information Systems) objects to be stored in the database.

So I think I'll give PostGis a try.

I've also found SimpleGeo. You can store points/places in the cloud and then query them via an API: https://simplegeo.com/docs/tutorials/python#how-do-radial-nearby-query

答: You may want to look at kdtree entry in wikipedia. This would be useful when you have more than two dimensions too (unlike quadtrees). I suggest the kd-tree because the entry has python code for creating and querying the tree.</p>


问:
How to remove the error hint on input focus in vueJS
I'd like to remove the error when I have focus on my input.
Here is my input:

```<code>      <v-text-field
        v-model="models.codePostal"
        label="Code postal"
        :rules="regles.codePostal"
        :hint="this.models.communeResidence.codePostal!==''?`Pourrait être ${this.models.communeResidence.codePostal}`:''"
        hide-details="auto"></v-text-field>
</code>```

I thought I could add

```<code>@focus="error=false"
</code>```

But it doesn't work.
Does anybody have an idea? It may not be possible.
Thanks.

答:
Use reset method on focus event.

```<code><v-text-field
  @focus="reset()"
  ref="field"
  v-model="models.codePostal"
  label="Code postal"
  :rules="regles.codePostal"
  :hint="this.models.communeResidence.codePostal!==''?`Pourrait être ${this.models.communeResidence.codePostal}`:''"
  hide-details="auto"
></v-text-field>
</code>```

```<code> methods: {
    reset() {
      this.$refs.field.reset()
    }
</code>```

Or resetValidation() method in the same way if you don't want to clear the field.

Body:
I'd like to remove the error when I have focus on my input.
Here is my input:

      <v-text-field
        v-model="models.codePostal"
        label="Code postal"
        :rules="regles.codePostal"
        :hint="this.models.communeResidence.codePostal!==''?`Pourrait être ${this.models.communeResidence.codePostal}`:''"
        hide-details="auto"></v-text-field>

I thought I could add

@focus="error=false"

But it doesn't work.
Does anybody have an idea? It may not be possible.
Thanks.

Body:
Use reset method on focus event.

<v-text-field
  @focus="reset()"
  ref="field"
  v-model="models.codePostal"
  label="Code postal"
  :rules="regles.codePostal"
  :hint="this.models.communeResidence.codePostal!==''?`Pourrait être ${this.models.communeResidence.codePostal}`:''"
  hide-details="auto"
></v-text-field>

 methods: {
    reset() {
      this.$refs.field.reset()
    }

Or resetValidation() method in the same way if you don't want to clear the field.


问:
Issue in user input or text file data in sentiment analysis
I am new to Python-NLTK. I have written my code using movie reviews data set.
When I put hard coded sample text for sentiment analysis it is working fine but when I try to take user input or fetch the data from text file it shows alphabet level splitting.

for e.g.
When sample text is hard coded like
["Music was awesome", "Special effects are awesome"]
Then splitting is like a
Review : Music was awesome
Review : Special effects are awesome.

But if I asked for user input or fetch the data from text file then it shows review as;
Review: M
Review: u
Review: S
Review: i
Review: c
Review: .

#For text file Below is my sample code.

```<code>t = open ("Sample1.txt", "r")
File_input = (t.read())
for review in File_input:
  print ("\nReview:", review)
  probdist = classifier.prob_classify(extract_features(review.split()))
  pred_sentiment = probdist.max()

print ("Predicted sentiment:", pred_sentiment)
print ("Probability:", round(probdist.prob(pred_sentiment), 5))
</code>```

#For user input Below is my sample code.

```<code>User_input = input("Enter your value: ")
for review in User_input:
  print ("\nReview:", review)
  probdist = classifier.prob_classify(extract_features(review.split()))
  pred_sentiment = probdist.max()
print ("Predicted sentiment:", pred_sentiment)
print ("Probability:", round(probdist.prob(pred_sentiment), 3))
</code>```

plz guide.
Thanks!

答:
the User_input variable is a string, so iterating over it is iterating over the chars, what you want to do is remove the for loop and treat User_input as a review assuming it holds 1 review, otherwise you could define a separating char between reviews and iterate like so:

```<code>for review in User_input.split(sep_char):
</code>```

Body:
I am new to Python-NLTK. I have written my code using movie reviews data set.
When I put hard coded sample text for sentiment analysis it is working fine but when I try to take user input or fetch the data from text file it shows alphabet level splitting.

for e.g.
When sample text is hard coded like
["Music was awesome", "Special effects are awesome"]
Then splitting is like a
Review : Music was awesome
Review : Special effects are awesome.

But if I asked for user input or fetch the data from text file then it shows review as;
Review: M
Review: u
Review: S
Review: i
Review: c
Review: .

#For text file Below is my sample code.

t = open ("Sample1.txt", "r")
File_input = (t.read())
for review in File_input:
  print ("\nReview:", review)
  probdist = classifier.prob_classify(extract_features(review.split()))
  pred_sentiment = probdist.max()

print ("Predicted sentiment:", pred_sentiment)
print ("Probability:", round(probdist.prob(pred_sentiment), 5))

#For user input Below is my sample code.

User_input = input("Enter your value: ")
for review in User_input:
  print ("\nReview:", review)
  probdist = classifier.prob_classify(extract_features(review.split()))
  pred_sentiment = probdist.max()
print ("Predicted sentiment:", pred_sentiment)
print ("Probability:", round(probdist.prob(pred_sentiment), 3))

plz guide.
Thanks!

Body:
the User_input variable is a string, so iterating over it is iterating over the chars, what you want to do is remove the for loop and treat User_input as a review assuming it holds 1 review, otherwise you could define a separating char between reviews and iterate like so:

for review in User_input.split(sep_char):


问:
Remove the numbers < 4 digits in list in a data frame in R
I have a data frame like this this, i need to remove the values less than 4 digits in the item column,

```<code>department  item
xyz009   c("1","676547","2","434567","3","567369","4","987654","6","54546676732")
</code>```

Output

```<code>department  item

xyz009      676547,434567,567369,987654,54546676732
</code>```

Thank you for your help

答:
1.Create a minimal reproducible example

```<code>xyz009 <- c("1","676547","2","434567","3","567369","4","987654","6","54546676732")
</code>```

2.Suggested solution using base R:

The vector xyz009 is of type character

```<code>typeof(xyz009)

[1] "character"
</code>```

In order to do maths with it (i.e. use >) we have to cast it to numeric using as.numeric

```<code>num_xyz <- as.numeric(xyz009)
</code>```

Now we can use an index to 'filter' values where an expression evaluates to TRUE:

```<code>test_result <- num_xyz > 9999
</code>```

The vector test_result consists of booleans

```<code>test_result

[1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
</code>```

We can use these booleans as an 'index' (R keeps only values where the index is TRUE):

```<code>num_xyz[test_result]
</code>```

This returns:

```<code>[1]      676547      434567      567369      987654 54546676732
</code>```

Body:
I have a data frame like this this, i need to remove the values less than 4 digits in the item column,

department  item
xyz009   c("1","676547","2","434567","3","567369","4","987654","6","54546676732")

Output

department  item

xyz009      676547,434567,567369,987654,54546676732

Thank you for your help

Body:
1.Create a minimal reproducible example

xyz009 <- c("1","676547","2","434567","3","567369","4","987654","6","54546676732")

2.Suggested solution using base R:

The vector xyz009 is of type character

typeof(xyz009)

[1] "character"

In order to do maths with it (i.e. use >) we have to cast it to numeric using as.numeric

num_xyz <- as.numeric(xyz009)

Now we can use an index to 'filter' values where an expression evaluates to TRUE:

test_result <- num_xyz > 9999

The vector test_result consists of booleans

test_result

[1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE

We can use these booleans as an 'index' (R keeps only values where the index is TRUE):

num_xyz[test_result]

This returns:

[1]      676547      434567      567369      987654 54546676732


问:
how to delete nan in df from row without losing the whole row?
G'day, how can I drop the nan values without losing the whole row?
This is how my df looks like.

I have tried the pandasdf = schule.dropna()  But this deleted everything in the rows.

But I have to keep the values, because at the end, I want them to go upwards.

答: it might help. you can try it  !!!!

Body: it might help. you can try it  !!!!


问:
Python MultiLevel Index on DataFrame. Access first row of first index level to apply function
I have a multi-level index dataframe.  Level 1 index contains a unique key, level 2 index contains a date for the level 1 index.

Code:

```<code>import pandas as pd
from dateutil.relativedelta import relativedelta
from datetime import datetime

fake_data=pd.DataFrame([(x,pd.to_datetime('04/01/2020')+relativedelta(months=y)) for x in list(range(0,11)) for y in list(range(0,11))],columns=['x','y'])
fake_data['z']=fake_data['x']*np.random.uniform(low=1,high=1000)
fake_data.set_index(['x','y'],drop=True,inplace=True)
</code>```

The desired result is that for the start of level 1 index (groupby) and assign a new variable to the dataframe which contains the quarter which is based off of the values in the second level index.  How can I specifically access groupby level 1 index and apply a function which evaluates the level 2 index to generate the Quarter?

Pictured, the RIGHT panel is the desired result from the dataframe.

Desired Results

Body:
I have a multi-level index dataframe.  Level 1 index contains a unique key, level 2 index contains a date for the level 1 index.

Code:

import pandas as pd
from dateutil.relativedelta import relativedelta
from datetime import datetime

fake_data=pd.DataFrame([(x,pd.to_datetime('04/01/2020')+relativedelta(months=y)) for x in list(range(0,11)) for y in list(range(0,11))],columns=['x','y'])
fake_data['z']=fake_data['x']*np.random.uniform(low=1,high=1000)
fake_data.set_index(['x','y'],drop=True,inplace=True)

The desired result is that for the start of level 1 index (groupby) and assign a new variable to the dataframe which contains the quarter which is based off of the values in the second level index.  How can I specifically access groupby level 1 index and apply a function which evaluates the level 2 index to generate the Quarter?

Pictured, the RIGHT panel is the desired result from the dataframe.

Desired Results

Body:
Use MultiIndex.get_level_values for extract second level and add DatetimeIndex.quarter:

fake_data['qtr'] = fake_data.index.get_level_values(1).quarter
print (fake_data.head(20))
                       z  qtr
x y
0 2020-04-01    0.000000    2
  2020-05-01    0.000000    2
  2020-06-01    0.000000    2
  2020-07-01    0.000000    3
  2020-08-01    0.000000    3
  2020-09-01    0.000000    3
  2020-10-01    0.000000    4
  2020-11-01    0.000000    4
  2020-12-01    0.000000    4
  2021-01-01    0.000000    1
  2021-02-01    0.000000    1
1 2020-04-01  983.538088    2
  2020-05-01  983.538088    2
  2020-06-01  983.538088    2
  2020-07-01  983.538088    3
  2020-08-01  983.538088    3
  2020-09-01  983.538088    3
  2020-10-01  983.538088    4
  2020-11-01  983.538088    4
  2020-12-01  983.538088    4

If want always starting by 0 add factorize:

fake_data['qtr'] = pd.factorize(fake_data.index.get_level_values(1).quarter)[0]
print (fake_data.head(20))
                      z  qtr
x y
0 2020-04-01   0.000000    0
  2020-05-01   0.000000    0
  2020-06-01   0.000000    0
  2020-07-01   0.000000    1
  2020-08-01   0.000000    1
  2020-09-01   0.000000    1
  2020-10-01   0.000000    2
  2020-11-01   0.000000    2
  2020-12-01   0.000000    2
  2021-01-01   0.000000    3
  2021-02-01   0.000000    3
1 2020-04-01  80.286425    0
  2020-05-01  80.286425    0
  2020-06-01  80.286425    0
  2020-07-01  80.286425    1
  2020-08-01  80.286425    1
  2020-09-01  80.286425    1
  2020-10-01  80.286425    2
  2020-11-01  80.286425    2
  2020-12-01  80.286425    2


问:
Removing duplicate values without using distinct
I have written the below query using BigQuery and it gives me duplicate article values. I have tried using distinct but it doesn't seem to work somehow so now I'm looking into removing the duplicates with other methods.     </p>

```<code>select
      replace(article, ' - paper', '') as p,
      pageviews,
      login_clicks,
      paywall_clicks
    from analytics.article_action_week
</code>```

答:
group by feature can be helpful.</p>

```<code>select
  replace(article, ' - paper', '') as p,
  pageviews,
  login_clicks,
  paywall_clicks
from analytics.article_action_week group by article
</code>```

Body:
I have written the below query using BigQuery and it gives me duplicate article values. I have tried using distinct but it doesn't seem to work somehow so now I'm looking into removing the duplicates with other methods.

select
      replace(article, ' - paper', '') as p,
      pageviews,
      login_clicks,
      paywall_clicks
    from analytics.article_action_week

Body:
group by feature can be helpful.

select
  replace(article, ' - paper', '') as p,
  pageviews,
  login_clicks,
  paywall_clicks
from analytics.article_action_week group by article


问:
Construct AWS cost APi for getting total monthly costs or total daily usage for my account
i want to create/consume API for getting AWS cost daily and monthly details.
want to know how i can create api and check in the postman for getting cost details for my account.</p>

答:
You need to grant iam permissions for cost explorer to your account/iam user.
https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/ce-api.html

After that you are able to consume the api

https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Cost_Explorer_Service.html

with postman.

https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html


问:
How to get HTTP request body size in Google Cloud Functions?
I would like to retrieve the size of the request body to filter out the large HTTP post request.
So, How can I get the length of the request?</p>

答:
As per its documentation, Cloud Functions has a hard limit of 10 MB for HTTP request and response payloads. For more detail, you can check documentation.
and also, you cannot extend the limit as well(I have not found yet).

Just to check the length of your request, you can use req.get("content-length").


问:
How can I limit the hosts in a Template on AWX?
The hosts which I address in the Playbook maint-change.yml belong to two Groups (instancegroup1 & instancegroup2 with sveral hosts in each group) like this:

- hosts: "{{ server |  default('instancegroup1 instancegroup2')  }}"

So if I just want to run the Playbook against one host I will limit with (-e EXTRA_VARS) the variable server and the hostname from the instance:

ansible-playbook maint-change.yml -e server=test.instance2

In that Case the "test.instance2" is listet in the inventory file of instancegroup2 and the playbook will only run against the host "test.instance2" successfully.

But how is is that possible with awx? If I have created the template with the same Playbook "maint-change.yml" which is using the variable server as I mentioned above, it's not possible to paste the "server=test.instance2" in the EXTRA VARIABLES field of the Template. Is there any Solution to set the specific variable server from the Playbook in the EXTRA VARIABLES field from awx's Template?

答: I believe you are using AWX Job templates. You can use the limit check option in your templates. Here's a screenshot of that -


Title: Remove the numbers < 4 digits in list in a data frame in R

Body:
Maybe you can try nchar+subset

> subset(v,nchar(v)>4)
[1] "676547"      "434567"      "567369"
[4] "987654"      "54546676732"

DATA

v <- c("1","676547","2","434567","3","567369","4","987654","6","54546676732")


问:
How to import python classes from another directory
I am working in kaggle notebook.
I have uploaded a python script name ResidualAttentionNetwork.py. There is a class defined by name ResidualAttentionNetwork.
This class is uploaded into sub-folder.

Sub-folder is like :

```<code>input
  |_ residual_attention
      |_ Code
         |_ ResidualAttentionNetwork.py
</code>```

My python code:

```<code>from Code.ResidualAttentionNetwork import ResidualAttentionNetwork
</code>```

This throws an error : ModuleNotFoundError: No module named 'Code'

So I cant't get access to class ResidualAttentionNetwork.
Can you please help me.
here is the screenshot

答: You should read language basics about modules and PYTHONPATH to understand how to add you Code folder into sys.path.

Body:
I am working in kaggle notebook.
I have uploaded a python script name ResidualAttentionNetwork.py. There is a class defined by name ResidualAttentionNetwork.
This class is uploaded into sub-folder.

Sub-folder is like :

input
  |_ residual_attention
      |_ Code
         |_ ResidualAttentionNetwork.py

My python code:

from Code.ResidualAttentionNetwork import ResidualAttentionNetwork

This throws an error : ModuleNotFoundError: No module named 'Code'

So I cant't get access to class ResidualAttentionNetwork.
Can you please help me.
here is the screenshot


问:
set google cloud storage bucket access logs in java
I want to enable logging against a bucket on GCS using the java sdk. Essentially, I want to implement the equivalent of the gsutil command : gsutil logging set on -b gs://logging-bucket  -o AccessLog  gs://mycompanybucket as specified in the documentation here . I have tried to call the command line via java code but this always hands forever.

```<code>public static void checkLoggingBuckets(ArrayList<String> cloudbuckets) throws IOException {
            Runtime rt = Runtime.getRuntime();
            ArrayList<String> bucketList = cloudbuckets;
            try {
                for (String st: bucketList) {
                    String command = "cmd /c cmd.exe gsutil logging set on -b gs://logs-bucket-2019  -o AccessLog  gs://";
                    System.out.println("checking for bucket "  + st);
                    Process proc = rt.exec(command + st);

            int result = proc.waitFor();

            System.out.println("Process exit code: " + result);
            System.out.println();
            System.out.println("Result:");
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
                }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

答:
You can do that with the Java client, there is no need to start a subprocess with gsutil command :

Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get("mycompanybucket");

BucketInfo.Logging logging = BucketInfo.Logging.newBuilder()
    .setLogBucket("logging-bucket")  // -b parameter of gsutil logging set command
    .setLogObjectPrefix("AccessLog") // -o parameter of gsutil logging set command
    .build();

bucket = bucket.toBuilder()
    .setLogging(logging)
    .build()
    .update();
```

Source : https://github.com/googleapis/google-cloud-java/issues/6981#issuecomment-561648354.

Body:
I want to enable logging against a bucket on GCS using the java sdk. Essentially, I want to implement the equivalent of the gsutil command : gsutil logging set on -b gs://logging-bucket  -o AccessLog  gs://mycompanybucket as specified in the documentation here . I have tried to call the command line via java code but this always hands forever.

public static void checkLoggingBuckets(ArrayList<String> cloudbuckets) throws IOException {
            Runtime rt = Runtime.getRuntime();
            ArrayList<String> bucketList = cloudbuckets;
            try {
                for (String st: bucketList) {
                    String command = "cmd /c cmd.exe gsutil logging set on -b gs://logs-bucket-2019  -o AccessLog  gs://";
                    System.out.println("checking for bucket "  + st);
                    Process proc = rt.exec(command + st);

            int result = proc.waitFor();

            System.out.println("Process exit code: " + result);
            System.out.println();
            System.out.println("Result:");
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
                }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Body:
You can do that with the Java client, there is no need to start a subprocess with gsutil command :

Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket = storage.get("mycompanybucket");

BucketInfo.Logging logging = BucketInfo.Logging.newBuilder()
    .setLogBucket("logging-bucket")  // -b parameter of gsutil logging set command
    .setLogObjectPrefix("AccessLog") // -o parameter of gsutil logging set command
    .build();

bucket = bucket.toBuilder()
    .setLogging(logging)
    .build()
    .update();

Source : https://github.com/googleapis/google-cloud-java/issues/6981#issuecomment-561648354.


问:
How to stop a function from executing more than x times per day?
In Google Sheets Script, how do I stop a function from executing more than x e.g. 5 times a day?

For instance, I have a trigger that executes a function every 20 minutes that sends an email based on a condition in the function, however I only want it to send this email a maximum of 5 times a day. How would I do this?

答:
As other users recommended, you can store a value in the Project Properties, and use it to count how many times the script has been executed. I recommend you to use a condition to compare the new property with 5.

Remind to convert the property returned result type to Integer, as it is an
  String by default, otherwise you won't be able to add 1 in each
  execution.

As an example we can use the setProperty to modify the already saved value, for example:

```<code>var userProperties = PropertiesService.getUserProperties();
var newValue = +userProperties.getProperty('Execution_times') + 1;

userProperties.setProperty('Execution_times', newValue); // Updates stored value.
</code>```

Body:
As other users recommended, you can store a value in the Project Properties, and use it to count how many times the script has been executed. I recommend you to use a condition to compare the new property with 5.

Remind to convert the property returned result type to Integer, as it is an
  String by default, otherwise you won't be able to add 1 in each
  execution.

As an example we can use the setProperty to modify the already saved value, for example:

var userProperties = PropertiesService.getUserProperties();
var newValue = +userProperties.getProperty('Execution_times') + 1;

userProperties.setProperty('Execution_times', newValue); // Updates stored value.


问:
Error when I tried to assign a value in Angular
I have an object in angular:

```<code>export class Task {
  taskId: number;
  description: string;
  date: string;
  project: Project;
}
</code>```

And in a component, I want to have a method that adds a new task. And for this I created a component:

```<code>export class CreateNewTaskComponent implements OnInit {

  task: Task = new Task();
  projectName: string;
  newTask: Task = new Task();

  constructor(
    private taskService: TaskService,
    private projectService: ProjectService,
    private router: Router) {
  }

  addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {
        this.project = project;
        console.log('Project: ' + JSON.stringify(this.project));
      }
    );

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = this.project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
  }
</code>```

I have created a Project object based on the project name. When I did console.log('Project: ' + JSON.stringify(this.project)); I received the correct answer. But when I tried to assign the project to a new task  this.newTask.project = this.project; the result is undefined.

答:
Project is not defined in your component, but you are not getting that error so I am assuming it is just missing here

```<code>export class CreateNewTaskComponent implements OnInit {

 task: Task = new Task();
 projectName: string;
 newTask: Task = new Task();

 constructor(
   private taskService: TaskService,
   private projectService: ProjectService,
   private router: Router) {
 }

 addANewTask() {
   this.projectService.getProjectByProjectName(this.projectName).subscribe(
     (project) => {
       this.project = project;
       console.log('Project: ' + JSON.stringify(this.project));
// this should be inside subscribe and not outside
// it is async so might be executed after the lines outside
       this.newTask.project = this.project;
     }
   );

   //this.newTask.description = this.task.description;
   //this.newTask.date = this.task.date;
  // this.newTask.project = this.project;

   this.taskService.createNewTask(this.newTask).subscribe(
     task => {
       console.log(task);
// these should be here
this.newTask.description = this.task.description;
  this.newTask.date = this.task.date;
       this.router.navigate(['/tasks']);
     });
 }
</code>```

the assignment should be inside subscribe, I have updated code with some comments

Body:
I have an object in angular:

export class Task {
  taskId: number;
  description: string;
  date: string;
  project: Project;
}

And in a component, I want to have a method that adds a new task. And for this I created a component:

export class CreateNewTaskComponent implements OnInit {

  task: Task = new Task();
  projectName: string;
  newTask: Task = new Task();

  constructor(
    private taskService: TaskService,
    private projectService: ProjectService,
    private router: Router) {
  }

  addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {
        this.project = project;
        console.log('Project: ' + JSON.stringify(this.project));
      }
    );

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = this.project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
  }

I have created a Project object based on the project name. When I did console.log('Project: ' + JSON.stringify(this.project)); I received the correct answer. But when I tried to assign the project to a new task  this.newTask.project = this.project; the result is undefined.

Body:
Project is not defined in your component, but you are not getting that error so I am assuming it is just missing here

export class CreateNewTaskComponent implements OnInit {

 task: Task = new Task();
 projectName: string;
 newTask: Task = new Task();

 constructor(
   private taskService: TaskService,
   private projectService: ProjectService,
   private router: Router) {
 }

 addANewTask() {
   this.projectService.getProjectByProjectName(this.projectName).subscribe(
     (project) => {
       this.project = project;
       console.log('Project: ' + JSON.stringify(this.project));
// this should be inside subscribe and not outside
// it is async so might be executed after the lines outside
       this.newTask.project = this.project;
     }
   );

   //this.newTask.description = this.task.description;
   //this.newTask.date = this.task.date;
  // this.newTask.project = this.project;

   this.taskService.createNewTask(this.newTask).subscribe(
     task => {
       console.log(task);
// these should be here
this.newTask.description = this.task.description;
  this.newTask.date = this.task.date;
       this.router.navigate(['/tasks']);
     });
 }

the assignment should be inside subscribe, I have updated code with some comments