问:
'for' loop through form fields and excluding one of the fields with 'if'
The problem I'm struggling with is as follows:

I have:

```<code>{% for field in form %}
    {{ field }}
{% end for %}
</code>```

What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:

```<code>{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}
</code>```

Is it possible? I have to many fields to write them one by one and only one or two to exclude.

Thank you for any tips.

BR,
Czlowiekwidmo.

答:
Yes, this should be possible:

```<code>{% for field in form %}
    {% ifnotequal field.label title %}
        {{ field }}
    {% endifnotequal %}
{% endfor %}
</code>```

Django's template tags offer ifequal and ifnotequal variants, and you can test the field.label against either a context variable, or a string.

OwnerDisplayName: Czlowiekwidmo

ContentLicense: CC BY-SA 2.5

Body:
The problem I'm struggling with is as follows:

I have:

{% for field in form %}
    {{ field }}
{% end for %}

What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:

{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}

Is it possible? I have to many fields to write them one by one and only one or two to exclude.

Thank you for any tips.

BR,
Czlowiekwidmo.

Body:
Yes, this should be possible:

{% for field in form %}
    {% ifnotequal field.label title %}
        {{ field }}
    {% endifnotequal %}
{% endfor %}

Django's template tags offer ifequal and ifnotequal variants, and you can test the field.label against either a context variable, or a string.

OwnerDisplayName: Jarret Hardie

LastEditorDisplayName: DzinX


来源: stackexchange

问:
How can I autoscale the font size to fit the contents of a div?
I have a div with some text:

```<code><div style="white-space:nowrap;overflow:none;width:50px;">
  With some text in it
</div>
</code>```

How can I scale the font size of the text so all of the text is visible?

答:
Short Answer:  You don't.

You would have to try a size, render it, see if it fits, try another size, render it see if it fits, etc.  Then you have to handle the case where the calculated font size is so small no one can read the text.

There are other options, if the text doesn't fit, add an ellipsis (...) to the end of the text, when you mouse over it, the div could expand, you could use a popup window or tooltip with the full text, or put the full text in a larger area of the screen.

Find another way.

ContentLicense: CC BY-SA 3.0

Body:
I have a div with some text:

  With some text in it

How can I scale the font size of the text so all of the text is visible?


问:
Types of inheritance is supported in Swift
i guess only these two types are available in swift, i just want to know, am i missing any, your help will be appreciated?

Single

Multilevel

答:
iOS supported Inheritance types.

Single

Multilevel

Hierarchical

Hybrid (combination of more than one form of inheritance)

Note: Multiple Inheritance not supported by many modern languages, due to avoid Diamond shape ambiguity.

Yes, both languages (Swift and Objective-C) support hierarchical inheritance. There are countless examples in the iOS SDK.

UIResponder is subclassed by UIApplication, UIView, UIViewController.

UIView obviously has many subclasses as does UIViewController.

And Hybrid also, here is a sample, combination of Multilevel and Hierarchical.

```<code>class Parent {
    fun_f1
}

class Child1: Parent {
    fun_f2
}

class Child2: Parent {
    fun_f3
}

class Child3: Child1 {
    fun_f4
}

class TestHybrid {
    fun test() {
        var c3: Child3
        c3.f1();
        c3.f2();
        c3.f4();
    }
}
</code>```

Body:
iOS supported Inheritance types.

Single

Multilevel

Hierarchical

Hybrid (combination of more than one form of inheritance)

Note: Multiple Inheritance not supported by many modern languages, due to avoid Diamond shape ambiguity.

Yes, both languages (Swift and Objective-C) support hierarchical inheritance. There are countless examples in the iOS SDK.

UIResponder is subclassed by UIApplication, UIView, UIViewController.

UIView obviously has many subclasses as does UIViewController.

And Hybrid also, here is a sample, combination of Multilevel and Hierarchical.

class Parent {
    fun_f1
}

class Child1: Parent {
    fun_f2
}

class Child2: Parent {
    fun_f3
}

class Child3: Child1 {
    fun_f4
}

class TestHybrid {
    fun test() {
        var c3: Child3
        c3.f1();
        c3.f2();
        c3.f4();
    }
}

ContentLicense: CC BY-SA 4.0


问:
AADSTS700016 ERROR when I try to get access to my outlook calandar with python
I'm trying to get access to my outlook calandar using the following code:

```<code>

from bs4 import BeautifulSoup
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from O365 import Account
from O365 import Connection
from O365 import FileSystemTokenBackend

from configparser import ConfigParser
file='config.py'
config = ConfigParser()
config.read(file)

def authenticate_outlook():
   # authenticate microsoft graph api credentials

   credentials = (config['account']['outlook_client_id'], config['account']['outlook_client_id'])
   token_backend = FileSystemTokenBackend(
       token_path=config['account']['outlook_token_path'], token_filename=config['account']['outlook_token_filename']
   )
   account = Account(credentials, token_backend=token_backend)
   if not account.is_authenticated:
       # not authenticated, throw error
       account.authenticate(scopes=config['account']['outlook_scopes'])

   connection = Connection(credentials, token_backend=token_backend, scopes=config['account']['outlook_scopes'])
   connection.refresh_token()

   print("Authenticated Outlook.")
   return account
# authenticate outlook credentials
outlook_acct = authenticate_outlook()

</code>```

And i'm using this config.py file:

```<code>[account]
outlook_client_id = "86ae4814-fad2-4cc0-b76e-57bd4b20476c"
outlook_client_secret = "06ecc895-b04d-4578-9c3c-b5a8ccc026ab"
outlook_scopes = ["basic", "calendar"]
outlook_token_path = "./credentials/"
outlook_token_filename = "outlook_token.txt"
previous_days = 40  # retrieve this many past days of events
future_days = 365  # retrieve this many future days of events
</code>```

Then I get this error:
AADSTS700016: Application with identifier '"86ae4814-fad2-4cc0-b76e-57bd4b20476c"' was not found in the directory 'z7fs3'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.

I checked that i'm using the good app ID and the secret ID, They match with my app on AZURE, I don't ound the issue yet.

Thank you.

答:
The issue indicates that there is a mismatch between the tenant where your app is registered and where you have stated that your app is registered in either the application code or the portal.

You must set the tenant ID in your codE for the application. This is usually found in the web.config or app settings files.
Then, using the same tenant ID that you specified in your code, you must register the application on the portal. Make sure your application ID and client ID are the same on both sides, and that all of the values in your app settings/web.config are the same as what you have in the portal.

Also, using the ID in the Client secret section instead of the Application (client) ID is a common cause of this problem.

Body:
I'm trying to get access to my outlook calandar using the following code:

from bs4 import BeautifulSoup
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from O365 import Account
from O365 import Connection
from O365 import FileSystemTokenBackend

from configparser import ConfigParser
file='config.py'
config = ConfigParser()
config.read(file)

def authenticate_outlook():
   # authenticate microsoft graph api credentials

   credentials = (config['account']['outlook_client_id'], config['account']['outlook_client_id'])
   token_backend = FileSystemTokenBackend(
       token_path=config['account']['outlook_token_path'], token_filename=config['account']['outlook_token_filename']
   )
   account = Account(credentials, token_backend=token_backend)
   if not account.is_authenticated:
       # not authenticated, throw error
       account.authenticate(scopes=config['account']['outlook_scopes'])

   connection = Connection(credentials, token_backend=token_backend, scopes=config['account']['outlook_scopes'])
   connection.refresh_token()

   print("Authenticated Outlook.")
   return account
# authenticate outlook credentials
outlook_acct = authenticate_outlook()

And i'm using this config.py file:

[account]
outlook_client_id = "86ae4814-fad2-4cc0-b76e-57bd4b20476c"
outlook_client_secret = "06ecc895-b04d-4578-9c3c-b5a8ccc026ab"
outlook_scopes = ["basic", "calendar"]
outlook_token_path = "./credentials/"
outlook_token_filename = "outlook_token.txt"
previous_days = 40  # retrieve this many past days of events
future_days = 365  # retrieve this many future days of events

Then I get this error:
AADSTS700016: Application with identifier '"86ae4814-fad2-4cc0-b76e-57bd4b20476c"' was not found in the directory 'z7fs3'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.

I checked that i'm using the good app ID and the secret ID, They match with my app on AZURE, I don't ound the issue yet.

Thank you.


问:
An AWS CI/CD Pipeline that allows manual deploy by commit

Background

I want to create the following CI/CD flow in AWS and Github, for a react app using Amplify:

A single main branch, with short-lived feature branches and PRs into main.

Each PR triggers its own test environment in Amplify, with its own temporary subdomain, which gets torn down when the PR is merged, as described here.

Merging into main does not automatically trigger a deploy to production.

Instead, there is a separate mechanism (a web page, or amplify command, or even triggers based on git tags) for manually selecting a commit from main to deploy to production.

Questions

It's not clear to me if...

Support for this flow is already built into Amplify (based on the docs I've read, I think the answer is "no", but I'm not sure).

Support for this flow is already built into AWS CodePipeline, or if it can be configured there.

There is another AWS tool that solves this.

I'm looking for answers to those questions, or specific references in the docs which address them.

答:
In my experience, I don't think there is any easy way to meet your requirement.

If you are using Gitlab, you can try Gitlab Review Apps to achieve that (I tried before with some scripts)


问:
how to hide bottomnavigation and app bar on scroll when app bar inside FragmentContainerView
I know we can hide bottomnavigation and app bar on scroll when both are the direct children of coordinate layout, But my issue is different, I have one home fragment and bottom view is a part of this fragment with FragmentContainerView, now my app bar inside the fragment which i am setting in container view, when i am scrolling, app bar getting scroll properly but i am not sure how to scroll bottom navigation as well,

home_fragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/rootFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="@drawable/nav_bar_tab_color"
        android:background="?android:attr/windowBackground"
        app:itemTextAppearanceActive="@style/navText"
        app:itemTextAppearanceInactive="@style/navText"
        app:itemTextColor="@drawable/nav_bar_tab_color"
        app:labelVisibilityMode="unlabeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/navigation_items" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

another fragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/appbar"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvLay"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/rvProgressBar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
        <ProgressBar
            android:id="@+id/rvProgressBar"
            android:visibility="gone"
            android:layout_width="0dp"
            android:layout_height="50dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@color/colorWhite"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat" >
            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="@dimen/twentyfour_24dp"
                android:paddingBottom="@dimen/eighteen_18dp"
                android:text="@string/t2"
                android:gravity="center"
                android:textAllCaps="true"
                style="@style/text_16px_franklin_gothic_normal_" />
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Can some one please explain me, how to achieve it?

答:
Have you tried to add app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior" inside your BottomNavigationView? In my case, it works just fine :)

I also suggest you to use CoordinatorLayout instead of ConstraintLayout in your home_fragment.xml

Body:
I know we can hide bottomnavigation and app bar on scroll when both are the direct children of coordinate layout, But my issue is different, I have one home fragment and bottom view is a part of this fragment with FragmentContainerView, now my app bar inside the fragment which i am setting in container view, when i am scrolling, app bar getting scroll properly but i am not sure how to scroll bottom navigation as well,

home_fragment:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/rootFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="@drawable/nav_bar_tab_color"
        android:background="?android:attr/windowBackground"
        app:itemTextAppearanceActive="@style/navText"
        app:itemTextAppearanceInactive="@style/navText"
        app:itemTextColor="@drawable/nav_bar_tab_color"
        app:labelVisibilityMode="unlabeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/navigation_items" />
</androidx.constraintlayout.widget.ConstraintLayout>

another fragment:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/appbar"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvLay"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/rvProgressBar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
        <ProgressBar
            android:id="@+id/rvProgressBar"
            android:visibility="gone"
            android:layout_width="0dp"
            android:layout_height="50dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@color/colorWhite"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat" >
            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="@dimen/twentyfour_24dp"
                android:paddingBottom="@dimen/eighteen_18dp"
                android:text="@string/t2"
                android:gravity="center"
                android:textAllCaps="true"
                style="@style/text_16px_franklin_gothic_normal_" />
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Can some one please explain me, how to achieve it?


问:
Implement a timer for user logout after timeout in the frontend
I was wondering what the best way of implementing a timer in the frontend would be.

The idea is to notify the user after 13 minutes of inactivity (= not made a request to the backend) that he will be logged out in 2 minutes.

My first attempt was to just use a Timer which is executed every second (I am doing this with Flutter web but it shouldn't make a difference) and counts down from 15 minutes.

Then we tested this internally and noticed that the Browser somehow stops JavaScript execution if the user switches to a different tab for a long time or if the computer goes into stand by such that the timer stops.

We already have a session timeout after 15 minutes from the backend, this is just to make the user experience better.

How would this be correctly implemented?

答:
For short, I think it's impossible for only using frontend

As you examine, the javascript code will be stop whenever switching tab or close tab, computer stands by. So that it will not be good to use a timeout or something like that.

I used an idea before but not implemented it yet because I switched to simpler idea with sessionStorage. But you could see and somehow success with it: when last request is made, created a cookie with expire time is 13 minutes. If next request is made, clear old cookie and add a new cookie with 13 minutes too. If the request will not made during 13 minutes, when cookie expire, fire a event to annouce to user. To listening cookie change, I think there are a lot solutions out there. But for me, this idea is not so good so I forgot it.

If you can use a nodejs backend, you could try to use Server Send Event - SSE. This will create one-way sending data. Therefore you can stream a chunk of data. And the frontend will listen that streaming and decide whether to annouce to user.


问:
GCP Create Project via Python
I have an organization under which I want to create a project using python, as per the documentation, without mentioning the parent , service account throws error as below
"Service accounts cannot create projects without a parent.". Details: "Service accounts cannot create projects without a parent."

Hence I provided a parent as below,

```<code>def create_signer(googleservice, principal, key, version):

    google_token_uri = 'https://oauth2.googleapis.com/token'
    if not all(['principal', 'key']):
        raise Exception('Google secret missing principal and/or key')
    signer = crypt.RSASigner.from_string(key.strip())
    credential = service_account.Credentials(signer, principal,
                                             google_token_uri)
    service = build(googleservice, version, credentials=credential,
                    cache_discovery=False)
    return service

def create_project():

    service = create_signer('cloudresourcemanager', principal, key, 'v1')
    operation = service.projects().create(
        body={
            'parent': {'type': 'organization', 'id': '72******78*8'},
            'project_id': 'abcd1234'
        }).execute()
    print(operation)
</code>```

But this throws below error,
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://cloudresourcemanager.googleapis.com/v1/projects?alt=json returned "The caller does not have permission". Details: "The caller does not have permission">

I have created a custom role at organization level with below permissions and attached it to my service account created at project level(since organization does not allow creating service accounts at organization level),

```<code>iam.roles.create
iam.roles.delete
iam.roles.get
iam.roles.list
iam.roles.undelete
iam.roles.update
orgpolicy.constraints.list
orgpolicy.policies.list
orgpolicy.policy.get
resourcemanager.folders.create
resourcemanager.folders.get
resourcemanager.folders.getIamPolicy
resourcemanager.folders.list
resourcemanager.folders.setIamPolicy
resourcemanager.organizations.get
resourcemanager.organizations.getIamPolicy
resourcemanager.organizations.setIamPolicy
resourcemanager.projects.create
resourcemanager.projects.createBillingAssignment
resourcemanager.projects.get
resourcemanager.projects.getIamPolicy
resourcemanager.projects.list
resourcemanager.projects.setIamPolicy
</code>```

Can someone please help me with this issue? I have all the required permissions but still having throws 403 error

Just to add, gcp list api call projects works fine

答:
Finally I found the issue, its not related to permissions but actually the way the permissions are added. i.e. we need to add the permissions in "Setup your Foundation->Administrative Access" for this to work with proper permissions.

Thanks Bakul for your guidance. Here we can provide the service account name and attach roles to it.

Title: GCP Create Project via Python

Body:
I have an organization under which I want to create a project using python, as per the documentation, without mentioning the parent , service account throws error as below
"Service accounts cannot create projects without a parent.". Details: "Service accounts cannot create projects without a parent."

Hence I provided a parent as below,

def create_signer(googleservice, principal, key, version):

    google_token_uri = 'https://oauth2.googleapis.com/token'
    if not all(['principal', 'key']):
        raise Exception('Google secret missing principal and/or key')
    signer = crypt.RSASigner.from_string(key.strip())
    credential = service_account.Credentials(signer, principal,
                                             google_token_uri)
    service = build(googleservice, version, credentials=credential,
                    cache_discovery=False)
    return service

def create_project():

    service = create_signer('cloudresourcemanager', principal, key, 'v1')
    operation = service.projects().create(
        body={
            'parent': {'type': 'organization', 'id': '72******78*8'},
            'project_id': 'abcd1234'
        }).execute()
    print(operation)

But this throws below error,
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://cloudresourcemanager.googleapis.com/v1/projects?alt=json returned "The caller does not have permission". Details: "The caller does not have permission">

I have created a custom role at organization level with below permissions and attached it to my service account created at project level(since organization does not allow creating service accounts at organization level),

iam.roles.create
iam.roles.delete
iam.roles.get
iam.roles.list
iam.roles.undelete
iam.roles.update
orgpolicy.constraints.list
orgpolicy.policies.list
orgpolicy.policy.get
resourcemanager.folders.create
resourcemanager.folders.get
resourcemanager.folders.getIamPolicy
resourcemanager.folders.list
resourcemanager.folders.setIamPolicy
resourcemanager.organizations.get
resourcemanager.organizations.getIamPolicy
resourcemanager.organizations.setIamPolicy
resourcemanager.projects.create
resourcemanager.projects.createBillingAssignment
resourcemanager.projects.get
resourcemanager.projects.getIamPolicy
resourcemanager.projects.list
resourcemanager.projects.setIamPolicy

Can someone please help me with this issue? I have all the required permissions but still having throws 403 error

Just to add, gcp list api call projects works fine


问:
Media Player - Seek bar and Time lable is not progressing
IDK why but after just coping the entier mainactivty.java file from this video

IDK why my seek bar and timetable are not showing any progress

there is an exception I have 2 audio files but the video show has only one so I have doubled all the methods also the onClick and a dialog which is different from it

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    int totalTime2;

    @Override

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

        // PlayButton    *  The ButtonClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn1);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        elapsedTimeLable1 = findViewById(R.id.cTime1);
        elapsedTimeLable2 = findViewById(R.id.cTime2);
        remainingTimeLable1 = findViewById(R.id.tTime1);
        remainingTimeLable2 = findViewById(R.id.tTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player1.setLooping(true);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player2.setLooping(true);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();

        //SeekBar

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
                if (fromUser1) {
                    player1.seekTo(progress1);
                    seekBar1.setProgress(progress1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
                if (fromUser2) {
                    player2.seekTo(progress2);
                    seekBar2.setProgress(progress2);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // Thread (Update SeekBar & TimeLabel)
        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000000000);
                } catch (InterruptedException e) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000000000);
                } catch (InterruptedException e) {

                }
            }
        }).start();

        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // Caution dialog

        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = preferences.getBoolean("firstStart", true);
        if (firstStart) {

            showDialog();
        }

    }

    // Caution dialog
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Caution!")
                .setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create().show();
        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstStart", false);
        editor.apply();
    }

    private  Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

        }
    };
    private  Handler handler2 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            // Update SeekBar
            seekBar2.setProgress(currentPosition2);
            // Update Timelable
            String elapsedTime2 = createTimerLable2(currentPosition2);
            elapsedTimeLable2.setText(elapsedTime2);
            String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
            remainingTimeLable2.setText("- " + remainingTime2);

        }
    };

    public String createTimerLable1(int duration) {
        String timerLabel1 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel1 += min + ":";
        if (sec < 10) timerLabel1 += "0";
        timerLabel1 += sec;
        return timerLabel1;

    }

    public String createTimerLable2(int duration) {
        String timerLabel2 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel2 += min + ":";
        if (sec < 10) timerLabel2 += "0";
        timerLabel2 += sec;
        return timerLabel2;

    }

    public void playBtnClick1(View view) {

        if (player2.isPlaying()) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {

        if (player1.isPlaying()) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

}
</code>```

答:
So well why should threads  sleep 1000000000 milliseconds.
In that case your thread does its tasks every 1000000 seconds.

1000000000 ms => 1000000 sec => 16666 min => 277 hour

So your thread does its task every 277 hours.
The param of sleep is millisecond so put st like 1000(1 second) or something like that which is a lot shorter.
If this wasn't solution let me know.

Body:
IDK why but after just coping the entier mainactivty.java file from this video

IDK why my seek bar and timetable are not showing any progress

there is an exception I have 2 audio files but the video show has only one so I have doubled all the methods also the onClick and a dialog which is different from it

MainActivity.java

public class MainActivity extends AppCompatActivity {
    MediaPlayer player1;
    MediaPlayer player2;
    SeekBar seekBar1;
    SeekBar seekBar2;
    TextView elapsedTimeLable1;
    TextView elapsedTimeLable2;
    TextView remainingTimeLable1;
    TextView remainingTimeLable2;
    ImageView play1;
    ImageView play2;
    int totalTime1;
    int totalTime2;

    @Override

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

        // PlayButton    *  The ButtonClick is in the last if you want to jump directly there  *

        play1 = findViewById(R.id.playbtn1);
        play2 = findViewById(R.id.playbtn2);

        // TimeLables

        elapsedTimeLable1 = findViewById(R.id.cTime1);
        elapsedTimeLable2 = findViewById(R.id.cTime2);
        remainingTimeLable1 = findViewById(R.id.tTime1);
        remainingTimeLable2 = findViewById(R.id.tTime2);

        // MediaPlayer

        player1 = MediaPlayer.create(this, R.raw.dog_howl);
        player1.setLooping(true);
        player1.seekTo(0);
        totalTime1 = player1.getDuration();
        player2 = MediaPlayer.create(this, R.raw.dog_bark);
        player2.setLooping(true);
        player2.seekTo(0);
        totalTime2 = player2.getDuration();

        //SeekBar

        seekBar1 = findViewById(R.id.seekbar1);
        seekBar2 = findViewById(R.id.seekbar2);
        seekBar1.setMax(totalTime1);
        seekBar2.setMax(totalTime2);

        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
                if (fromUser1) {
                    player1.seekTo(progress1);
                    seekBar1.setProgress(progress1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
                if (fromUser2) {
                    player2.seekTo(progress2);
                    seekBar2.setProgress(progress2);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        // Thread (Update SeekBar & TimeLabel)
        new Thread(() -> {
            while (player1 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player1.getCurrentPosition();
                    handler1.sendMessage(msg);
                    Thread.sleep(1000000000);
                } catch (InterruptedException e) {

                }
            }
        }).start();

        new Thread(() -> {
            while (player2 != null) {
                try {
                    Message msg = new Message();
                    msg.what = player2.getCurrentPosition();
                    handler2.sendMessage(msg);
                    Thread.sleep(1000000000);
                } catch (InterruptedException e) {

                }
            }
        }).start();

        // Admob Banner Ad

        MobileAds.initialize(this, initializationStatus -> {
        });

        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // Caution dialog

        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = preferences.getBoolean("firstStart", true);
        if (firstStart) {

            showDialog();
        }

    }

    // Caution dialog
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("Caution!")
                .setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create().show();
        SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("firstStart", false);
        editor.apply();
    }

    private  Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition1 = msg.what;
            //Update SeekBar
            seekBar1.setProgress(currentPosition1);
            // Update Timelable
            String elapsedTime1 = createTimerLable1(currentPosition1);
            elapsedTimeLable1.setText(elapsedTime1);
            String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
            remainingTimeLable1.setText("- " + remainingTime1);

        }
    };
    private  Handler handler2 = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int currentPosition2 = msg.what;
            // Update SeekBar
            seekBar2.setProgress(currentPosition2);
            // Update Timelable
            String elapsedTime2 = createTimerLable2(currentPosition2);
            elapsedTimeLable2.setText(elapsedTime2);
            String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
            remainingTimeLable2.setText("- " + remainingTime2);

        }
    };

    public String createTimerLable1(int duration) {
        String timerLabel1 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel1 += min + ":";
        if (sec < 10) timerLabel1 += "0";
        timerLabel1 += sec;
        return timerLabel1;

    }

    public String createTimerLable2(int duration) {
        String timerLabel2 = "";
        int min = duration / 1000 / 60;
        int sec = duration / 1000 % 60;
        timerLabel2 += min + ":";
        if (sec < 10) timerLabel2 += "0";
        timerLabel2 += sec;
        return timerLabel2;

    }

    public void playBtnClick1(View view) {

        if (player2.isPlaying()) {
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player1.isPlaying()) {
            // Stoping
            player1.start();
            play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

    public void playBtnClick2(View view) {

        if (player1.isPlaying()) {
            player1.pause();
            play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

        if (!player2.isPlaying()) {
            // Stoping
            player2.start();
            play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            // Playing
            player2.pause();
            play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
        }

    }

}


问:
Where to place ||
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!</p>

```<code>if ([[file pathExtension] isEqualToString:@"caf"])
</code>```

答:
```<code>if ([[file pathExtension] isEqualToString:@"caf"] || [[file pathExtension] isEqualToString:@"aac"])
</code>```

Title: Where to place ||

Body:
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!

if ([[file pathExtension] isEqualToString:@"caf"])


问:
Combine Rows but concatenate on a certain field in Excel Power Query or Microsoft SQL
I have brought a table from an Authority database into Excel via power query OBDC type, that includes fields like:

Date - various

Comments - mem_txt

Sequence - seq_num

The Comments field has a length restriction, and if a longer string is entered, it returns multiple rows with the Comments  field being chopped into suitable lengths and the order returned in the Sequence field as per extract below.  All other parts of the records are the same.

I want to collapse the rows based and concatenate the various Comments into a single entry. There is a date/time column just outside of the screen shot above that can be used to group the rows by (it is the same for the set of rows, but unique across the data set).

For example:

I did try bring the data in by a query connection, using the GROUP_CONCAT(Comments SEPARATOR ', ') and GROUP BY date, but that command isn't available in Microsoft Query.

答:
Assuming the date/time column you refer to is named date_time, the M code would be:

```<code>let
  Source = Excel.CurrentWorkbook(){[Name = "Table1"]}[Content],
  #"Grouped Rows" = Table.Group(
    Source,
    {"date_time"},
    {{"NewCol", each Text.Combine([mem_text])}}
  )
in
  #"Grouped Rows"
</code>```

Amend the Source line as required.

Body:
Assuming the date/time column you refer to is named date_time, the M code would be:

let
  Source = Excel.CurrentWorkbook(){[Name = "Table1"]}[Content],
  #"Grouped Rows" = Table.Group(
    Source,
    {"date_time"},
    {{"NewCol", each Text.Combine([mem_text])}}
  )
in
  #"Grouped Rows"

Amend the Source line as required.


问:
How do you determine the version of OCaml or Jane Street Core library at runtime
I am migrating to a recent version of OCaml (and Jane Street's Core modules), but would like my code to continue to compile with older versions. To do so, I would like to create a module with portable functions that map to either the old or new interfaces depending on the version. Querying both the version of OCaml and the version of Jane Street Core would work.

How can we look up the version of the compiler or of Jane Street Core at runtime? I know that I could pass the output of ocamlopt --version via my build system, but ideally I should not have to invoke my programs in a special way.

答:
You could use
Config.version from Compiler_libs as documented here https://ocaml.org/api/compilerlibref/Config.html.

Note this warning from Compiler_libs:

This library is part of the internal OCaml compiler API, and is not
the language standard library. There are no compatibility guarantees
between releases, so code written against these modules must be
willing to depend on specific OCaml compiler versions.


问:
Passing array into query string
I need to send array as query parameter, I do it like this

```<code>StringBuilder Ids = new StringBuilder();
for (int i = 0; i < array.Count; i++)
{
    Ids.Append(String.Format("&id[{0}]={1}", i, items[i].ID));
}

ifrDocuments.Attributes.Add("src", "Download.aspx?arrayCount=" + array.Count + Ids);
</code>```

After this I have string:

```<code>Download.aspx?arrayCount=8&id[0]=106066&id[1]=106065&id[2]=106007&id[3]=105284&id[4]=105283&id[5]=105235&id[6]=105070&id[7]=103671
</code>```

It can contain 100 elements and in this case I'm getting error:

enter image description here

Maybe I can do it in another way? Not by sending it inside query qtring.

答:
There is a limit on URL length on multiple levels (browsers, proxy servers, etc). You can change maxQueryString (*1) but I would not recommend it if you expect real users to use your system.

It looks like downloads.aspx is your page. Put all those ids in temporary storage - (cache or database) and pass the key to this new entity in the request

*1: https://blog.elmah.io/fix-max-url-and-query-string-length-with-web-config-and-iis/

Title: Passing array into query string

Body:
I need to send array as query parameter, I do it like this

StringBuilder Ids = new StringBuilder();
for (int i = 0; i < array.Count; i++)
{
    Ids.Append(String.Format("&id[{0}]={1}", i, items[i].ID));
}

ifrDocuments.Attributes.Add("src", "Download.aspx?arrayCount=" + array.Count + Ids);

After this I have string:

Download.aspx?arrayCount=8&id[0]=106066&id[1]=106065&id[2]=106007&id[3]=105284&id[4]=105283&id[5]=105235&id[6]=105070&id[7]=103671

It can contain 100 elements and in this case I'm getting error:

enter image description here

Maybe I can do it in another way? Not by sending it inside query qtring.


问:
Django SESSION_COOKIE_DOMAIN
I'm seeing something mysterious with the SESSION_COOKIE_DOMAIN setting in django.

Normally, when I have this set to ".mydomain.net" it works fine. But occasionally cookies don't seem to be being set, because when I log in, I'm not remembered in the session and I become AnonymousUser when I get to the next page.

In these circumstances, if, I change my settings file so that SESSION_COOKIE_DOMAIN is now None or "", then the site behaviour returns to normal. If I change SESSION_COOKIE_DOMAIN back to mydomain, the problem returns.

Any ideas? Is this likely to be a silent failure in the settings? Or could it be something to do with my server configuration? Or the machine I'm accessing the site from?

答: In all likelihood, you are ending up with multiple sessionid cookies being sent. If you have a sessionid cookie with domain 'example.com' and another cookie with domain '.example.com', Django will test only one of those sessionid values. I am unsure of how Django decides which sessionid value to test for validity.</p>

Title: Django SESSION_COOKIE_DOMAIN


问:
Advertising flag, “BR/EDR Not Supported.”, how is it interpreted?
If the “BR/EDR Not Supported.” bit is set as "0" or "1" what does that mean? I have been confused for the last hour about how to interpret it.

If the bit is set as 1, does that mean the "BR/EDR Not Supported" is false which means that BR/EDR is indeed supported? Or is it the other way around with the bit set as "0"?

答:
The following is from BLUETOOTH CORE SPECIFICATION Version 5.3 | Vol 3, Part C:

• For a device of the LE-only device type with all the following flags
set as described:

a) The ‘BR/EDR Not Supported’ flag to set one.

b) The ‘Simultaneous LE and BR/EDR to Same Device Capable (Controller)’
flag set to zero.

Having a 1 for the BR/EDR Not Supported flag means it does not support BR/EDR. i.e: it is an LE only device.


问:
Birt Reports - Adding percentages to chart legend
Is it possible to add percentages to the chart legend, or is it the only way to put percentages to the chart, by adding the "Percentile Value Data"?

Thanks for your help in advance.

答:
AFAIK the percentile value is usually something different, it only makes sense if the categories are based on intervals, e.g. given 7 billion living humans and measuring their age, the top 0.1 percentile are the 7_000_000_000 * 0.1/100 = 7_000_000 oldest living humans.

So, percentile values make sense for things you can measure, like age, income, length - in other words, numbers, or at least things which can be ordered.
You wouldn't use a pie chart then.

Percentile values don't make sense for things that cannot be measured like car labels.

Take a look at https://forums.opentext.com/forums/developer/discussion/48914/how-to-create-pie-chart-with-percentage-instead-of-values

M Williams writes there (I just repeat this here):

In the chart editor, you can go to the "format data" tab, then to the value series section, click on the "labels" button at the bottom, delete the "value data" option from the values window, then from the dropdown below the window, choose the percentage option and add it. This will show your pie chart labels in percentage.


问:
Retrieve value of a column after update?
I update a counter (no autoincrement ... not my database ...) with this FDQuery SQL:

```<code>UPDATE CountersTables
SET Cnter = Cnter + 1
OUTPUT Inserted.Cnter
WHERE TableName = 'TableName'
</code>```

I execute FDQuery.ExecSQL and it works: 'Cnter' is incremented.

I need to retrieve the new 'Counter' value but the subsequent command

```<code>newvalue := FDQuery.FieldByName('Cnter').AsInteger
</code>```

Fails with error:

... EDatabaseError ... 'CountersTables: Field 'Cnter' not found.

What is the way to get that value?

答:
You have also the RETURNING Unified support Ok, doc only shows INSERT SQL but UPDATE works too.
And I should use a substitution variable for tablename</p>

Body:
I update a counter (no autoincrement ... not my database ...) with this FDQuery SQL:

UPDATE CountersTables
SET Cnter = Cnter + 1
OUTPUT Inserted.Cnter
WHERE TableName = 'TableName'

I execute FDQuery.ExecSQL and it works: 'Cnter' is incremented.

I need to retrieve the new 'Counter' value but the subsequent command

newvalue := FDQuery.FieldByName('Cnter').AsInteger

Fails with error:

... EDatabaseError ... 'CountersTables: Field 'Cnter' not found.

What is the way to get that value?


问:
My app crashed when clicking new dependency question. I don't know what is the error and how to solved it
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6969
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.login/com.example.login.NavigationDrawer}: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.navigation.NavigationView.getHeaderView(int)' on a null object reference
at com.example.login.ui.questionnaire.QuestionnaireFragment.onCreateView(QuestionnaireFragment.java:80)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2777)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3020)
at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:295)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:274)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:784)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:867)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:54)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:48)
E/AndroidRuntime:     at com.example.login.NavigationDrawer.onCreate(NavigationDrawer.java:42)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873

```<code>Java Code

package com.example.login;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.login.databinding.ActivityNavigationDrawerBinding;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
public class NavigationDrawer extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityNavigationDrawerBinding binding;
private String username;
private EditText etUsername;
Pref pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = new Pref(getApplicationContext());
//get username from login page
username = pref.getUsername();
//System.out.println("username in 2nd  "+username);
binding = ActivityNavigationDrawerBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(binding.navView);
setSupportActionBar(binding.appBarNavigationDrawer.toolbar);
binding.appBarNavigationDrawer.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_questionnaire, R.id.nav_submitsurvey, R.id.nav_responses, R.id.nav_imagecapture, R.id.nav_dashboard)
.setOpenableLayout(drawer)
.build();
 NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
//display welcome username
etUsername = findViewById(R.id.welcomeUsername);
 etUsername.setText(username);
 Button button_log_out = findViewById(R.id.button_log_out);
button_log_out.setOnClickListener(new View.OnClickListener() {
 @Override
public void onClick(View v) {
logoutDialog();
}
});
return true;
    }
    @Override
    public boolean onSupportNavigateUp() {
 NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
 || super.onSupportNavigateUp();
}
public void logoutDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("LogOut Alert!");
alertDialog.setMessage("Are you sure want to LogOut this Application?");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
  pref.setLogin("no");
dialog.dismiss();
Intent intent = new Intent(NavigationDrawer.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 dialog.dismiss();
 }
        });
alertDialog.show();
    }
}
</code>```

答:
you have a NullPointerException. You should check whether the data you receive is full. For example
if(data != null){
.
.
.
...
}</p>

Body:
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6969
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.login/com.example.login.NavigationDrawer}: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #19: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.navigation.NavigationView.getHeaderView(int)' on a null object reference
at com.example.login.ui.questionnaire.QuestionnaireFragment.onCreateView(QuestionnaireFragment.java:80)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2777)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3020)
at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:295)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:274)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:784)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:867)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:999)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:54)
at com.example.login.databinding.ActivityNavigationDrawerBinding.inflate(ActivityNavigationDrawerBinding.java:48)
E/AndroidRuntime:     at com.example.login.NavigationDrawer.onCreate(NavigationDrawer.java:42)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873

Java Code

package com.example.login;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.login.databinding.ActivityNavigationDrawerBinding;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
public class NavigationDrawer extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityNavigationDrawerBinding binding;
private String username;
private EditText etUsername;
Pref pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = new Pref(getApplicationContext());
//get username from login page
username = pref.getUsername();
//System.out.println("username in 2nd  "+username);
binding = ActivityNavigationDrawerBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(binding.navView);
setSupportActionBar(binding.appBarNavigationDrawer.toolbar);
binding.appBarNavigationDrawer.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_questionnaire, R.id.nav_submitsurvey, R.id.nav_responses, R.id.nav_imagecapture, R.id.nav_dashboard)
.setOpenableLayout(drawer)
.build();
 NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
//display welcome username
etUsername = findViewById(R.id.welcomeUsername);
 etUsername.setText(username);
 Button button_log_out = findViewById(R.id.button_log_out);
button_log_out.setOnClickListener(new View.OnClickListener() {
 @Override
public void onClick(View v) {
logoutDialog();
}
});
return true;
    }
    @Override
    public boolean onSupportNavigateUp() {
 NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_drawer);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
 || super.onSupportNavigateUp();
}
public void logoutDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("LogOut Alert!");
alertDialog.setMessage("Are you sure want to LogOut this Application?");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
  pref.setLogin("no");
dialog.dismiss();
Intent intent = new Intent(NavigationDrawer.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 dialog.dismiss();
 }
        });
alertDialog.show();
    }
}


问:
Min-max normalization when using tf.data.Dataset
I have a tf.Dataset and I want to perform a minmax normalization, in order to have image values in the range [0,1].

I am interested in knowing how to perform normalization on each image, as well as for the whole batch.

@tf.function def load_images(imagePath):

label = tf.io.read_file(imagePath)

label = tf.image.decode_jpeg(label,
channels=3)

label = tf.image.convert_image_dtype(label,
dtype=tf.float32)

image=label+tf.random.normal(shape=tf.shape(label),mean=0,stddev=0.1**0.5)

return image, label

filenames = glob.glob("/content/mydrive/images/" + "*.jpg")

trainDS = tf.data.Dataset.from_tensor_slices(filenames)
trainDS = (trainDS

.shuffle(len(filenames))

.map(load_images, num_parallel_calls=AUTOTUNE)

.batch(16)

.prefetch(AUTOTUNE) )

Could anyone suggest what is the best way to do that?

P.S. I would expect that a tf.image.per_image_normalization function existed (similar as tf.image.per_image_standardization) but no luck.

答:
You can use tf.keras.layers.Rescaling(1./255) to perform a minmax normalization:

import tensorflow as tf
import pathlib

dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

batch_size = 32

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  batch_size=batch_size)

normalization_layer = tf.keras.layers.Rescaling(1./255)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))

for x, y in normalized_ds.take(1):
  # the pixel values are now in [0,1]
  print(tf.reduce_min(x), tf.reduce_max(x))
```
```tf.Tensor(0.0, shape=(), dtype=float32) tf.Tensor(1.0, shape=(), dtype=float32)
```

If you want to normalize each image separately just change the batch size to 1.

Body:
You can use tf.keras.layers.Rescaling(1./255) to perform a minmax normalization:

import tensorflow as tf
import pathlib

dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

batch_size = 32

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  batch_size=batch_size)

normalization_layer = tf.keras.layers.Rescaling(1./255)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))

for x, y in normalized_ds.take(1):
  # the pixel values are now in [0,1]
  print(tf.reduce_min(x), tf.reduce_max(x))

tf.Tensor(0.0, shape=(), dtype=float32) tf.Tensor(1.0, shape=(), dtype=float32)

If you want to normalize each image separately just change the batch size to 1.


问:
how to tell if a web request is coming from google's crawler?
From the HTTP server's perspective.</p>

答:
You can now perform an IP address check, by checking against googlebot's published IP address list at https://developers.google.com/search/apis/ipranges/googlebot.json

From the docs:

you can identify Googlebot by IP address by matching the crawler's IP address to the list of Googlebot IP addresses. For all other Google crawlers, match the crawler's IP address against the complete list of Google IP addresses.

Body: From the HTTP server's perspective.


问:
how to return int. if int. is in range 10-19?
Here is my code so far. I want to return all sums, but if sum is in range of 10-19, return 20. Thank you! -Learning student</p>
```<code>def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

def find_sum(num1, num2):
    sum = num1 + num2
    if 10 <= sum <= 19:
        print(20)
    print(sum)

main()
</code>```

答:
You can simply use an if - else statement using the range function to determine the range of integers.

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

 def find_sum(num1, num2):
        sum = num1 + num2
        if sum in range(10,20): # [10:20):
                print("20")
        else:
                print(sum)
```

Body:
Here is my code so far. I want to return all sums, but if sum is in range of 10-19, return 20. Thank you! -Learning student

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

def find_sum(num1, num2):
    sum = num1 + num2
    if 10 <= sum <= 19:
        print(20)
    print(sum)

main()


问:
Expand array of map type in pyspark
I have a column with type ArrayType(MapType(StringType, StringType)) and i want to expand in such way that keys present in map type becomes column name and its value(maptype) becomes value's of column.

here is an example:

[[version -> HTTP/1.1], [code -> 400], [reason -> Illegal character VCHAR='.'], [Content-Type -> text/html;charset=iso-8859-1], [Content-Length -> 70], [Connection -> close], [Server -> Jetty(9.4.24.v20191120)], [body -> 3c68313e426164204d65737361676520]]

this is a row which have arrayType() of maptype()

答:
Skip the ArrayType. Use a UDF directly from the json

```<code>from pyspark.sql.types import MapType, StringType

@udf(returnType=MapType(StringType(), StringType()))
def http_flatten(s):
    if s is None:
        return None
    import json
    out = json.loads(s)["http"][0]["out"]
    data = dict()
    for e in out:
        data.update(e)
    return data
</code>```

Then use something like this

```<code>kafka_df.select(
  http_flatten(
    kafka_df.value.cast("string").alias("value")
  ).alias("headers")
)
</code>```

Then select("headers.*") to get those as the top level columns

Title: Expand array of map type in pyspark

Body:
Skip the ArrayType. Use a UDF directly from the json

from pyspark.sql.types import MapType, StringType

@udf(returnType=MapType(StringType(), StringType()))
def http_flatten(s):
    if s is None:
        return None
    import json
    out = json.loads(s)["http"][0]["out"]
    data = dict()
    for e in out:
        data.update(e)
    return data

Then use something like this

kafka_df.select(
  http_flatten(
    kafka_df.value.cast("string").alias("value")
  ).alias("headers")
)

Then select("headers.*") to get those as the top level columns


问:
jQuery: menu bar similar to "tabs" but without changing divs
I'm trying to figure out how to generate tabs like jQuery's tabs plugin, but without the swapping of DIVs. In other words, I'd like a jQuery plugin that just draws the tab bar (and lets me specify which tab is selected). I'll take care of drawing the content and having things happen when tabs are clicked.</p>

答:
All you have to do, is copy the classes that jQuery UI applies to the tabs, and you're all set.

You'll also then add/remove classes dynamically when the user clicks on one of them.

This is actually the way that jQuery UI does it with the tabs.

Here are some sample classes that they use:

```<code>ui-tabs ui-widget ui-widget-content ui-corner-all
</code>```

I got these by inspecting the DOM after the jQuery UI has already applied the tabs functionality. Do the same, and you'll see exactly what classes you need for which elements.

EDIT:

Here's the complete HTML:

```<code><div class="ui-tabs ui-widget ui-widget-content ui-corner-all">
    <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
        <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">The selected tab</a></li>
        <li class="ui-state-default ui-corner-top"><a href="#">Other tabs</a></li>
        <li class="ui-state-default ui-corner-top"><a href="#">Other tabs</a></li>
    </ul>
</div>
</code>```

And here's the Javascript:

```<code>$('.ui-tabs-nav li').mouseenter(function(){
    $(this).addClass('ui-state-hover');
})
.mouseleave(function(){
    $(this).removeClass('ui-state-hover');
})
.click(function(){
    $(this).addClass('ui-tabs-selected ui-state-active')
        .siblings().removeClass('ui-tabs-selected ui-state-active');

    return false;
});
</code>```

And, of course, where would we be without the fiddle: http://jsfiddle.net/Bsa7J/ .

Body:
All you have to do, is copy the classes that jQuery UI applies to the tabs, and you're all set.

You'll also then add/remove classes dynamically when the user clicks on one of them.

This is actually the way that jQuery UI does it with the tabs.

Here are some sample classes that they use:

ui-tabs ui-widget ui-widget-content ui-corner-all

I got these by inspecting the DOM after the jQuery UI has already applied the tabs functionality. Do the same, and you'll see exactly what classes you need for which elements.

EDIT:

Here's the complete HTML:

<div class="ui-tabs ui-widget ui-widget-content ui-corner-all">
    <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
        <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#">The selected tab</a></li>
        <li class="ui-state-default ui-corner-top"><a href="#">Other tabs</a></li>
        <li class="ui-state-default ui-corner-top"><a href="#">Other tabs</a></li>
    </ul>
</div>

And here's the Javascript:

$('.ui-tabs-nav li').mouseenter(function(){
    $(this).addClass('ui-state-hover');
})
.mouseleave(function(){
    $(this).removeClass('ui-state-hover');
})
.click(function(){
    $(this).addClass('ui-tabs-selected ui-state-active')
        .siblings().removeClass('ui-tabs-selected ui-state-active');

    return false;
});

And, of course, where would we be without the fiddle: http://jsfiddle.net/Bsa7J/ .


问:
Transforming 2D image point to 3D world point where Z !=0
the below code transforms a detected 2D-image point to it's 3D location on a defined plane Grid in 3D-world.
This mean Z=0, and taking into account that the Extrinsics and Intrinsics are known, we can compute the corresponding 3D_point of the detected 2D-image point:

```<code>import cv2
import numpy as np

#load extrinsics & intrinsics
with np.load('parameters_cam1.npz') as X:
mtx, dist = [X[i] for i in ('mtx','dist','rvecs','tvecs')]
with np.load('extrincic.npz') as X:
rvecs1,tvecs1 = [X[i] for i in('rvecs1','tvecs1')]

#prepare rotation matrix
R_mtx, jac=cv2.Rodrigues(rvecs1)

#prepare projection matrix
Extrincic=cv2.hconcat([R_mtx,tvecs1])
Projection_mtx=mtx.dot(Extrincic)

#delete the third column since Z=0
Projection_mtx = np.delete(Projection_mtx, 2, 1)

#finding the inverse of the matrix
Inv_Projection = np.linalg.inv(Projection_mtx)

#detected image point (extracted from a que)
img_point=np.array([pts1_blue[0]])

#adding dimension 1 in order for the math to be correct (homogeneous coordinates)
img_point=np.vstack((img_point,np.array(1)))

#calculating the 3D point which located on the 3D plane
3D_point=Inv_Projection.dot(img_point)

#show results
print('3D_pt_method1\n',3D_point)

#output
3D_pt_method1
[[0.01881387]
[0.0259416 ]
[0.04150276]]
</code>```

By normalizing the point (dividing by the third value) the result is

```<code>`X_World=0.45331611680765327 # 45.3 cm from defined world point cm which is correct
 Y_world=0.6250572251098481  # 62.5 cm which is also correct

</code>```

By evaluating the results, it turns out that they are correct.

I now that we can't retrieve the the Z coordinate of the 3D world point since depth information is lost going from 3d to 2d. The following equation also performs the inverse projection of the 2D point onto 3D world and can be found in all literature, and the result is an equation which represents a line on which the 3D_ world point must lie on

I put the equation 3.15 into code, however without setting Z=0, meaning to say with out deleting the third column of the projection matrix like i did in the previous method (Just as it's written) by doing the following the following:

```<code>#inverting the rotation matrix
INV_R=np.linalg.inv(R_mtx)

#inverting the camera matrix
INV_k=np.linalg.inv(mtx)

#multiplying the tow matrices
kinv_Rinv=INV_k.dot(INV_R)

#calcuating the 3D_point X which expressed in eq.3.15
3D_point=kinv_Rinv.dot(img_point)+tvecs1

#print the results
print('3D_pt_method2\n',3D_point)
</code>```

and the result was

```<code>3D_pt_method2 #how should one understand these coordinates ?
[[-9.12505825]
[-5.57152147]
[40.12264881]]
</code>```

My question is, How should i understand or interpret this result? as it doesn't make any sense compared to the previous method where Z=0. the 3D 3x1 resulted vector seems to give an intuition that it's values represents simply the 3D X, Y and Z of the detected image_point. However, this is not true if we compare X and Y with the previous method!!

So what is literally the difference between 3D_pt_method1 and 3D_pt_method2???

I hope i could express my self and really appreciate helping me understand the difference between the two implementations!

Note: the Grid that represents my defined World-plane and can be seen in the below image in which the distance between every two yellow points is 40 cm

Thanks in advance

答:
You miss the key variable "w" in method2.

You can get help from referring to this article: https://blog.csdn.net/zhou4411781/article/details/103876478

This article is written in Chinese, but you can just try to get the point from those formula in that article if you cannot understand Chinese.

Simply speaking:
You said right "I know that we can't retrieve the the Z coordinate of the 3D world point since depth information is lost going from 3d to 2d. "
This also means: If you know the depth (the Z axis value in world coordination), you can get 3d ordinate by 2d ordinate and the depth. As well, if you know the X or Y axis value in world coordination, you can also get the result.

Body:
the below code transforms a detected 2D-image point to it's 3D location on a defined plane Grid in 3D-world.
This mean Z=0, and taking into account that the Extrinsics and Intrinsics are known, we can compute the corresponding 3D_point of the detected 2D-image point:

import cv2
import numpy as np

#load extrinsics & intrinsics
with np.load('parameters_cam1.npz') as X:
mtx, dist = [X[i] for i in ('mtx','dist','rvecs','tvecs')]
with np.load('extrincic.npz') as X:
rvecs1,tvecs1 = [X[i] for i in('rvecs1','tvecs1')]

#prepare rotation matrix
R_mtx, jac=cv2.Rodrigues(rvecs1)

#prepare projection matrix
Extrincic=cv2.hconcat([R_mtx,tvecs1])
Projection_mtx=mtx.dot(Extrincic)

#delete the third column since Z=0
Projection_mtx = np.delete(Projection_mtx, 2, 1)

#finding the inverse of the matrix
Inv_Projection = np.linalg.inv(Projection_mtx)

#detected image point (extracted from a que)
img_point=np.array([pts1_blue[0]])

#adding dimension 1 in order for the math to be correct (homogeneous coordinates)
img_point=np.vstack((img_point,np.array(1)))

#calculating the 3D point which located on the 3D plane
3D_point=Inv_Projection.dot(img_point)

#show results
print('3D_pt_method1\n',3D_point)

#output
3D_pt_method1
[[0.01881387]
[0.0259416 ]
[0.04150276]]

By normalizing the point (dividing by the third value) the result is

`X_World=0.45331611680765327 # 45.3 cm from defined world point cm which is correct
 Y_world=0.6250572251098481  # 62.5 cm which is also correct

By evaluating the results, it turns out that they are correct.

I now that we can't retrieve the the Z coordinate of the 3D world point since depth information is lost going from 3d to 2d. The following equation also performs the inverse projection of the 2D point onto 3D world and can be found in all literature, and the result is an equation which represents a line on which the 3D_ world point must lie on

I put the equation 3.15 into code, however without setting Z=0, meaning to say with out deleting the third column of the projection matrix like i did in the previous method (Just as it's written) by doing the following the following:

#inverting the rotation matrix
INV_R=np.linalg.inv(R_mtx)

#inverting the camera matrix
INV_k=np.linalg.inv(mtx)

#multiplying the tow matrices
kinv_Rinv=INV_k.dot(INV_R)

#calcuating the 3D_point X which expressed in eq.3.15
3D_point=kinv_Rinv.dot(img_point)+tvecs1

#print the results
print('3D_pt_method2\n',3D_point)

and the result was

3D_pt_method2 #how should one understand these coordinates ?
[[-9.12505825]
[-5.57152147]
[40.12264881]]

My question is, How should i understand or interpret this result? as it doesn't make any sense compared to the previous method where Z=0. the 3D 3x1 resulted vector seems to give an intuition that it's values represents simply the 3D X, Y and Z of the detected image_point. However, this is not true if we compare X and Y with the previous method!!

So what is literally the difference between 3D_pt_method1 and 3D_pt_method2???

I hope i could express my self and really appreciate helping me understand the difference between the two implementations!

Note: the Grid that represents my defined World-plane and can be seen in the below image in which the distance between every two yellow points is 40 cm

Thanks in advance


答:
You can use an if else statement and the range keyword to see if "sum" is in 10 - 19</p>
```<code>def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

 def find_sum(num1, num2):
        sum = num1 + num2
        if sum not in range(10, 20) # I included 19 too
            print(sum)
        else:
            print("20") # Prints 20 if the sum is with 10 and 19 (19 included)
</code>```

Title: how to return int. if int. is in range 10-19?

Body:
You can use an if else statement and the range keyword to see if "sum" is in 10 - 19

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)

 def find_sum(num1, num2):
        sum = num1 + num2
        if sum not in range(10, 20) # I included 19 too
            print(sum)
        else:
            print("20") # Prints 20 if the sum is with 10 and 19 (19 included)