问:
How to use margin on checkboxes so they will be on each other
I have the following code:

```<code>    <LinearLayout
        android:id="@+id/availability_sunday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tile_divider"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/text_sunday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sunday:" />

        <CheckBox
            android:id="@+id/checkbox_sunday_morning"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp" />

        <TextView
            android:id="@+id/text_sunday_morning"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Morning"/>

        <CheckBox
            android:id="@+id/checkbox_sunday_evening"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content" />

        <TextView
            android:id="@+id/text_sunday_evening"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Evening"/>
    </LinearLayout>
</code>```

In a RelativeLayout. I would like the layout to be:

```<code>Sunday     [] Morning [] Evening
Monday     [] Morning [] Evening
...
Thursday   [] Morning [] Evening
</code>```

But If I add the same block for monday I will get:

Because the work android:layout_marginStart and android:layout_marginLeft. I want the checkbox to be above each other. How can I do it?

答:
Try below code:</p>

```<code><LinearLayout
   android:layout_below="@+id/tile_divider"
    android:id="@+id/availability_sunday"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/text_sunday"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Sunday:" />

    <CheckBox
        android:id="@+id/checkbox_sunday_morning"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:layout_width="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp" />

    <TextView
        android:id="@+id/text_sunday_morning"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Morning"/>

    <CheckBox
        android:id="@+id/checkbox_sunday_evening"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:layout_width="wrap_content" />

    <TextView
        android:id="@+id/text_sunday_evening"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Evening"/>
</LinearLayout>
</code>```

Body:
I have the following code:

    <LinearLayout
        android:id="@+id/availability_sunday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tile_divider"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/text_sunday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sunday:" />

        <CheckBox
            android:id="@+id/checkbox_sunday_morning"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp" />

        <TextView
            android:id="@+id/text_sunday_morning"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Morning"/>

        <CheckBox
            android:id="@+id/checkbox_sunday_evening"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true"
            android:layout_width="wrap_content" />

        <TextView
            android:id="@+id/text_sunday_evening"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Evening"/>
    </LinearLayout>

In a RelativeLayout. I would like the layout to be:

Sunday     [] Morning [] Evening
Monday     [] Morning [] Evening
...
Thursday   [] Morning [] Evening

But If I add the same block for monday I will get:

Because the work android:layout_marginStart and android:layout_marginLeft. I want the checkbox to be above each other. How can I do it?

Body:
Try below code:

<LinearLayout
   android:layout_below="@+id/tile_divider"
    android:id="@+id/availability_sunday"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/text_sunday"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Sunday:" />

    <CheckBox
        android:id="@+id/checkbox_sunday_morning"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:layout_width="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp" />

    <TextView
        android:id="@+id/text_sunday_morning"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Morning"/>

    <CheckBox
        android:id="@+id/checkbox_sunday_evening"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:layout_width="wrap_content" />

    <TextView
        android:id="@+id/text_sunday_evening"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Evening"/>
</LinearLayout>


来源: stackexchange

问:
Notify event from application to web page
first i describe my app then the question and.. sorry for my english.

I have an application that make some data processing, this app is write in C++.
The process search for some patterns in the data and trigger some event, when event is triggered i push data to a Database.

In the other hand i have a webpage (PHP or Ruby o Python) to see what happens in the C++ application. Some kind of Log. The web app query the Database to see the events.

But now i wan't to notify the webpage when i update the database (when an event is occur). The idea is immediately show the database change in the web app.

How can i accomplish that?

Any idea, model, guideline would help..

Thanks in advance and thank for your time!

EDIT: Finally i solve this using couchdb like my DB and node.js.
Couchdb have a grate _change API, this can be query for the change in real time with nodejs and push the change (the notification or the data) to webpage using socket.io

ContentLicense: CC BY-SA 3.0


问:
How can I show the computed compiler flags for a clang invocation?
For example, when I run clang with clang ... -Wno-error -Werror, I don't want to it to show -Wno-error, since it's being overridden. I could use -v or -### to print out what the driver's executing, but that doesn't help because it still shows -Wno-error -Werror at the end. How might I show the computed compiler flags?

答: The -cc1 flag -compiler-options-dump appears to be the best option at the moment.

ContentLicense: CC BY-SA 4.0


问:
Is there a better way to restrict method calling than by passing a string "password"? C#
For example: Let's say I only want a specific function (A) to be called from 2 specific places (B and C). Even though its possible to call A from other places (the function is public), I want to make sure I (or someone else) call the method via function B or C and not directly by mistake.

I've been thinking about it a lot and the only viable way I can come up with is something like:

```<code>public void A(string callingFrom, object arg1, object arg2)
{
    if (callingFrom != "B" && callingFrom != "C")
        throw new Exception("Call the function via B och C");

    // Some code
}

</code>```

*And please don't write anything like "If you need to do that then you have done something wrong in the first place". Not every codebase is 100% optimal - to say the least...

Any thoughts?

答:
One approach is to use interfaces to control access. I.e. the method A is public, but is not exposed in the interface. B and C gets a reference to the actual class, while everyone else gets the interface. This protection can be side stepped by casting the object, but it can make casual miss-use more difficult.

Another option is to put A, B, and C in the same project, and make A internal.

A third option would be to Use a method name that makes it clear that the method should only be used in some very special circumstances. If a developer sees method named a DoNotCallThisMethodFromAnythingExceptBorC with a prominent comment telling him why, he would probably not use it before investigating some more.

There is also CallerMemberName that can be used to automatically inject calling method/file name.

There is also the StackTrace class that can be used to inspect the calling method.

But please do not use callerMemberName or StackTrace for more than logging. It can easily result in runtime errors that can be difficult to find, and since it is not something most people do, your colleagues (current and future) will probably rightfully complain.

Body:
For example: Let's say I only want a specific function (A) to be called from 2 specific places (B and C). Even though its possible to call A from other places (the function is public), I want to make sure I (or someone else) call the method via function B or C and not directly by mistake.

I've been thinking about it a lot and the only viable way I can come up with is something like:

public void A(string callingFrom, object arg1, object arg2)
{
    if (callingFrom != "B" && callingFrom != "C")
        throw new Exception("Call the function via B och C");

    // Some code
}

*And please don't write anything like "If you need to do that then you have done something wrong in the first place". Not every codebase is 100% optimal - to say the least...

Any thoughts?


问:
Difference between these two requests
Request One  (Not working)

```<code>{
    "AddNewRequest":{
        "Patient":{
            "PrimaryPhoneNumber":" ",
            "DateOfBirth":" ",
            "CellPhoneNumber1":" ",
            "ResidentialAddress":{
                "AddressLine1":" ",
                "State":" ",
                "City":" ",
                "PostalCode":" "
            },
            "PhoneNumber1":" ",
            "SSN":" ",
            "FullName":"John",
            "Religion":" ",
            "Gender":" ",
            "Race":" ",
            "Firstname":"Vinoth",
            "EmailAddress1":" ",
            "LastName":"Cooper"
        },
        "Header":{
            "SourceSiteID":"300242",
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1"
        },
        "Credentials":{
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            },
            "PrimeSuiteCredential":{
                "PrimeSuiteUserPassword":"password",
                "PrimeSuiteSiteId":"1",
                "PrimeSuiteUserName":"Admin"
            }
        }
    }
}
</code>```

Request Two (Working)

```<code>{
    "PatientAddNewRequest":{
        "Credentials":{
            "PrimeSuiteCredential":{
                "PrimeSuiteSiteId":"300242",
                "PrimeSuiteUserName":"Admin",
                "PrimeSuiteUserPassword":"password"
            },
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            }
        },
        "Header":{
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1",
            ":SourceSiteID":"300242"
        },
        "Patient":{
            "CellPhoneNumber1":"206-567-2222",
            "DateOfBirth":"/Date(1306348200000)/",
            "EmailAddress1":"JohnDoe@yahoo.com",
            "Firstname":"TestMan1",
            "FullName":"TestFullMan1",
            "Gender":"2",
            "LastName":"Testlastname1",
            "PhoneNumber1":"205-567-1111",
            "PrimaryPhoneNumber":"205-456-4545",
            "Race":"2",
            "Religion":"3",
            "ResidentialAddress":{
                "City":"Carrollton",
                "PostalCode":"35209",
                "State":"10"
            },
            "SSN":"911-91-9191"
        }
    }
}
</code>```

I am just not able to figure out why the first request is not working and the second one gives response. Can anyone identify what i am doing wrong.

Does Order Matter?

Update

The First one throws me Bad Request and the second one responds as expected.

答:
Rename property name in #1 request

Have you tried renaming AddNewRequest to PatientAddNewRequest in the first request? Any difference?

Title: Difference between these two requests

Body:
Request One  (Not working)

{
    "AddNewRequest":{
        "Patient":{
            "PrimaryPhoneNumber":" ",
            "DateOfBirth":" ",
            "CellPhoneNumber1":" ",
            "ResidentialAddress":{
                "AddressLine1":" ",
                "State":" ",
                "City":" ",
                "PostalCode":" "
            },
            "PhoneNumber1":" ",
            "SSN":" ",
            "FullName":"John",
            "Religion":" ",
            "Gender":" ",
            "Race":" ",
            "Firstname":"Vinoth",
            "EmailAddress1":" ",
            "LastName":"Cooper"
        },
        "Header":{
            "SourceSiteID":"300242",
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1"
        },
        "Credentials":{
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            },
            "PrimeSuiteCredential":{
                "PrimeSuiteUserPassword":"password",
                "PrimeSuiteSiteId":"1",
                "PrimeSuiteUserName":"Admin"
            }
        }
    }
}

Request Two (Working)

{
    "PatientAddNewRequest":{
        "Credentials":{
            "PrimeSuiteCredential":{
                "PrimeSuiteSiteId":"300242",
                "PrimeSuiteUserName":"Admin",
                "PrimeSuiteUserPassword":"password"
            },
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            }
        },
        "Header":{
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1",
            ":SourceSiteID":"300242"
        },
        "Patient":{
            "CellPhoneNumber1":"206-567-2222",
            "DateOfBirth":"/Date(1306348200000)/",
            "EmailAddress1":"JohnDoe@yahoo.com",
            "Firstname":"TestMan1",
            "FullName":"TestFullMan1",
            "Gender":"2",
            "LastName":"Testlastname1",
            "PhoneNumber1":"205-567-1111",
            "PrimaryPhoneNumber":"205-456-4545",
            "Race":"2",
            "Religion":"3",
            "ResidentialAddress":{
                "City":"Carrollton",
                "PostalCode":"35209",
                "State":"10"
            },
            "SSN":"911-91-9191"
        }
    }
}

I am just not able to figure out why the first request is not working and the second one gives response. Can anyone identify what i am doing wrong.

Does Order Matter?

Update

The First one throws me Bad Request and the second one responds as expected.


问:
GITLAB CI Error loading key "/dev/fd/63": invalid format ERROR: Job failed: exit code 1
Here is my code  giltlab-ci.yml :

```<code> before_script:
  ##
  ## Install ssh-agent if not already installed, it is required by Docker.
  ## (change apt-get to yum if you use an RPM-based image)
  ##
  - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'

  ##
  ## Run ssh-agent (inside the build environment)
  ##
  - eval $(ssh-agent -s)
  ##
  ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
  ## We're using tr to fix line endings which makes ed25519 keys work
  ## without extra base64 encoding.
  ## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
  ##
  - mkdir -p ~/.ssh
  #- echo -n "$PROJECT_SSH_KEY" | ssh-add - >/dev/null
  - echo "$PROJECT_SSH_KEY"
  - ssh-add <(echo "$PROJECT_SSH_KEY")
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
      ##
  ## Create the SSH directory and give it the right permissions
  ##
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh

  ##
  ## Optionally, if you will be using any Git commands, set the user name and
  ## and email.
  ##
  #- git config --global user.email "user@example.com"
  #- git config --global user.name "User name"
</code>```

I get  this out put

Running with gitlab-runner 11.8.0 (4745a6f3)
        on Allence-Tunisie-docker-runner sH47eTgb
      Using Docker executor with image ntfactory/ci-tool:0.0.2 ...
      Pulling docker image ntfactory/ci-tool:0.0.2 ...
      Using docker image sha256:7fe7b170806f6846271eec23b41c4f79202777f62c0d7a32165dc41722900979
  for ntfactory/ci-tool:0.0.2 ...
      Running on runner-sH47eTgb-project-11060727-concurrent-0 via a732493b4b94...
      Cloning repository...
      Cloning into '/builds/allence-tunisie/e-formation'...
      Checking out 0a6b48ef as feat/gitlab-ci...
      Skipping Git submodules setup
      Checking cache for default...
      No URL provided, cache will not be downloaded from shared cache server. Instead a local version of cache will be extracted.
      Successfully extracted cache
      $ which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
      /usr/bin/ssh-agent
      $ eval $(ssh-agent -s)
      Agent pid 12
      $ mkdir -p ~/.ssh
      $ echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
      Error loading key "(stdin)": invalid format
      ERROR: Job failed: exit code 1

even though i tried  - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add
- > /dev/null   i get  this error

Error loading key "(stdin)": invalid format

答: If you have protected the variable then you need to have a protected branch. As mentioned in the variables settings - "They can be protected by only exposing them to protected branches or tags."</p>

Body:
Here is my code  giltlab-ci.yml :

 before_script:
  ##
  ## Install ssh-agent if not already installed, it is required by Docker.
  ## (change apt-get to yum if you use an RPM-based image)
  ##
  - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'

  ##
  ## Run ssh-agent (inside the build environment)
  ##
  - eval $(ssh-agent -s)
  ##
  ## Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
  ## We're using tr to fix line endings which makes ed25519 keys work
  ## without extra base64 encoding.
  ## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
  ##
  - mkdir -p ~/.ssh
  #- echo -n "$PROJECT_SSH_KEY" | ssh-add - >/dev/null
  - echo "$PROJECT_SSH_KEY"
  - ssh-add <(echo "$PROJECT_SSH_KEY")
  - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
      ##
  ## Create the SSH directory and give it the right permissions
  ##
  - mkdir -p ~/.ssh
  - chmod 700 ~/.ssh

  ##
  ## Optionally, if you will be using any Git commands, set the user name and
  ## and email.
  ##
  #- git config --global user.email "user@example.com"
  #- git config --global user.name "User name"

I get  this out put

Running with gitlab-runner 11.8.0 (4745a6f3)
        on Allence-Tunisie-docker-runner sH47eTgb
      Using Docker executor with image ntfactory/ci-tool:0.0.2 ...
      Pulling docker image ntfactory/ci-tool:0.0.2 ...
      Using docker image sha256:7fe7b170806f6846271eec23b41c4f79202777f62c0d7a32165dc41722900979
  for ntfactory/ci-tool:0.0.2 ...
      Running on runner-sH47eTgb-project-11060727-concurrent-0 via a732493b4b94...
      Cloning repository...
      Cloning into '/builds/allence-tunisie/e-formation'...
      Checking out 0a6b48ef as feat/gitlab-ci...
      Skipping Git submodules setup
      Checking cache for default...
      No URL provided, cache will not be downloaded from shared cache server. Instead a local version of cache will be extracted.
      Successfully extracted cache
      $ which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )
      /usr/bin/ssh-agent
      $ eval $(ssh-agent -s)
      Agent pid 12
      $ mkdir -p ~/.ssh
      $ echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
      Error loading key "(stdin)": invalid format
      ERROR: Job failed: exit code 1

even though i tried  - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add
- > /dev/null   i get  this error

Error loading key "(stdin)": invalid format


问:
Is there any way to implement drill down in flutter?

I have implemented drill down option in javascript.

Is there any option I can use it as it is in flutter ?

I am using flutter to develop a android and ios application.

Or is there any way I can implement a drill down in flutter application.

For those who don't know what drill down is. The below image would help you.

答:
Your requirement can be achieved using the onPointTapped event. In this event, you can get the point index on which you have tapped. With this information, you can render the chart based on your requirement. After drill down, we have provided an icon with a back arrow, can be used to get back to the actual chart. Find the code below to accomplish this.

```<code>SfCircularChart(
 onPointTapped: (PointTapArgs args) {
      getDrilledChart(args.pointIndex);
 }
//Other configurations,
)
</code>```

The sample for reference can be found below.

Drill down sample

Screenshot before drill down

Screenshot after drill down

Body:
Your requirement can be achieved using the onPointTapped event. In this event, you can get the point index on which you have tapped. With this information, you can render the chart based on your requirement. After drill down, we have provided an icon with a back arrow, can be used to get back to the actual chart. Find the code below to accomplish this.

SfCircularChart(
 onPointTapped: (PointTapArgs args) {
      getDrilledChart(args.pointIndex);
 }
//Other configurations,
)

The sample for reference can be found below.

Drill down sample

Screenshot before drill down

Screenshot after drill down


问:
Refresh multiple div-[unique_ID]'s with jQuery and .load()?
I am working on modifying a plugin to allow users to vote on posts. My page looks something like this (though this is simplified of course):

```<code><div class="vote vote1">
//voting buttons
</div>

<div class="vote vote2">
//voting buttons
</div>

<div class="vote vote3">
//voting buttons
</div>

<div class="vote vote4">
//voting buttons
</div>
</code>```

As you can see, each voting div has a unique class associated with it, vote[id]. My trouble is that after submitting the vote to my vote.php file I need to refresh this unique voting div with the new data. I have been able to do this without trouble when I hardcode a particular voting div's unique id into .load(), but I cannot seem to get this to work dynamically for all voting divs using a single script. Would somebody be able to help me out in refreshing the unique voting div that has been clicked?

```<code><script type="text/javascript">
jQuery(document).ready(function(){
$(".vote a.can-vote").click(
    function() {
        var some = jQuery(this).parent();
        var thepost = jQuery(this).attr("post");
        var theuser = jQuery(this).attr("user");
        var updown = jQuery(this).attr("up-down");
        var is_update = jQuery(this).attr("update");
        var votebox = ".vote"+thepost+" span";

        jQuery.ajax({
            type: "POST",
            url: "<?php bloginfo('template_url'); ?>/vote.php",
            data: {user: theuser, post: thepost, up_down: updown, update: is_update},
            cache: false,
            success: function( data ){
                jQuery(some).load('http://mydomain.com div.vote[ID]');
            }
        });
        return false;
    });
});
</script>
</code>```

I'm sorry if this is a simple question but I've been trying my best to figure it out for two days with no luck; thank you in advance for any help.

答:
Hmm ... well you could find the "ID" class via a regex:

```<code>$(".vote a.can-vote").click(
    function() {
        var some = jQuery(this).parent();
        var keyClass = some.attr('className').replace(/^.*(vote\d+).*$/, '$1');
</code>```

Then your ".load()" can do:

```<code>          jQuery(some).load('http://mydomain.com div.' + keyClass);
</code>```

You might also consider giving the
 elements an actual "id" value too. That'd make stuff a little easier.

Body:
I am working on modifying a plugin to allow users to vote on posts. My page looks something like this (though this is simplified of course):

//voting buttons

//voting buttons

//voting buttons

//voting buttons

As you can see, each voting div has a unique class associated with it, vote[id]. My trouble is that after submitting the vote to my vote.php file I need to refresh this unique voting div with the new data. I have been able to do this without trouble when I hardcode a particular voting div's unique id into .load(), but I cannot seem to get this to work dynamically for all voting divs using a single script. Would somebody be able to help me out in refreshing the unique voting div that has been clicked?

I'm sorry if this is a simple question but I've been trying my best to figure it out for two days with no luck; thank you in advance for any help.

Body:
Hmm ... well you could find the "ID" class via a regex:

$(".vote a.can-vote").click(
    function() {
        var some = jQuery(this).parent();
        var keyClass = some.attr('className').replace(/^.*(vote\d+).*$/, '$1');

Then your ".load()" can do:

          jQuery(some).load('http://mydomain.com div.' + keyClass);

You might also consider giving the <div> elements an actual "id" value too. That'd make stuff a little easier.


问:
Capture Request Headers whenever a static file is requested in Flask App
All,

I'm able to capture request headers whenever a request is made to an endpoint but I was wondering how to capture the request headers whenever a static file is requested.

For example, whenever a request is made to get an image through this endpoint, I'm able to write the headers to a .txt file with a timestamp like below.

https://<host_name>/img

Request Headers example:

```<code>============================
28/05/2020, 14:31:03
Request Headers:
Host: <host_name>
Connection: close
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,kn;q=0.8
X-Request-Id: 00a79a7f-84eb-4fb3-b949-76254a93a001
X-Forwarded-For: 157.49.191.87
X-Forwarded-Proto: https
X-Forwarded-Port: 443
Via: 1.1 vegur
Connect-Time: 0
X-Request-Start: 1590676263802
Total-Route-Time: 0

============================
</code>```

But when someone directly accesses the static objects like this:

```<code>https://<host_name>/static/img/<img_name>.png
</code>```

How to capture the request headers for the static objects when requested directly without any route or a view as the above endpoint?

Currently, I'm capturing the request headers using request.headers in Flask. My function for an img endpoint looks like this:

```<code>@app.route('/img')
def img_func():
    req_headers = request.headers
    dir = "static"
    full_path = os.path.join(dir, "logs")
    filename = full_path +'/request_headers_img.txt'

    if os.path.exists(filename):
        append_write = 'a'  # append if already exists
    else:
        append_write = 'w'  # make a new file if not

    now = datetime.datetime.now()
    date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
    app_logs = open(filename, append_write)
    app_logs.write("============================" + '\n')
    app_logs.write(date_time + '\n')
    app_logs.write("Request Headers: " + '\n' + str(req_headers))
    app_logs.write("============================"+ '\n')
    app_logs.close()

    fn = os.path.join(dir, "img") + '/<file_name>.png'

    return send_file(fn)
</code>```

As I did check some online links, someone mentioned making use of request.path('static') but not sure on how to implement this & capture the request headers.

One more thing which was mentioned there that the static files are being served from the webserver like Nginx or Apache, not from the flask app if static files are requested directly as I mentioned above. If so is there a way to capture these static request headers at the webserver level?

FYI:
The app is built using Flask, Python 3 & deployed to Heroku using CI/CD from Github.

Any help around this or if someone can point to the resources where I can read & implement this will be very useful guys.

Thanks in advance!

答:
Here is my updated code which I was looking for:

```<code>@app.route('/sta/<path:path>')
def getStaticFile(path):
    fn = str(path).split("/")[-1]
    file_type = str(fn).split(".")[-1]

    dir = "static"
    full_path = os.path.join(dir, "logs")
    if file_type == 'png':
        req_headers = request.headers
        filename = full_path + '/request_headers_img.txt'

        if os.path.exists(filename):
            append_write = 'a'  # append if already exists
        else:
            append_write = 'w'  # make a new file if not

        now = datetime.datetime.now()
        date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
        app_logs = open(filename, append_write)
        app_logs.write("============================" + '\n')
        app_logs.write(date_time + '\n')
        app_logs.write("Request Headers: " + '\n' + str(req_headers))
        app_logs.write("============================" + '\n')
        app_logs.close()
    return send_from_directory('static', path)

</code>```

I should make use of <path:path> instead of <var1>/<var2>. Thanks, Akib for looking into it!

Body:
All,

I'm able to capture request headers whenever a request is made to an endpoint but I was wondering how to capture the request headers whenever a static file is requested.

For example, whenever a request is made to get an image through this endpoint, I'm able to write the headers to a .txt file with a timestamp like below.

https://<host_name>/img

Request Headers example:

============================
28/05/2020, 14:31:03
Request Headers:
Host: <host_name>
Connection: close
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,kn;q=0.8
X-Request-Id: 00a79a7f-84eb-4fb3-b949-76254a93a001
X-Forwarded-For: 157.49.191.87
X-Forwarded-Proto: https
X-Forwarded-Port: 443
Via: 1.1 vegur
Connect-Time: 0
X-Request-Start: 1590676263802
Total-Route-Time: 0

============================

But when someone directly accesses the static objects like this:

https://<host_name>/static/img/<img_name>.png

How to capture the request headers for the static objects when requested directly without any route or a view as the above endpoint?

Currently, I'm capturing the request headers using request.headers in Flask. My function for an img endpoint looks like this:

@app.route('/img')
def img_func():
    req_headers = request.headers
    dir = "static"
    full_path = os.path.join(dir, "logs")
    filename = full_path +'/request_headers_img.txt'

    if os.path.exists(filename):
        append_write = 'a'  # append if already exists
    else:
        append_write = 'w'  # make a new file if not

    now = datetime.datetime.now()
    date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
    app_logs = open(filename, append_write)
    app_logs.write("============================" + '\n')
    app_logs.write(date_time + '\n')
    app_logs.write("Request Headers: " + '\n' + str(req_headers))
    app_logs.write("============================"+ '\n')
    app_logs.close()

    fn = os.path.join(dir, "img") + '/<file_name>.png'

    return send_file(fn)

As I did check some online links, someone mentioned making use of request.path('static') but not sure on how to implement this & capture the request headers.

One more thing which was mentioned there that the static files are being served from the webserver like Nginx or Apache, not from the flask app if static files are requested directly as I mentioned above. If so is there a way to capture these static request headers at the webserver level?

FYI:
The app is built using Flask, Python 3 & deployed to Heroku using CI/CD from Github.

Any help around this or if someone can point to the resources where I can read & implement this will be very useful guys.

Thanks in advance!

Body:
Here is my updated code which I was looking for:

@app.route('/sta/<path:path>')
def getStaticFile(path):
    fn = str(path).split("/")[-1]
    file_type = str(fn).split(".")[-1]

    dir = "static"
    full_path = os.path.join(dir, "logs")
    if file_type == 'png':
        req_headers = request.headers
        filename = full_path + '/request_headers_img.txt'

        if os.path.exists(filename):
            append_write = 'a'  # append if already exists
        else:
            append_write = 'w'  # make a new file if not

        now = datetime.datetime.now()
        date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
        app_logs = open(filename, append_write)
        app_logs.write("============================" + '\n')
        app_logs.write(date_time + '\n')
        app_logs.write("Request Headers: " + '\n' + str(req_headers))
        app_logs.write("============================" + '\n')
        app_logs.close()
    return send_from_directory('static', path)

I should make use of <path:path> instead of <var1>/<var2>. Thanks, Akib for looking into it!


问:
Google Cloud shell is killing my process after some time
I am running a java app using the google cloud shell and the app engine.
The application is running continuously and every 5 minutes it writes to Firestore Database a document using the Admin SDK with the proper authentication.
Yesterday it was killed after 2 hours and 20 minutes.
The 3 commands I am using to run it are the following.

```<code>mvn clean package
mvn package appengine:deploy -Dapp.deploy.projectId=myProjectIdHere
nohup mvn exec:exec -Dfirestore.project.id="myProjectIdHere" &> program.out &
</code>```

Today the process was killed after 10 minutes.
Any ideas on how to fix that?

答:
Cloud shell is a ephemeral VM that is killed after few hours, this is designed for administrative tasks not for deployment.

If you need to run some process you could use an always free Compute engine VM (F1-micro instance), this F1 instance offers a better performance than the cloud shell.

Body:
I am running a java app using the google cloud shell and the app engine.
The application is running continuously and every 5 minutes it writes to Firestore Database a document using the Admin SDK with the proper authentication.
Yesterday it was killed after 2 hours and 20 minutes.
The 3 commands I am using to run it are the following.

mvn clean package
mvn package appengine:deploy -Dapp.deploy.projectId=myProjectIdHere
nohup mvn exec:exec -Dfirestore.project.id="myProjectIdHere" &> program.out &

Today the process was killed after 10 minutes.
Any ideas on how to fix that?


问:
How to display average in an SSRS table?
I am using SSRS 2008 and one of my rows is supposed to return the average of a certain field.  But currently it just displays all of the rows instead of one row with the average.  How do I implement this?

Currently the stored proc for this RDL file returns all of the records.  So I tried using the "Avg(<field value>)" function in SSRS for the SSRS expression.  And then I grouped this row on the <field value>.  I removed filtering so it should average all rows now.

I'm guessing the cause is the grouping.  Any ideas though?

答: I think you need a totals row. Right-click on the group and then Add Totals Then you should be able to put your Avg(<field value>) in that cell.


问:
When a property value is changed in a class via @Published, some of the observedObjects wont get updated?
These are all the codes.

the SurveyQuestion class

```<code>class SurveyQuestion: ObservableObject {
    @Published var text: String

    init() {
        print("Initialising now ...")
        self.text = "HELLO"
        changeText()
    }

    func changeText() {
        print("Changing Text Now from \(text).. ")

        if self.text == "HELLO"{
            self.text = "BYE"
        }
        else{
            self.text = "HELLO"
        }

        print("to \(self.text) \n")

    }
}
</code>```

SubView.swift

```<code>struct SubView: View {

    @ObservedObject var someOtherClass = SurveyQuestion()

    var body: some View {
        Text("Text now is \(someOtherClass.text)")

    }
}
</code>```

ContentView.swift

```<code>struct ContentView: View {

    @ObservedObject var someClass = SurveyQuestion()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.someClass.changeText()
            }) {
                Text("Change Text ")
            }

            Text("Text now is \(someClass.text)")

            SubView()

        }
    }
}
</code>```

Whenever I click 'changeText' button, it changes the text in  Text("Text now is (someClass.text)") but not Subview(). They should all be updated with the same text change.
Any idea what went wrong here?

答:
To make it work you should use same instance of ObservableObject, like below

```<code>struct SubView: View {
    @ObservedObject var someOtherClass: SurveyQuestion // to be injected

    var body: some View {
        Text("Text now is \(someOtherClass.text)")

    }
}

struct ContentView: View {
    @ObservedObject var someClass = SurveyQuestion() // created

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.someClass.changeText()
            }) {
                Text("Change Text ")
            }

            Text("Text now is \(someClass.text)")

            SubView(someOtherClass: someClass) // << injected

        }
    }
}
</code>```

Body:
These are all the codes.

the SurveyQuestion class

class SurveyQuestion: ObservableObject {
    @Published var text: String

    init() {
        print("Initialising now ...")
        self.text = "HELLO"
        changeText()
    }

    func changeText() {
        print("Changing Text Now from \(text).. ")

        if self.text == "HELLO"{
            self.text = "BYE"
        }
        else{
            self.text = "HELLO"
        }

        print("to \(self.text) \n")

    }
}

SubView.swift

struct SubView: View {

    @ObservedObject var someOtherClass = SurveyQuestion()

    var body: some View {
        Text("Text now is \(someOtherClass.text)")

    }
}

ContentView.swift

struct ContentView: View {

    @ObservedObject var someClass = SurveyQuestion()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.someClass.changeText()
            }) {
                Text("Change Text ")
            }

            Text("Text now is \(someClass.text)")

            SubView()

        }
    }
}

Whenever I click 'changeText' button, it changes the text in  Text("Text now is (someClass.text)") but not Subview(). They should all be updated with the same text change.
Any idea what went wrong here?

Body:
To make it work you should use same instance of ObservableObject, like below

struct SubView: View {
    @ObservedObject var someOtherClass: SurveyQuestion // to be injected

    var body: some View {
        Text("Text now is \(someOtherClass.text)")

    }
}

struct ContentView: View {
    @ObservedObject var someClass = SurveyQuestion() // created

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.someClass.changeText()
            }) {
                Text("Change Text ")
            }

            Text("Text now is \(someClass.text)")

            SubView(someOtherClass: someClass) // << injected

        }
    }
}


问:
Kernel sys_call_table address does not match address specified in system.map
I am trying to brush up on C so I have been playing around with the linux kernel's system call table (on 3.13.0-32-generic). I found a resource online that searches for the system call table with the following function which I load into the kernel in an LKM:

static uint64_t **aquire_sys_call_table(void)
{
    uint64_t offset = PAGE_OFFSET;
    uint64_t **sct;

    while (offset < ULLONG_MAX) {
        sct = (uint64_t **)offset;

        if (sct[__NR_close] == (uint64_t *) sys_close) {
            printk("\nsys_call_table found at address: 0x%p\n", sys_call_table);
            return sct;
        }

        offset += sizeof(void *);
    }

    return NULL;
}
```

<p>The function works. I am able to use the address it returns to manipulate the system call table. What I don't understand is why the address returned by this function doesn't match the address in /boot/System.map-(KERNEL)</p>

<p>Here is what the function prints:</p>

```sys_call_table found at address: 0xffff880001801400
```

<p>Here is what I get when I search system.map</p>

```$ sudo cat /boot/System.map-3.13.0-32-generic | grep sys_call_table
  ffffffff81801400 R sys_call_table
  ffffffff81809cc0 R ia32_sys_call_table
```

Why don't the two addresses match? Its my understanding that the module runs in the kernel's address space, so the address of the system call table should be the same.

答:
Only root can show the addresses in the /proc/kallsyms file! It is rarely disabled but you can enable it if it's disabled. But the addresses in the System.map and kallsyms file for the same sys_call are different.

If a person is using a kernel built by himself, then System.map is preferable but if you are using a pre-built kernel (like we mostly do), then kallsyms is the right place for you!

Body:
I am trying to brush up on C so I have been playing around with the linux kernel's system call table (on 3.13.0-32-generic). I found a resource online that searches for the system call table with the following function which I load into the kernel in an LKM:

static uint64_t **aquire_sys_call_table(void)
{
    uint64_t offset = PAGE_OFFSET;
    uint64_t **sct;

    while (offset < ULLONG_MAX) {
        sct = (uint64_t **)offset;

        if (sct[__NR_close] == (uint64_t *) sys_close) {
            printk("\nsys_call_table found at address: 0x%p\n", sys_call_table);
            return sct;
        }

        offset += sizeof(void *);
    }

    return NULL;
}

The function works. I am able to use the address it returns to manipulate the system call table. What I don't understand is why the address returned by this function doesn't match the address in /boot/System.map-(KERNEL)

Here is what the function prints:

sys_call_table found at address: 0xffff880001801400

Here is what I get when I search system.map

$ sudo cat /boot/System.map-3.13.0-32-generic | grep sys_call_table
  ffffffff81801400 R sys_call_table
  ffffffff81809cc0 R ia32_sys_call_table

Why don't the two addresses match? Its my understanding that the module runs in the kernel's address space, so the address of the system call table should be the same.


问:
How to select multiple items in FlatList, highlight them and keep them saved in React Native
I want to select multiple items from the FlatList. Whenever, I click them, they should be highlighted and they should be saved in some state variable

I am using 'react-native-android-installed-apps' to get a list of all the installed apps in a FLatList

This is what I have done up till now:

```<code>import React, {Component} from 'react';
import {View, Text, Image, FlatList, Dimensions, TouchableOpacity} from 'react-native';
import RNAndroidInstalledApps from 'react-native-android-installed-apps';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            data: []
        };
    }

    componentDidMount() {
        this.check();
    }

    check = () => {
        let combine = [];
        RNAndroidInstalledApps.getApps()
            .then(apps => {
                if(apps.length > 0) {
                    for(let i = 0; i< apps.length ; i++) {
                        thisApp = apps[i];
                        const obj = {'appName': thisApp.appName, 'icon': thisApp.icon};
                        combine.push(obj);
                    }
                }
                this.setState({
                    data: combine
                });
                // console.log(this.state.data);
            });
    };

    renderSeperator = () => {
        return(
            <View
                style={{
                    height: 1,
                    backgroundColor: '#CED0CE',
                }}
            />
        );
    };

    render() {
        return(
        <FlatList
                data={this.state.data}
                renderItem={({ item }) =>(
                    <TouchableOpacity
                        style={{flexDirection:'row', padding: 5 }}
                    >
                        <Image
                            style={{width: 51, height: 51, resizeMode: 'contain', flex: 1 }}
                            source={{ uri: `data:image;base64,${item.icon}` }}
                        />
                        <Text style={{alignSelf: 'center', marginStart: 10, flex: 5 }}>{item.appName}</Text>
                    </TouchableOpacity>
                )}
                keyExtractor={(item) => item.appName}
                ItemSeparatorComponent={this.renderSeperator}
        />
        );
    }
}

export default App;
</code>```

I expect to highlight each item when it is selected, and save it's data in some state variable

答:
For that, you can use the library react-native-sectioned-multi-select

Documentation in https://github.com/renrizzolo/react-native-sectioned-multi-select

Body:
I want to select multiple items from the FlatList. Whenever, I click them, they should be highlighted and they should be saved in some state variable

I am using 'react-native-android-installed-apps' to get a list of all the installed apps in a FLatList

This is what I have done up till now:

import React, {Component} from 'react';
import {View, Text, Image, FlatList, Dimensions, TouchableOpacity} from 'react-native';
import RNAndroidInstalledApps from 'react-native-android-installed-apps';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            data: []
        };
    }

    componentDidMount() {
        this.check();
    }

    check = () => {
        let combine = [];
        RNAndroidInstalledApps.getApps()
            .then(apps => {
                if(apps.length > 0) {
                    for(let i = 0; i< apps.length ; i++) {
                        thisApp = apps[i];
                        const obj = {'appName': thisApp.appName, 'icon': thisApp.icon};
                        combine.push(obj);
                    }
                }
                this.setState({
                    data: combine
                });
                // console.log(this.state.data);
            });
    };

    renderSeperator = () => {
        return(
            <View
                style={{
                    height: 1,
                    backgroundColor: '#CED0CE',
                }}
            />
        );
    };

    render() {
        return(
        <FlatList
                data={this.state.data}
                renderItem={({ item }) =>(
                    <TouchableOpacity
                        style={{flexDirection:'row', padding: 5 }}
                    >
                        <Image
                            style={{width: 51, height: 51, resizeMode: 'contain', flex: 1 }}
                            source={{ uri: `data:image;base64,${item.icon}` }}
                        />
                        <Text style={{alignSelf: 'center', marginStart: 10, flex: 5 }}>{item.appName}</Text>
                    </TouchableOpacity>
                )}
                keyExtractor={(item) => item.appName}
                ItemSeparatorComponent={this.renderSeperator}
        />
        );
    }
}

export default App;

I expect to highlight each item when it is selected, and save it's data in some state variable


问:
Padding missing on one side of scrollable div
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="moh">
    <div></div>
</div></code>```

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

答:
The reason for this can tell. It's hard to explain, but I'll try. Your" moh " div width value is 100px," moh " in the div width value is 500px. The order of items on Pages is normally left to right. If you do not apply overflow, you see the overflowing sections :

#moh {
  background: red;
  width: 100px;
  padding: 5px; // this padding should be on all 4 sides
}

#moh div {
  width: 500px;
  height: 50px;
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="moh">
  <div></div>
</div></code>```

As you can see, there's an overflow from left to right. when you give overflow, The Overflow will be hidden automatically. So where's the overflow ? (left ? right ? ) That's why it will try to hide everything from the overflow, that is, the part that goes out when it doesn't fit. The part he's trying to hide is in the padding, so that part doesn't show up.

I'm sorry if I said anything that would be misunderstood. Maybe I helped you understand a little bit.

Body:
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

Body:
The reason for this can tell. It's hard to explain, but I'll try. Your" moh " div width value is 100px," moh " in the div width value is 500px. The order of items on Pages is normally left to right. If you do not apply overflow, you see the overflowing sections :

#moh {
  background: red;
  width: 100px;
  padding: 5px; // this padding should be on all 4 sides
}

#moh div {
  width: 500px;
  height: 50px;
  background: green;
}

<div id="moh">
  <div></div>
</div>

As you can see, there's an overflow from left to right. when you give overflow, The Overflow will be hidden automatically. So where's the overflow ? (left ? right ? ) That's why it will try to hide everything from the overflow, that is, the part that goes out when it doesn't fit. The part he's trying to hide is in the padding, so that part doesn't show up.

I'm sorry if I said anything that would be misunderstood. Maybe I helped you understand a little bit.


问:
AWS Personalize: Failure reason Dataset has fewer than 1000 interactions
I am trying to create an AWS Personalize solution for the first time and I am able to import all the needed data sets but then it fails when I want to start.

And when I enter the solution overview

In my first attempts to import the interactions dataset it failed due to <1000 reason. Then I imported one with +2000 and worked. Once all the imports worked then the Start option was enabled, and this error happens.
Thanks!

答: The reason is that the 1000 interactions must be distinct, got it after contacting AWS support.</p>


问:
How to merge close points in 2d list python
I'm having troubles to merge close points for Voronoi diagram, here is the case:

I load a map from image

The map is converted to an array containing only points meaning obstacles

Voronoi diagram is computed from this array

Then is the problem that I have vertices inside "obstacles" as shown in image

My idea is to convert obstacles containing many points to one point.

List of points look similar to this:

```<code>map = [[11, 29], [11, 30], [11, 31], [12, 28], [12, 29], [12, 30]]
</code>```

I want to take a group of points and merge these points into one.

I've found this Fast fuse of close points in a numpy-2d (vectorized)

I Don't have any idea how to fuse these points taking into account obstacles which are not "point-shaped"

答:
I would recommend you not to map as variable name, as there is a function with the same name. Your issue in genreal is to find clusters which is similiar to the issue in your link, but based on the data k-Dtree might not be great. I would recommend an other clustering algorithm from scikit:

KMeans, if you know the amount of obstacles

DBSCAN, if you know the maximal size of the obstacles

from sklearn.cluster import KMeans, DBSCAN
import numpy as np

```<code>obstacle_list = [[0, 0], [0, 1], [1, 0], [1, 1], [3, 3], [4, 3],[3,4]]
obstacle_array = np.array(obstacle_list) # for easier handling

#if you know the number of obstacles
number_of_obstacles=2
cluster_values = KMeans(n_clusters=number_of_obstacles).fit_predict(obstacle_array)
print(cluster_values) # those are the cluster MeanShift found

#if you know the maximal size of an obstacle
max_size_of_obstacle = 3
db_values = DBSCAN(eps=max_size_of_obstacle).fit_predict(obstacle_array)
print(cluster_values)# those are the cluster DBSCAN found
</code>```

If you want it to be represented only by 1 point probably somewhere in the center) you can loop over the cluster_values to calcualte it. I would take mean of x and y values, but your data seems to be only integers so you might want to take something else.

Body:
I'm having troubles to merge close points for Voronoi diagram, here is the case:

I load a map from image

The map is converted to an array containing only points meaning obstacles

Voronoi diagram is computed from this array

Then is the problem that I have vertices inside "obstacles" as shown in image

My idea is to convert obstacles containing many points to one point.

List of points look similar to this:

map = [[11, 29], [11, 30], [11, 31], [12, 28], [12, 29], [12, 30]]

I want to take a group of points and merge these points into one.

I've found this Fast fuse of close points in a numpy-2d (vectorized)

I Don't have any idea how to fuse these points taking into account obstacles which are not "point-shaped"

Body:
I would recommend you not to map as variable name, as there is a function with the same name. Your issue in genreal is to find clusters which is similiar to the issue in your link, but based on the data k-Dtree might not be great. I would recommend an other clustering algorithm from scikit:

KMeans, if you know the amount of obstacles

DBSCAN, if you know the maximal size of the obstacles

from sklearn.cluster import KMeans, DBSCAN
import numpy as np

obstacle_list = [[0, 0], [0, 1], [1, 0], [1, 1], [3, 3], [4, 3],[3,4]]
obstacle_array = np.array(obstacle_list) # for easier handling

#if you know the number of obstacles
number_of_obstacles=2
cluster_values = KMeans(n_clusters=number_of_obstacles).fit_predict(obstacle_array)
print(cluster_values) # those are the cluster MeanShift found

#if you know the maximal size of an obstacle
max_size_of_obstacle = 3
db_values = DBSCAN(eps=max_size_of_obstacle).fit_predict(obstacle_array)
print(cluster_values)# those are the cluster DBSCAN found

If you want it to be represented only by 1 point probably somewhere in the center) you can loop over the cluster_values to calcualte it. I would take mean of x and y values, but your data seems to be only integers so you might want to take something else.


问:
How to change Theme of "MaterialDatePicker" in Android?
I've used MaterialDatePicker for the purpose of selecting a single date & also I had achieved that task but I cannot change the theme of the header & button.

```<code>        MaterialDatePicker.Builder builder;
        MaterialDatePicker materialDatePicker;

        long today = MaterialDatePicker.todayInUtcMilliseconds();
        CalendarConstraints.Builder con = new CalendarConstraints.Builder();
        con.setValidator(DateValidatorPointForward.now());
        builder.setSelection(today);
        builder.setCalendarConstraints(con.build());

        materialDatePicker = builder.build();

        findViewById(R.id.startCalender).setOnClickListener(v ->
                materialDatePicker.show(getSupportFragmentManager(), builder.toString())
        );

        materialDatePicker.addOnPositiveButtonClickListener(selection ->
        Toast.makeText(this, materialDatePicker.getHeaderText(),
        Toast.LENGTH_SHORT).show());
</code>```

答:
You have different options.

You can use:

```<code>builder.setTheme(R.style.MaterialCalendarTheme);
</code>```

with:

```<code>  <style name="MaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <!-- just override the colors used in the default style -->
    <item name="colorOnPrimary">@color/primaryDarkColor</item>
    <item name="colorPrimary">@color/primaryLightColor</item>
  </style>
</code>```

or you can use something like:

```<code>  <style name="MaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">

    <!-- Header panel -->
    <item name="materialCalendarHeaderLayout">@style/MaterialCalendar.HeaderLayout1</item>
    <!-- Buttons -->
    <item name="buttonBarPositiveButtonStyle">@style/TextButton.Dialog1</item>
    <item name="buttonBarNegativeButtonStyle">@style/TextButton.Dialog1</item>
  </style>
  <style name="MaterialCalendar.HeaderLayout1" parent="Widget.MaterialComponents.MaterialCalendar.HeaderLayout">
    <!--<item name="android:background">?attr/colorPrimary</item>-->
    <item name="android:background">@color/primaryLightColor</item>
  </style>
  <style name="TextButton.Dialog1" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">@color/white</item>
    <item name="backgroundTint">@color/primaryDarkColor</item>
  </style>
</code>```

Body:
I've used MaterialDatePicker for the purpose of selecting a single date & also I had achieved that task but I cannot change the theme of the header & button.

        MaterialDatePicker.Builder builder;
        MaterialDatePicker materialDatePicker;

        long today = MaterialDatePicker.todayInUtcMilliseconds();
        CalendarConstraints.Builder con = new CalendarConstraints.Builder();
        con.setValidator(DateValidatorPointForward.now());
        builder.setSelection(today);
        builder.setCalendarConstraints(con.build());

        materialDatePicker = builder.build();

        findViewById(R.id.startCalender).setOnClickListener(v ->
                materialDatePicker.show(getSupportFragmentManager(), builder.toString())
        );

        materialDatePicker.addOnPositiveButtonClickListener(selection ->
        Toast.makeText(this, materialDatePicker.getHeaderText(),
        Toast.LENGTH_SHORT).show());

Body:
You have different options.

You can use:

builder.setTheme(R.style.MaterialCalendarTheme);

with:

  <style name="MaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">
    <!-- just override the colors used in the default style -->
    <item name="colorOnPrimary">@color/primaryDarkColor</item>
    <item name="colorPrimary">@color/primaryLightColor</item>
  </style>

or you can use something like:

  <style name="MaterialCalendarTheme" parent="ThemeOverlay.MaterialComponents.MaterialCalendar">

    <!-- Header panel -->
    <item name="materialCalendarHeaderLayout">@style/MaterialCalendar.HeaderLayout1</item>
    <!-- Buttons -->
    <item name="buttonBarPositiveButtonStyle">@style/TextButton.Dialog1</item>
    <item name="buttonBarNegativeButtonStyle">@style/TextButton.Dialog1</item>
  </style>
  <style name="MaterialCalendar.HeaderLayout1" parent="Widget.MaterialComponents.MaterialCalendar.HeaderLayout">
    <!--<item name="android:background">?attr/colorPrimary</item>-->
    <item name="android:background">@color/primaryLightColor</item>
  </style>
  <style name="TextButton.Dialog1" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">@color/white</item>
    <item name="backgroundTint">@color/primaryDarkColor</item>
  </style>


问:
how to pass AWS lambda 1 output as lambda 2's input using BOTO 3
I have a AWS lambda function which have some info and another 6 lambda functions which query cloudwatch logs using BOTO 3.

How can i call lambda 2 with lambda 1 input.

I'm calling 6 other lambdas because execution time taking more than 48 mins to query logs. I've divided time duration into 6 parts and calling each lambda with some start and end times, As lambda execution time is 15 mins max

lambda 1 code

```<code>import json
import boto3
import time

client = boto3.client('lambda')

payload3=b"""{ "query":"fields @timestamp, @message | sort @timestamp desc", "log_group":"abc.log", "sTime":1585630748456, "eTime":1585713248457}"""

def lambda_handler(event,context):
    response = client.invoke(
        FunctionName='testamurin',
        InvocationType='Event',
        Payload=payload3
    )

   return {
        'statusCode': 200
    }
</code>```

lambda 2

```<code>import json
import boto3
import time

client = boto3.client('logs')

def lambda_handler(event,context):

    response = client.start_query(
        logGroupName = log_group,
        startTime=sTime,
        endTime=eTime,
        queryString = query
    )

    query_id = response['queryId']

    response = None

    while response == None or response['status'] == 'Running':
        print('Waiting for query to complete ...')
        time.sleep(1)
        response = client.get_query_results(
            queryId=query_id)

    return {
        'body': response
    }
</code>```

When i'm running lambda1 its getting successful. But, in lambda 2 i'm getting error

```<code>[ERROR] NameError: name 'log_group' is not defined
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 16, in lambda_handler
    logGroupName = log_group,
</code>```

答:
I assume the function 1 is calling function 2

Function 1 input contains first_name and last_name

Function 1

import json
from boto3 import client as boto3_client

lambda_client = boto3_client('lambda')

def my_handler(event, context):
    response = lambda_client.invoke(
        FunctionName="FUNCTION-2-NAME-FOUND-IN-LAMBDA-CONSOLE",
        InvocationType='RequestResponse',
        Payload=json.dumps(event)
    )
    # do something with the response
    # ...

```

<h1>Function 2</h1>

<pre class="lang-py prettyprint-override"><code>def my_handler(event, context):
    message = 'Hello {} {}!'.format(event['first_name'],
                                    event['last_name'])
    return {
        'message' : message
    }
</code>```

Body:
I have a AWS lambda function which have some info and another 6 lambda functions which query cloudwatch logs using BOTO 3.

How can i call lambda 2 with lambda 1 input.

I'm calling 6 other lambdas because execution time taking more than 48 mins to query logs. I've divided time duration into 6 parts and calling each lambda with some start and end times, As lambda execution time is 15 mins max

lambda 1 code

import json
import boto3
import time

client = boto3.client('lambda')

payload3=b"""{ "query":"fields @timestamp, @message | sort @timestamp desc", "log_group":"abc.log", "sTime":1585630748456, "eTime":1585713248457}"""

def lambda_handler(event,context):
    response = client.invoke(
        FunctionName='testamurin',
        InvocationType='Event',
        Payload=payload3
    )

   return {
        'statusCode': 200
    }

lambda 2

import json
import boto3
import time

client = boto3.client('logs')

def lambda_handler(event,context):

    response = client.start_query(
        logGroupName = log_group,
        startTime=sTime,
        endTime=eTime,
        queryString = query
    )

    query_id = response['queryId']

    response = None

    while response == None or response['status'] == 'Running':
        print('Waiting for query to complete ...')
        time.sleep(1)
        response = client.get_query_results(
            queryId=query_id)

    return {
        'body': response
    }

When i'm running lambda1 its getting successful. But, in lambda 2 i'm getting error

[ERROR] NameError: name 'log_group' is not defined
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 16, in lambda_handler
    logGroupName = log_group,

Body:
I assume the function 1 is calling function 2

Function 1 input contains first_name and last_name

Function 1

import json
from boto3 import client as boto3_client

lambda_client = boto3_client('lambda')

def my_handler(event, context):
    response = lambda_client.invoke(
        FunctionName="FUNCTION-2-NAME-FOUND-IN-LAMBDA-CONSOLE",
        InvocationType='RequestResponse',
        Payload=json.dumps(event)
    )
    # do something with the response
    # ...

Function 2

def my_handler(event, context):
    message = 'Hello {} {}!'.format(event['first_name'],
                                    event['last_name'])
    return {
        'message' : message
    }


问:
How to check a node contains empty string or space or null in xpath?
I want to check using xpath an node in the xml contains empty string/spaces. What is the xpath expression i need to use?

eg:

```<code> <p:insert_acc_data_file xmlns:p="http://ws.wso2.org/dataservice">
<p:Id>123</p:Id>
<p:Name></p:pName>
</p:insert_acc_data_file>
</code>```

How to check the Name node is empty or containing space values?

答:
For both mentioned type.

```<code><Employee/>
<Employee></Employee>
</code>```

Below code will work

```<code>string(your_node_xpath) != ''
</code>```

Body:
I want to check using xpath an node in the xml contains empty string/spaces. What is the xpath expression i need to use?

eg:

123

How to check the Name node is empty or containing space values?

Body:
For both mentioned type.

<Employee/>
<Employee></Employee>

Below code will work

string(your_node_xpath) != ''


问:
specify ssl ca and key in app config c# mysql connection string
How can I specify the sslca file to be used by entity framework mysql in the app.config connection string.

My connection string currently looks like this;

```<code><connectionStrings>
<add name="Model" connectionString="server=localhost;user id=username;password=*****;persistsecurityinfo=True;database=database_name;CharSet=utf8;SslMode=VerifyCA;CertificateFile=client-bundle.pfx;CertificatePassword=******;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
</code>```

I get a keyword not recognised error when i use SslCa=ca.pem in the connection string.

So how do I specify the ca file to be used?

答:
Mixing PEM and PFX files is not supported by Oracle's MySQL Connector/NET. Specifically, as per bug 95526, SslCa is treated as an alias of CertificateFile so you can't use both at the same time.

I would normally recommend switching to MySqlConnector, which does support using SslCa and CertificateFile simultaneously, but it doesn't support EF6 (only EF Core).

Instead, you'll have to drop the CertificateFile option, convert your certificates to PEM format, and use SslKey and SslCert instead (along with SslCa). I think this will also prevent you from using the CertificatePassword option (as that's only for PFX files).

Body:
How can I specify the sslca file to be used by entity framework mysql in the app.config connection string.

My connection string currently looks like this;

<connectionStrings>
<add name="Model" connectionString="server=localhost;user id=username;password=*****;persistsecurityinfo=True;database=database_name;CharSet=utf8;SslMode=VerifyCA;CertificateFile=client-bundle.pfx;CertificatePassword=******;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

I get a keyword not recognised error when i use SslCa=ca.pem in the connection string.

So how do I specify the ca file to be used?


问:
Create Multiple Dataframes using Loop & function
I have a df over 1M rows similar to this

```<code>ID  Date    Amount
x   May 1   10
y   May 2   20
z   May 4   30
x   May 1   40
y   May 1   50
z   May 2   60
x   May 1   70
y   May 5   80
a   May 6   90
b   May 8   100
x   May 10  110
</code>```

I have to sort the data based on the date and then create new dataframes depending on the times the value is present in Amount column. So if x has made purchase 3 time then I need it in 3 different dataframes. first_purchase dataframe would have every ID that has purchased even once irrespective of date or amount.
If an ID purchases 3 times, I need that ID to be in first purchase then second and then 3rd  with Date and Amount.

Doing it manually is easy with:-

```<code>df = df.sort_values('Date')
first_purchase = df.drop_duplicates('ID')
after_1stpurchase = df[~df.index.isin(first_purchase.index)]
</code>```

second data frame would be created with:-

```<code>after_1stpurchase = after_1stpurchase.sort_values('Date')
second_purchase = after_1stpurchase.drop_duplicates('ID')
after_2ndpurchase = after_1stpurchase[~after_1stpurchase.index.isin(second_purchase.index)]
</code>```

How do I create the loop to provide me with each dataframes?

答:
IIUC, I was able to achieve what you wanted.

```<code>import pandas as pd
import numpy as np

# source data for the dataframe
data = {
"ID":["x","y","z","x","y","z","x","y","a","b","x"],
"Date":["May 01","May 02","May 04","May 01","May 01","May 02","May 01","May 05","May 06","May 08","May 10"],
"Amount":[10,20,30,40,50,60,70,80,90,100,110]
}

df = pd.DataFrame(data)

# convert the Date column to datetime and still maintain the format like "May 01"
df['Date'] = pd.to_datetime(df['Date'], format='%b %d').dt.strftime('%b %d')

# sort the values on ID and Date
df.sort_values(by=['ID', 'Date'], inplace=True)
df.reset_index(inplace=True, drop=True)

print(df)
</code>```

Original Dataframe:

```<code>    Amount    Date ID
0       90  May 06  a
1      100  May 08  b
2       10  May 01  x
3       40  May 01  x
4       70  May 01  x
5      110  May 10  x
6       50  May 01  y
7       20  May 02  y
8       80  May 05  y
9       60  May 02  z
10      30  May 04  z
</code>```

.

```<code># create a list of unique ids
list_id = sorted(list(set(df['ID'])))

# create an empty list that would contain dataframes
df_list = []

# count of iterations that must be seperated out
# for example if we want to record 3 entries for
# each id, the iter would be 3. This will create
# three new dataframes that will hold transactions
# respectively.
iter = 3
for i in range(iter):
    df_list.append(pd.DataFrame())

for val in list_id:
    tmp_df = df.loc[df['ID'] == val].reset_index(drop=True)

    # consider only the top iter(=3) values to be distributed
    counter = np.minimum(tmp_df.shape[0], iter)
    for idx in range(counter):
        df_list[idx] = df_list[idx].append(tmp_df.loc[tmp_df.index == idx])

for df in df_list:
    df.reset_index(drop=True, inplace=True)
    print(df)
</code>```

Transaction #1:

```<code>   Amount    Date ID
0      90  May 06  a
1     100  May 08  b
2      10  May 01  x
3      50  May 01  y
4      60  May 02  z
</code>```

Transaction #2:

```<code>   Amount    Date ID
0      40  May 01  x
1      20  May 02  y
2      30  May 04  z
</code>```

Transaction #3:

```<code>   Amount    Date ID
0      70  May 01  x
1      80  May 05  y
</code>```

Note that in your data, there are four transactions for 'x'. If lets say you wanted to track the 4th iterative transaction as well. All you need to do is change the value if 'iter' to 4 and you will get the fourth dataframe as well with the following value:

```<code>   Amount    Date ID
0     110  May 10  x
</code>```

Body:
I have a df over 1M rows similar to this

ID  Date    Amount
x   May 1   10
y   May 2   20
z   May 4   30
x   May 1   40
y   May 1   50
z   May 2   60
x   May 1   70
y   May 5   80
a   May 6   90
b   May 8   100
x   May 10  110

I have to sort the data based on the date and then create new dataframes depending on the times the value is present in Amount column. So if x has made purchase 3 time then I need it in 3 different dataframes. first_purchase dataframe would have every ID that has purchased even once irrespective of date or amount.
If an ID purchases 3 times, I need that ID to be in first purchase then second and then 3rd  with Date and Amount.

Doing it manually is easy with:-

df = df.sort_values('Date')
first_purchase = df.drop_duplicates('ID')
after_1stpurchase = df[~df.index.isin(first_purchase.index)]

second data frame would be created with:-

after_1stpurchase = after_1stpurchase.sort_values('Date')
second_purchase = after_1stpurchase.drop_duplicates('ID')
after_2ndpurchase = after_1stpurchase[~after_1stpurchase.index.isin(second_purchase.index)]

How do I create the loop to provide me with each dataframes?

Body:
IIUC, I was able to achieve what you wanted.

import pandas as pd
import numpy as np

# source data for the dataframe
data = {
"ID":["x","y","z","x","y","z","x","y","a","b","x"],
"Date":["May 01","May 02","May 04","May 01","May 01","May 02","May 01","May 05","May 06","May 08","May 10"],
"Amount":[10,20,30,40,50,60,70,80,90,100,110]
}

df = pd.DataFrame(data)

# convert the Date column to datetime and still maintain the format like "May 01"
df['Date'] = pd.to_datetime(df['Date'], format='%b %d').dt.strftime('%b %d')

# sort the values on ID and Date
df.sort_values(by=['ID', 'Date'], inplace=True)
df.reset_index(inplace=True, drop=True)

print(df)

Original Dataframe:

    Amount    Date ID
0       90  May 06  a
1      100  May 08  b
2       10  May 01  x
3       40  May 01  x
4       70  May 01  x
5      110  May 10  x
6       50  May 01  y
7       20  May 02  y
8       80  May 05  y
9       60  May 02  z
10      30  May 04  z

.

# create a list of unique ids
list_id = sorted(list(set(df['ID'])))

# create an empty list that would contain dataframes
df_list = []

# count of iterations that must be seperated out
# for example if we want to record 3 entries for
# each id, the iter would be 3. This will create
# three new dataframes that will hold transactions
# respectively.
iter = 3
for i in range(iter):
    df_list.append(pd.DataFrame())

for val in list_id:
    tmp_df = df.loc[df['ID'] == val].reset_index(drop=True)

    # consider only the top iter(=3) values to be distributed
    counter = np.minimum(tmp_df.shape[0], iter)
    for idx in range(counter):
        df_list[idx] = df_list[idx].append(tmp_df.loc[tmp_df.index == idx])

for df in df_list:
    df.reset_index(drop=True, inplace=True)
    print(df)

Transaction #1:

   Amount    Date ID
0      90  May 06  a
1     100  May 08  b
2      10  May 01  x
3      50  May 01  y
4      60  May 02  z

Transaction #2:

   Amount    Date ID
0      40  May 01  x
1      20  May 02  y
2      30  May 04  z

Transaction #3:

   Amount    Date ID
0      70  May 01  x
1      80  May 05  y

Note that in your data, there are four transactions for 'x'. If lets say you wanted to track the 4th iterative transaction as well. All you need to do is change the value if 'iter' to 4 and you will get the fourth dataframe as well with the following value:

   Amount    Date ID
0     110  May 10  x


问:
Java Script Date Function
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.</p>

```<code>function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}
</code>```

答:
You can shorten it further by using an arrow function as seen below:

const abc = () => new Date().getHours()

console.log(abc());```

Title: Java Script Date Function

Body:
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.

function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}


问:
How do I rerender my view in swiftUI after a user logged in with Google on Firebase?
I'm fairly new to iOS Programming and swiftUI in particular.
I have the issue that I try to integrate firebase auth in my App in order to manage users.
Now the login, and log out basically works, the issue is, that after logging in, my view (which conditionally renders eighter the Google sign-in button or a list of content does not rerender so I still see the sign-in button even though I'm signed in).

I have set an observable Object to hold my auth status but unfortunately, it does not reload the current user automatically. So I set up a function to reload it manually which I would like to trigger when logging in. This works for the logout button but the logging in finishes in the AppDelegate, where for some reason I can't access the reloadUser() function.

I'm sure there is a better way to do this and would appreciate any help!

The Environment:

```<code>final class UserData: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var qrTags = qrTagData
    @Published var user: User? = Auth.auth().currentUser

    func reloadUser() -> Void {
        self.user = Auth.auth().currentUser
    }
}
</code>```

The View I'd like to render:

```<code>struct MyQuaggsList: View {
        @EnvironmentObject private var userData: UserData

        var body: some View {
            Group {
                if getLogInState() != nil {
                    VStack {
                        NavigationView {
                            List {
                                Toggle(isOn: $userData.showFavoritesOnly) {
                                    Text("Show Favorites Only")
                                }

                                ForEach(userData.qrTags) { qrTag in
                                    if !self.userData.showFavoritesOnly || qrTag.isFavorite {
                                        NavigationLink(
                                            destination: QuagDetail(qrTag: qrTag)
                                                .environmentObject(self.userData)
                                        ) {
                                            QuaggRow(qrTag: qrTag)
                                        }
                                    }
                                }
                            }
                            .navigationBarTitle(Text("My Quaggs"))
                        }
                        SignOutButton()
                    }
                } else {
                    SignInView()
                }
            }.onAppear(perform: {self.userData.reloadUser()})
        }

        func getLogInState() -> User? {
            return Auth.auth().currentUser
        }
    }
</code>```

Also, note there is the .onAppear() function which unfortunately only triggers on the initial appear not on the reappearance of the view after the user logged in.

Thanks so much in advance! It has been really frustrating.

答:
The firebase and swiftUI combination is kinda tricky at first, but you will figure out that the same pattern is used in every single project, no worries.
Just follow my steps and customise on your project, here is our strategy.

- This might be a long answer, but i want to leave it as a refrence to all Firebase-SwiftUI user Managing in Stack OverFlow. -

Creating a SessionStore class which provides the BindableObject, and listen to your users Authentification and Handle the Auth and CRUD methods.

Creating a Model to our project ( you already did it)

Adding Auth methods in SessionStore Class.

Listening for changes and putting things together.

Let s start by SessionStore Class:
import SwiftUI
import Firebase
import Combine

```<code>class SessionStore : BindableObject {
    var didChange = PassthroughSubject<SessionStore, Never>()
    var session: User? { didSet { self.didChange.send(self) }}
    var handle: AuthStateDidChangeListenerHandle?

    func listen () {
        // monitor authentication changes using firebase
        handle = Auth.auth().addStateDidChangeListener { (auth, user) in
            if let user = user {
                // if we have a user, create a new user model
                print("Got user: \(user)")
                self.session = User(
                    uid: user.uid,
                    displayName: user.displayName
                )
            } else {
                // if we don't have a user, set our session to nil
                self.session = nil
            }
        }
    }

    // additional methods (sign up, sign in) will go here
}
</code>```

Notice that we’ve declared that our session property is an optional User type, which we haven’t yet defined. Let’s quickly make one:

```<code>class User {
    var uid: String
    var email: String?
    var displayName: String?

    init(uid: String, displayName: String?, email: String?) {
        self.uid = uid
        self.email = email
        self.displayName = displayName
    }

}
</code>```

Now, adding signUp, signIn and signOut methods

```<code>class SessionStore : BindableObject {

    // prev code...

    func signUp(
        email: String,
        password: String,
        handler: @escaping AuthDataResultCallback
        ) {
        Auth.auth().createUser(withEmail: email, password: password, completion: handler)
    }

    func signIn(
        email: String,
        password: String,
        handler: @escaping AuthDataResultCallback
        ) {
        Auth.auth().signIn(withEmail: email, password: password, completion: handler)
    }

    func signOut () -> Bool {
        do {
            try Auth.auth().signOut()
            self.session = nil
            return true
        } catch {
            return false
        }
    }
}
</code>```

Finally, we need a way to stop listening to our authentication change handler.

```<code>class SessionStore : BindableObject {

    // prev code...

    func unbind () {
        if let handle = handle {
            Auth.auth().removeStateDidChangeListener(handle)
        }
    }
}
</code>```

Finally, Making our content view:

```<code>import SwiftUI

struct ContentView : View {

  @EnvironmentObject var session: SessionStore
  var body: some View {
    Group {
     if (session.session != nil) {
      Text("Hello user!")
     } else {
        Text("Our authentication screen goes here...")
    }
   }
  }
}
</code>```

Body:
I'm fairly new to iOS Programming and swiftUI in particular.
I have the issue that I try to integrate firebase auth in my App in order to manage users.
Now the login, and log out basically works, the issue is, that after logging in, my view (which conditionally renders eighter the Google sign-in button or a list of content does not rerender so I still see the sign-in button even though I'm signed in).

I have set an observable Object to hold my auth status but unfortunately, it does not reload the current user automatically. So I set up a function to reload it manually which I would like to trigger when logging in. This works for the logout button but the logging in finishes in the AppDelegate, where for some reason I can't access the reloadUser() function.

I'm sure there is a better way to do this and would appreciate any help!

The Environment:

final class UserData: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var qrTags = qrTagData
    @Published var user: User? = Auth.auth().currentUser

    func reloadUser() -> Void {
        self.user = Auth.auth().currentUser
    }
}

The View I'd like to render:

struct MyQuaggsList: View {
        @EnvironmentObject private var userData: UserData

        var body: some View {
            Group {
                if getLogInState() != nil {
                    VStack {
                        NavigationView {
                            List {
                                Toggle(isOn: $userData.showFavoritesOnly) {
                                    Text("Show Favorites Only")
                                }

                                ForEach(userData.qrTags) { qrTag in
                                    if !self.userData.showFavoritesOnly || qrTag.isFavorite {
                                        NavigationLink(
                                            destination: QuagDetail(qrTag: qrTag)
                                                .environmentObject(self.userData)
                                        ) {
                                            QuaggRow(qrTag: qrTag)
                                        }
                                    }
                                }
                            }
                            .navigationBarTitle(Text("My Quaggs"))
                        }
                        SignOutButton()
                    }
                } else {
                    SignInView()
                }
            }.onAppear(perform: {self.userData.reloadUser()})
        }

        func getLogInState() -> User? {
            return Auth.auth().currentUser
        }
    }

Also, note there is the .onAppear() function which unfortunately only triggers on the initial appear not on the reappearance of the view after the user logged in.

Thanks so much in advance! It has been really frustrating.

Body:
The firebase and swiftUI combination is kinda tricky at first, but you will figure out that the same pattern is used in every single project, no worries.
Just follow my steps and customise on your project, here is our strategy.

- This might be a long answer, but i want to leave it as a refrence to all Firebase-SwiftUI user Managing in Stack OverFlow. -

Creating a SessionStore class which provides the BindableObject, and listen to your users Authentification and Handle the Auth and CRUD methods.

Creating a Model to our project ( you already did it)

Adding Auth methods in SessionStore Class.

Listening for changes and putting things together.

Let s start by SessionStore Class:
import SwiftUI
import Firebase
import Combine

class SessionStore : BindableObject {
    var didChange = PassthroughSubject<SessionStore, Never>()
    var session: User? { didSet { self.didChange.send(self) }}
    var handle: AuthStateDidChangeListenerHandle?

    func listen () {
        // monitor authentication changes using firebase
        handle = Auth.auth().addStateDidChangeListener { (auth, user) in
            if let user = user {
                // if we have a user, create a new user model
                print("Got user: \(user)")
                self.session = User(
                    uid: user.uid,
                    displayName: user.displayName
                )
            } else {
                // if we don't have a user, set our session to nil
                self.session = nil
            }
        }
    }

    // additional methods (sign up, sign in) will go here
}

Notice that we’ve declared that our session property is an optional User type, which we haven’t yet defined. Let’s quickly make one:

class User {
    var uid: String
    var email: String?
    var displayName: String?

    init(uid: String, displayName: String?, email: String?) {
        self.uid = uid
        self.email = email
        self.displayName = displayName
    }

}

Now, adding signUp, signIn and signOut methods

class SessionStore : BindableObject {

    // prev code...

    func signUp(
        email: String,
        password: String,
        handler: @escaping AuthDataResultCallback
        ) {
        Auth.auth().createUser(withEmail: email, password: password, completion: handler)
    }

    func signIn(
        email: String,
        password: String,
        handler: @escaping AuthDataResultCallback
        ) {
        Auth.auth().signIn(withEmail: email, password: password, completion: handler)
    }

    func signOut () -> Bool {
        do {
            try Auth.auth().signOut()
            self.session = nil
            return true
        } catch {
            return false
        }
    }
}

Finally, we need a way to stop listening to our authentication change handler.

class SessionStore : BindableObject {

    // prev code...

    func unbind () {
        if let handle = handle {
            Auth.auth().removeStateDidChangeListener(handle)
        }
    }
}

Finally, Making our content view:

import SwiftUI

struct ContentView : View {

  @EnvironmentObject var session: SessionStore
  var body: some View {
    Group {
     if (session.session != nil) {
      Text("Hello user!")
     } else {
        Text("Our authentication screen goes here...")
    }
   }
  }
}


问:
How to get the sequence lengths from padded batches from a `tf.data.Dataset`?
E.g. imagine I use the Librispeech dataset via TFDS (or whatever dataset, including sequences of varying length of data), and then use padded_batch to create batches, e.g. like this:

```<code>import tensorflow_datasets as tfds

dataset = tfds.load(name="librispeech", split="train_clean100")
dataset = dataset.shuffle(1024)
dataset = dataset.padded_batch(32)
</code>```

Now when iterating through the resulting dataset, i.e. over the (padded) batches, how would I know the original sequence lengths in the padded batch? Or is this information lost at this point? How would I extend the pipeline to include it? Is there a special dataset like AddSeqLengthInfoDataset or so? This would need to run before the padded_batch, right?
(This is basically an equivalent of my question for TF PaddingFIFOQueue but for tf.data.Dataset.)

Is there some example? (I wonder a bit that I have not found anything about this. I would assume this is a pretty standard requirement when you work on sequences, that you need to have the information about the original sequence lengths, or not?)

答:
You can just add a new field to the dataset holding the size of the sequence, for example like this:

import tensorflow as tf

# Make a dataset with variable-size data
def generate_data():
    for i in range(10):
        yield {'id': i, 'data': range(i % 5)}
ds = tf.data.Dataset.from_generator(generate_data,
                                    {'id': tf.int32, 'data': tf.int32},
                                    {'id': [], 'data': [None]})
# Add field with size of data
ds = ds.map(lambda item: {**item, 'size': tf.shape(item['data'])[0]})
# Padded batch
ds = ds.padded_batch(3)
# Show dataset
for batch in ds:
    tf.print(batch)
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>{'data': [[0 0]
 [0 0]
 [0 1]], 'id': [0 1 2], 'size': [0 1 2]}
{'data': [[0 1 2 0]
 [0 1 2 3]
 [0 0 0 0]], 'id': [3 4 5], 'size': [3 4 0]}
{'data': [[0 0 0]
 [0 1 0]
 [0 1 2]], 'id': [6 7 8], 'size': [1 2 3]}
{'data': [[0 1 2 3]], 'id': [9], 'size': [4]}
</code>```

Then you can use for example tf.sequence_mask with the value of that field to mask the padding values.

Another option is simply to pass some special padding_values to padded_batch that cannot appear in the actual data, e.g. -1 or nan, but that depends on whether those are actually invalid values for your problem.

Body:
E.g. imagine I use the Librispeech dataset via TFDS (or whatever dataset, including sequences of varying length of data), and then use padded_batch to create batches, e.g. like this:

import tensorflow_datasets as tfds

dataset = tfds.load(name="librispeech", split="train_clean100")
dataset = dataset.shuffle(1024)
dataset = dataset.padded_batch(32)

Now when iterating through the resulting dataset, i.e. over the (padded) batches, how would I know the original sequence lengths in the padded batch? Or is this information lost at this point? How would I extend the pipeline to include it? Is there a special dataset like AddSeqLengthInfoDataset or so? This would need to run before the padded_batch, right?
(This is basically an equivalent of my question for TF PaddingFIFOQueue but for tf.data.Dataset.)

Is there some example? (I wonder a bit that I have not found anything about this. I would assume this is a pretty standard requirement when you work on sequences, that you need to have the information about the original sequence lengths, or not?)

Body:
You can just add a new field to the dataset holding the size of the sequence, for example like this:

import tensorflow as tf

# Make a dataset with variable-size data
def generate_data():
    for i in range(10):
        yield {'id': i, 'data': range(i % 5)}
ds = tf.data.Dataset.from_generator(generate_data,
                                    {'id': tf.int32, 'data': tf.int32},
                                    {'id': [], 'data': [None]})
# Add field with size of data
ds = ds.map(lambda item: {**item, 'size': tf.shape(item['data'])[0]})
# Padded batch
ds = ds.padded_batch(3)
# Show dataset
for batch in ds:
    tf.print(batch)

Output:

{'data': [[0 0]
 [0 0]
 [0 1]], 'id': [0 1 2], 'size': [0 1 2]}
{'data': [[0 1 2 0]
 [0 1 2 3]
 [0 0 0 0]], 'id': [3 4 5], 'size': [3 4 0]}
{'data': [[0 0 0]
 [0 1 0]
 [0 1 2]], 'id': [6 7 8], 'size': [1 2 3]}
{'data': [[0 1 2 3]], 'id': [9], 'size': [4]}

Then you can use for example tf.sequence_mask with the value of that field to mask the padding values.

Another option is simply to pass some special padding_values to padded_batch that cannot appear in the actual data, e.g. -1 or nan, but that depends on whether those are actually invalid values for your problem.


问:
Touchablehighlight not clickable if position absolute
I have a Touchablehighlight that I need to position absolute, but it becomes unclickable after I do it.

What could cause this? It functions like it should if I dont have the position set to absolute.

答:
This worked for me

```<code>import { TouchableOpacity } from 'react-native-gesture-handler'
</code>```

and changed onPress to onPressIn

```<code><TouchableOpacity onPressIn={() => console.log('clicked')}></TouchableOpacity>
</code>```

Body:
This worked for me

import { TouchableOpacity } from 'react-native-gesture-handler'

and changed onPress to onPressIn

<TouchableOpacity onPressIn={() => console.log('clicked')}></TouchableOpacity>