问:
Devise Confirmation email is being to sent to mail, How to prevent user from login if they don't confirm mail?
I am using devise.
Before I was able to login without email confirmation.
Then I had to setup email confirmation for my application.
So I added    confirmable on    user.rb and made changes on devise user migration.
Also, I made changes on    devise.rb file.
Also I did setup for mailer as    smtp on    config/environment/development.rb file.

I think setup is correct for mailer but the problem is that:
When user signs up as new user, mail with confirmation token will goes to that user. But even without clicking that mail link User is able to login.
What is the use of setup for mailer if user can login without confirmation token?
How to prevent user from logging if they don't verify mail confirmation token?

I have tired making customized    confirmable controller but result is same.

application_controller.rb

```<code># frozen_string_literal: true

# Router entry point
require 'json_web_token'
class ApplicationController < ActionController::Base
    before_action :configure_permitted_parameters, if: :devise_controller?
    before_action :make_action_mailer_use_request_host_and_protocol
    # before_action :authenticate_user!, :set_mailer_host
    protect_from_forgery with: :exception

    respond_to :html, :json

    def index
        render template: 'application'
    end

    def not_found
        render json: { error: 'not_found' }
    end

    def authorize_request
        header = request.headers['Authorization']
        header = header.split(' ').last if header
        begin
        @decoded = JsonWebToken.decode(header)
        @current_user = User.find(@decoded[:user_id])
        rescue ActiveRecord::RecordNotFound => e
        render json: { errors: e.message }, status: :unauthorized
        rescue JWT::DecodeError => e
        render json: { errors: e.message }, status: :unauthorized
        end
    end

    protected

    def current_user
        @current_user ||= User.find_by(id: session[:user_id])
    end

    def signed_in?
        !!current_user
    end
    helper_method :current_user, :signed_in?

    def current_user=(user)
        session[:user_id] = user&.id
        @current_user = user
    end

    def configure_permitted_parameters
        update_attrs = [:password, :password_confirmation, :current_password]
        devise_parameter_sanitizer.permit :account_update, keys: update_attrs
        devise_parameter_sanitizer.permit(:login, keys: [ :email, :password ])
    end

    private

    def make_action_mailer_use_request_host_and_protocol
        ActionMailer::Base.default_url_options[:protocol] = request.protocol
        ActionMailer::Base.default_url_options[:host] = request.host_with_port
    end
end
</code>```

authorization_controller.rb

```<code>module Api
    module V1
        class AuthenticationController < ApplicationController
            skip_before_action :verify_authenticity_token
            before_action :authorize_request, except: :login

            # POST /auth/login
            def login
                @user = User.find_by_email(params[:email])
                if @user&.valid_password?(params[:password])
                token = JsonWebToken.encode(user_id: @user.id)
                time = Time.now + 24.hours.to_i
                render json: { token: token, exp: time.strftime("%m-%d-%Y %H:%M"),
                                username: @user.username, user_id: @user.id }, status: :ok
                else
                render json: { error: 'unauthorized' }, status: :unauthorized
                end
            end

            private

            def login_params
                params.permit(:email, :password)
            end
        end
    end
end
</code>```

users_controller.rb

```<code>module Api
    module V1
        class UsersController < ApplicationController
            skip_before_action :verify_authenticity_token

            before_action :authorize_request, except: :create

            # GET /users
            def index
                @users = User.all
                render json: @users, status: :ok
            end

            def create
                # render plain: params.inspect
                @user = User.new(user_params)
                # render plain: user_params.insp
                if @user.save
                    render json: @user, status: :created
                else
                    render json: { errors: @user.errors.full_messages },
                        status: :unprocessable_entity
                end
            end

            def update
                user = User.find(params[:id])
                if user.update(user_params)
                render json: user, status: :created
                else
                render json: { errors: user.errors.full_messages },
                        status: :unprocessable_entity
                end
            end

            def show
                user = User.find(params[:id])
                if !user.nil?
                    render json: user, status: :ok
                else
                    render json: {errors: user.errors.full_messages}, status: :unprocessable_entity
                end
            end

            def destroy
                user = User.find(params[:id])
                if user.destroy
                    render json: {success: "deleted successfully"}, status: :ok
                else
                    render json: {errors: user.errors.full_messages}, status: :not_acceptable
                end
            end

            private

            def find_user
                @user = User.find_by_username!(params[:_username])
                rescue ActiveRecord::RecordNotFound
                render json: { errors: 'User not found' }, status: :not_found
            end

            def user_params
                params.permit(
                    :first_name, :last_name, :username, :email, :password, :password_confirmation
                )
            end
        end
    end
end
</code>```

registrations_controller.rb

```<code>class RegistrationsController < Devise::RegistrationsController
    skip_before_action :require_no_authentication
    def update_resource(resource, params)
        if resource.encrypted_password.blank?
            resource.email = params[:email] if params[:email]
            if !params[:password].blank? && params[:password] == params[:password_confirmation]
                resource.password = params[:password]
                resource.save
            end
            if resource.valid?
            resource.update_without_password(params)
            end
        else
            resource.update_with_password(params)
        end
    end
end
</code>```

user.rb

```<code>class User < ApplicationRecord
    # has_secure_password
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable,
        :confirmable, :omniauthable, password_length: 8..36
    has_many :identities
    has_one :testimonials
    has_many :questions
    has_many :answers

    def facebook
        identities.where(provider: 'facebook').first
    end

    def facebook_client
        @facebook_client ||= Facebook.client(access_token: facebook.accesstoken)
    end

    def twitter
        identities.where(provider: 'twitter').first
    end

    def twitter_client
        @twitter_client ||= Twitter.client(access_token: twitter.accesstoken)
    end

    def google_oauth2
        identities.where(provider: 'google_oauth2').first
    end

    def google_oauth2_client
        unless @google_oauth2_client
        @google_oauth2_client = Google::APIClient.new(application_name: '',
                                                        application_version: '')
        @google_oauth2_client.authorization.update_token!(access_token: google_oauth2.accesstoken,
                                                            refresh_token: google_oauth2.refreshtoken)
        end
        @google_oauth2_client
    end

    #validation for users
    validates :username, presence: true, uniqueness: {case_sensitive: false}

    # validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
    validates :email, presence: true, uniqueness: {case_senstive: false}
    PASSWORD_FORMAT = /\A
        (?=.{8,})          # Must contain 8 or more characters
        (?=.*\d)           # Must contain a digit
        (?=.*[a-z])        # Must contain a lower case character
        (?=.*[A-Z])        # Must contain an upper case character
        (?=.*[[:^alnum:]]) # Must contain a symbol
        /x

    validates :password,
        presence: true,
        # length: { in: Devise.password_length },
        format: { with: PASSWORD_FORMAT, message: 'must contain 8 Characters with at least One Lowercase, One Uppercase, One Number and One Special Character' },
        confirmation: true,
        on: :create

        validates :password_confirmation,
        presence: true

    validates :password,
        # allow_nil: true,
        # length: { in: Devise.password_length },
        format: { with: PASSWORD_FORMAT, message: 'must contain 8 Characters with at least one Uppercase, One Number and One Special Character' },
        confirmation: true,
        on: :update

end
</code>```

答:
Take a look at your devise initializer, you need to set allow_unconfirmed_access_for to 0 (actually, it should be zero by default). According to devise documentation:

```<code>#   * +allow_unconfirmed_access_for+: the time you want to allow the user to access their account
#     before confirming it. After this period, the user access is denied. You can
#     use this to let your user access some features of your application without
#     confirming the account, but blocking it after a certain period (ie 7 days).
#     By default allow_unconfirmed_access_for is zero, it means users always have to confirm to sign in.
</code>```

Devise is using this method to verify unconfirmed access.

Could you also post the results of this methods:

User.find(id_of_user_that_was_just_created).confirmation_required?

User.find(id_of_user_that_was_just_created).confirmed?

User.find(id_of_user_that_was_just_created).confirmation_period_valid?

Body:
I am using devise.
Before I was able to login without email confirmation.
Then I had to setup email confirmation for my application.
So I added    confirmable on    user.rb and made changes on devise user migration.
Also, I made changes on    devise.rb file.
Also I did setup for mailer as    smtp on    config/environment/development.rb file.

I think setup is correct for mailer but the problem is that:
When user signs up as new user, mail with confirmation token will goes to that user. But even without clicking that mail link User is able to login.
What is the use of setup for mailer if user can login without confirmation token?
How to prevent user from logging if they don't verify mail confirmation token?

I have tired making customized    confirmable controller but result is same.

application_controller.rb

# frozen_string_literal: true

# Router entry point
require 'json_web_token'
class ApplicationController < ActionController::Base
    before_action :configure_permitted_parameters, if: :devise_controller?
    before_action :make_action_mailer_use_request_host_and_protocol
    # before_action :authenticate_user!, :set_mailer_host
    protect_from_forgery with: :exception

    respond_to :html, :json

    def index
        render template: 'application'
    end

    def not_found
        render json: { error: 'not_found' }
    end

    def authorize_request
        header = request.headers['Authorization']
        header = header.split(' ').last if header
        begin
        @decoded = JsonWebToken.decode(header)
        @current_user = User.find(@decoded[:user_id])
        rescue ActiveRecord::RecordNotFound => e
        render json: { errors: e.message }, status: :unauthorized
        rescue JWT::DecodeError => e
        render json: { errors: e.message }, status: :unauthorized
        end
    end

    protected

    def current_user
        @current_user ||= User.find_by(id: session[:user_id])
    end

    def signed_in?
        !!current_user
    end
    helper_method :current_user, :signed_in?

    def current_user=(user)
        session[:user_id] = user&.id
        @current_user = user
    end

    def configure_permitted_parameters
        update_attrs = [:password, :password_confirmation, :current_password]
        devise_parameter_sanitizer.permit :account_update, keys: update_attrs
        devise_parameter_sanitizer.permit(:login, keys: [ :email, :password ])
    end

    private

    def make_action_mailer_use_request_host_and_protocol
        ActionMailer::Base.default_url_options[:protocol] = request.protocol
        ActionMailer::Base.default_url_options[:host] = request.host_with_port
    end
end

authorization_controller.rb

module Api
    module V1
        class AuthenticationController < ApplicationController
            skip_before_action :verify_authenticity_token
            before_action :authorize_request, except: :login

            # POST /auth/login
            def login
                @user = User.find_by_email(params[:email])
                if @user&.valid_password?(params[:password])
                token = JsonWebToken.encode(user_id: @user.id)
                time = Time.now + 24.hours.to_i
                render json: { token: token, exp: time.strftime("%m-%d-%Y %H:%M"),
                                username: @user.username, user_id: @user.id }, status: :ok
                else
                render json: { error: 'unauthorized' }, status: :unauthorized
                end
            end

            private

            def login_params
                params.permit(:email, :password)
            end
        end
    end
end

users_controller.rb

module Api
    module V1
        class UsersController < ApplicationController
            skip_before_action :verify_authenticity_token

            before_action :authorize_request, except: :create

            # GET /users
            def index
                @users = User.all
                render json: @users, status: :ok
            end

            def create
                # render plain: params.inspect
                @user = User.new(user_params)
                # render plain: user_params.insp
                if @user.save
                    render json: @user, status: :created
                else
                    render json: { errors: @user.errors.full_messages },
                        status: :unprocessable_entity
                end
            end

            def update
                user = User.find(params[:id])
                if user.update(user_params)
                render json: user, status: :created
                else
                render json: { errors: user.errors.full_messages },
                        status: :unprocessable_entity
                end
            end

            def show
                user = User.find(params[:id])
                if !user.nil?
                    render json: user, status: :ok
                else
                    render json: {errors: user.errors.full_messages}, status: :unprocessable_entity
                end
            end

            def destroy
                user = User.find(params[:id])
                if user.destroy
                    render json: {success: "deleted successfully"}, status: :ok
                else
                    render json: {errors: user.errors.full_messages}, status: :not_acceptable
                end
            end

            private

            def find_user
                @user = User.find_by_username!(params[:_username])
                rescue ActiveRecord::RecordNotFound
                render json: { errors: 'User not found' }, status: :not_found
            end

            def user_params
                params.permit(
                    :first_name, :last_name, :username, :email, :password, :password_confirmation
                )
            end
        end
    end
end

registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
    skip_before_action :require_no_authentication
    def update_resource(resource, params)
        if resource.encrypted_password.blank?
            resource.email = params[:email] if params[:email]
            if !params[:password].blank? && params[:password] == params[:password_confirmation]
                resource.password = params[:password]
                resource.save
            end
            if resource.valid?
            resource.update_without_password(params)
            end
        else
            resource.update_with_password(params)
        end
    end
end

user.rb

class User < ApplicationRecord
    # has_secure_password
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable
    devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable,
        :confirmable, :omniauthable, password_length: 8..36
    has_many :identities
    has_one :testimonials
    has_many :questions
    has_many :answers

    def facebook
        identities.where(provider: 'facebook').first
    end

    def facebook_client
        @facebook_client ||= Facebook.client(access_token: facebook.accesstoken)
    end

    def twitter
        identities.where(provider: 'twitter').first
    end

    def twitter_client
        @twitter_client ||= Twitter.client(access_token: twitter.accesstoken)
    end

    def google_oauth2
        identities.where(provider: 'google_oauth2').first
    end

    def google_oauth2_client
        unless @google_oauth2_client
        @google_oauth2_client = Google::APIClient.new(application_name: '',
                                                        application_version: '')
        @google_oauth2_client.authorization.update_token!(access_token: google_oauth2.accesstoken,
                                                            refresh_token: google_oauth2.refreshtoken)
        end
        @google_oauth2_client
    end

    #validation for users
    validates :username, presence: true, uniqueness: {case_sensitive: false}

    # validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
    validates :email, presence: true, uniqueness: {case_senstive: false}
    PASSWORD_FORMAT = /\A
        (?=.{8,})          # Must contain 8 or more characters
        (?=.*\d)           # Must contain a digit
        (?=.*[a-z])        # Must contain a lower case character
        (?=.*[A-Z])        # Must contain an upper case character
        (?=.*[[:^alnum:]]) # Must contain a symbol
        /x

    validates :password,
        presence: true,
        # length: { in: Devise.password_length },
        format: { with: PASSWORD_FORMAT, message: 'must contain 8 Characters with at least One Lowercase, One Uppercase, One Number and One Special Character' },
        confirmation: true,
        on: :create

        validates :password_confirmation,
        presence: true

    validates :password,
        # allow_nil: true,
        # length: { in: Devise.password_length },
        format: { with: PASSWORD_FORMAT, message: 'must contain 8 Characters with at least one Uppercase, One Number and One Special Character' },
        confirmation: true,
        on: :update

end

Body:
Take a look at your devise initializer, you need to set allow_unconfirmed_access_for to 0 (actually, it should be zero by default). According to devise documentation:

#   * +allow_unconfirmed_access_for+: the time you want to allow the user to access their account
#     before confirming it. After this period, the user access is denied. You can
#     use this to let your user access some features of your application without
#     confirming the account, but blocking it after a certain period (ie 7 days).
#     By default allow_unconfirmed_access_for is zero, it means users always have to confirm to sign in.

Devise is using this method to verify unconfirmed access.

Could you also post the results of this methods:

User.find(id_of_user_that_was_just_created).confirmation_required?

User.find(id_of_user_that_was_just_created).confirmed?

User.find(id_of_user_that_was_just_created).confirmation_period_valid?


来源: stackexchange

问:
How can I trigger the dropdown from within a component
I'm building an angular application where the user should be able to right-click the canvas (this covers most of the page) and see a context menu. I've been using the ngx-bootstrap dropdown for the main menu of the app and want to use the same module for this context menu.
The demo of this dropdown menu shows a manual toggle using a button with

```<code><button type="button" class="btn btn-primary" (onclick)="dropdown.toggle(true);">Toggle</button>
</code>```

If I try this:
Component.html

```<code><div id="canvas" (contextmenu)="handleRightClick($event)">
</div>
</code>```

Component.ts

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'app-my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent {
    constructor() {
    }
    handleRightClick(e) {
        dropdown.toggle(true);
    }
}
</code>```

When right clicking the canvas I get an error:

```<code>ReferenceError: dropdown is not defined
</code>```

The fact that I get the error does not surprise me. I did not declare this "dropdown" variable anywhere. My question is: how do I get access to this dropdown from Component.ts

答:
You need to add a template variable to a dropdown directive #dropdown="bs-dropdown" and this variable will work in the template, but if you need to manage dropdown's state from component's code you have to use @ViewChild to get a reference to a dropdown and it will look somewhat like this @ViewChild('dropdown') dropdown: BsDropdownDirective;

here's an example - https://stackblitz.com/edit/angular-gnvgjn

ContentLicense: CC BY-SA 4.0

Body:
I'm building an angular application where the user should be able to right-click the canvas (this covers most of the page) and see a context menu. I've been using the ngx-bootstrap dropdown for the main menu of the app and want to use the same module for this context menu.
The demo of this dropdown menu shows a manual toggle using a button with

<button type="button" class="btn btn-primary" (onclick)="dropdown.toggle(true);">Toggle</button>

If I try this:
Component.html

Component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent {
    constructor() {
    }
    handleRightClick(e) {
        dropdown.toggle(true);
    }
}

When right clicking the canvas I get an error:

ReferenceError: dropdown is not defined

The fact that I get the error does not surprise me. I did not declare this "dropdown" variable anywhere. My question is: how do I get access to this dropdown from Component.ts


问:
How to disable copy on a JTable
First of all I have to say that I never worked on java application.

I've been asked to prevent the possibility the user copy (ctrl+c or right click of the mouse) the content of JTable/JLabel (I didn't developed this java application).

I can't disable JTable or JLabel since the user must be allowed to edit them. I just need to disable the copy function on JLabel and/or JLabel.

What's the easiest way?
I read some posts on the internet but I didn't understand much since I never worked on Java application.

Thank you

答:
You can disable the "Ctrl+C" Key Binding on the JTable by using:</p>

```<code>InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke("control C"), "none");
</code>```

Title: How to disable copy on a JTable

Body:
You can disable the "Ctrl+C" Key Binding on the JTable by using:

InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke("control C"), "none");


问:
Amazon Fire TV Remote Not Pausing ExoPlayer When Controls Hidden
I'm working on an Android library which is just a simple video player wrapping ExoPlayer. When using an Amazon Fire TV I can navigate my app using the remote (the directional pad switches between elements in my view) and I can control the player (the play/pause button will toggle the playing state and the seek buttons work as intended).... so long as the control bar is visible

After 3 seconds or so the control bar auto-hides, and the remote control becomes non-responsive

Is there an appropriate fix for this, or do I need to manually detect key presses on the remote and show the control bar? I feel like this is the kind of thing Amazon's port of ExoPlayer should have resolved

Update

I extended the PlayerView class and overrode the dispatchKeyEvent method to see what was being seen:

```<code>public class Test extends PlayerView {
    @Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        Log.debug("***** KEY EVENT: " + String.valueOf(event.getKeyCode()) + " *********");
        return true;
    }
}
</code>```

Doing this and pressing the play button on the remote I noticed:

When the control bar was visible, a KeyEvent with a keyCode value of 85 was dispatched

When the control bar was hidden, this method never triggered

I skimmed through the methods available to PlayerView to see if any were helpful, but nothing seemed worthwhile:

setControllerAutoShow - determines if control bar is shown when video first starts

setControllerHideDuringAds - determines if the control bar is visible while an ad is playing

setControllerHideOnTouch - irrelevant on FireTV (no touch events) but hides the control bar if you tap the video

setControllerHideTimeoutMs - can delay the hiding of the control bar, but otherwise doesn't let me bring it back after it's hidden

showController - can forcibly reveal the controller in code, allowing me to pause the video, but I without being able to see keyup events I can't properly call this when a button is pressed on the remote control

Ultimately I just want this to behave like the Netflix or Hulu apps -- the control bar goes away after a few seconds of inactivity but if you press the pause button the control bar comes back.

答:
I've found an answer, but it's not exactly a beautiful one. For some reason (I still want to know why, and if someone could explain why then I would gladly accept their answer over mine) when the control bar disappears the PlayerView loses focus, and keyboard events are no longer sent to it. However all keyboard events are still seen by the Activity hosting the PlayerView. So I added the following to my Activity:

```<code>    @Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        playerView.dispatchKeyEvent(event);
        return true;
    }
</code>```

Now whether the control bar is visible or not, the player still responds to all key events. However:

This requires editing the activity, which means anyone using my player library will need to know about this extra step to integrate the player properly

This does not explain why the player is losing focus, it merely circumvents the issue

Body:
I'm working on an Android library which is just a simple video player wrapping ExoPlayer. When using an Amazon Fire TV I can navigate my app using the remote (the directional pad switches between elements in my view) and I can control the player (the play/pause button will toggle the playing state and the seek buttons work as intended).... so long as the control bar is visible

After 3 seconds or so the control bar auto-hides, and the remote control becomes non-responsive

Is there an appropriate fix for this, or do I need to manually detect key presses on the remote and show the control bar? I feel like this is the kind of thing Amazon's port of ExoPlayer should have resolved

Update

I extended the PlayerView class and overrode the dispatchKeyEvent method to see what was being seen:

public class Test extends PlayerView {
    @Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        Log.debug("***** KEY EVENT: " + String.valueOf(event.getKeyCode()) + " *********");
        return true;
    }
}

Doing this and pressing the play button on the remote I noticed:

When the control bar was visible, a KeyEvent with a keyCode value of 85 was dispatched

When the control bar was hidden, this method never triggered

I skimmed through the methods available to PlayerView to see if any were helpful, but nothing seemed worthwhile:

setControllerAutoShow - determines if control bar is shown when video first starts

setControllerHideDuringAds - determines if the control bar is visible while an ad is playing

setControllerHideOnTouch - irrelevant on FireTV (no touch events) but hides the control bar if you tap the video

setControllerHideTimeoutMs - can delay the hiding of the control bar, but otherwise doesn't let me bring it back after it's hidden

showController - can forcibly reveal the controller in code, allowing me to pause the video, but I without being able to see keyup events I can't properly call this when a button is pressed on the remote control

Ultimately I just want this to behave like the Netflix or Hulu apps -- the control bar goes away after a few seconds of inactivity but if you press the pause button the control bar comes back.

Body:
I've found an answer, but it's not exactly a beautiful one. For some reason (I still want to know why, and if someone could explain why then I would gladly accept their answer over mine) when the control bar disappears the PlayerView loses focus, and keyboard events are no longer sent to it. However all keyboard events are still seen by the Activity hosting the PlayerView. So I added the following to my Activity:

    @Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        playerView.dispatchKeyEvent(event);
        return true;
    }

Now whether the control bar is visible or not, the player still responds to all key events. However:

This requires editing the activity, which means anyone using my player library will need to know about this extra step to integrate the player properly

This does not explain why the player is losing focus, it merely circumvents the issue


问:
Convert financial year and financial quarter into year month
I've got 2 columns in a table, Financial_Year and Financial_Quarter.  An example of the data is as follows:

```<code>Financial_Year  Financial_Quarter
2018/2019         2
</code>```

I want to produce a third column called 'Year_month' which is the last month of the quarter within each financial year, so in the above example I want the year_month column to read 201809.

Has anyone got any hints how to do this in Oracle SQL?

答:
Assuming the FINANCIAL_YEAR column is a string (two numbers separated by slash) and the financial year 2018/2019 begins on 1 April 2018 and ends on 31 March 2019, you could do something like this:

```<code>with
  test_data (financial_year, financial_quarter) as (
    select '2018/2019', 1 from dual union all
    select '2018/2019', 2 from dual union all
    select '2018/2019', 3 from dual union all
    select '2018/2019', 4 from dual
  )
select financial_year, financial_quarter,
       to_char(add_months(to_date(substr(financial_year, 1, 4) || '03', 'yyyymm'),
                          3 * financial_quarter), 'yyyymm') as year_month
from   test_data
;

FINANCIAL_YEAR  FINANCIAL_QUARTER  YEAR_MONTH
--------------  -----------------  ----------
2018/2019                       1  201806
2018/2019                       2  201809
2018/2019                       3  201812
2018/2019                       4  201903
</code>```

Also, just for fun, here is a different solution that doesn't use any date computations - it's all string based.

```<code>select financial_year, financial_quarter,
       substr(financial_year, decode(financial_quarter, 4, 6, 1), 4) ||
       decode(financial_quarter, 1, '06', 2, '09', 3, '12', 4, '03') as year_month
from   test_data
;
</code>```

Body:
I've got 2 columns in a table, Financial_Year and Financial_Quarter.  An example of the data is as follows:

Financial_Year  Financial_Quarter
2018/2019         2

I want to produce a third column called 'Year_month' which is the last month of the quarter within each financial year, so in the above example I want the year_month column to read 201809.

Has anyone got any hints how to do this in Oracle SQL?

Body:
Assuming the FINANCIAL_YEAR column is a string (two numbers separated by slash) and the financial year 2018/2019 begins on 1 April 2018 and ends on 31 March 2019, you could do something like this:

with
  test_data (financial_year, financial_quarter) as (
    select '2018/2019', 1 from dual union all
    select '2018/2019', 2 from dual union all
    select '2018/2019', 3 from dual union all
    select '2018/2019', 4 from dual
  )
select financial_year, financial_quarter,
       to_char(add_months(to_date(substr(financial_year, 1, 4) || '03', 'yyyymm'),
                          3 * financial_quarter), 'yyyymm') as year_month
from   test_data
;

FINANCIAL_YEAR  FINANCIAL_QUARTER  YEAR_MONTH
--------------  -----------------  ----------
2018/2019                       1  201806
2018/2019                       2  201809
2018/2019                       3  201812
2018/2019                       4  201903

Also, just for fun, here is a different solution that doesn't use any date computations - it's all string based.

select financial_year, financial_quarter,
       substr(financial_year, decode(financial_quarter, 4, 6, 1), 4) ||
       decode(financial_quarter, 1, '06', 2, '09', 3, '12', 4, '03') as year_month
from   test_data
;


问:
Run A function when user registered
I have two kinds of login form i.e. one as "individual" and the other as "entity". So when a user registered as entity, then only I want to run a function which will display "minimum product size as 1 m",otherwise for individual users it will show 10m and any user who has not registered, it also should show 10m.
(Here, the minimum product size is minimum product size a user can order)</p>

```<code>function quantityForEntity() {
  var smv = order_selection.options[order_selection.selectedIndex].value;

  if (customer[note][type] != blank) {
    if (smv == "Sampling") {
      productQtySelector.setAttribute("value", "1");
      productQtySelector.setAttribute("min", "1");
      if (sampleOnlytext != null) {
        sampleOnlytext.style.display = "block";
        samplingPrice.style.display = "block";
      }
    }
  } else {
    if (sampleOnlytext != null) {
      sampleOnlytext.style.display = "none";
      samplingPrice.style.display = "none";
    }
  }
}
</code>```

答:
If you hope to access the customer information, then you had best be using some Liquid. So for your purposes, you could at least run this before your JS code.

```<code>{% if customer %}
   var customer = {{customer | json}};
{% endif %}
</code>```

Note that this might not prove super useful, if you cannot see the note assigned to the customer from Shopify.

Also, you can do all this in pure Liquid and avoid all this messy Javascript since you have the customer and any related info on them in Liquid. So you'd setup all those rules in Liquid so that even before rendering the HTML it would be correct. Make your life easier. Do the right thing!

Title: Run A function when user registered

Body:
I have two kinds of login form i.e. one as "individual" and the other as "entity". So when a user registered as entity, then only I want to run a function which will display "minimum product size as 1 m",otherwise for individual users it will show 10m and any user who has not registered, it also should show 10m.
(Here, the minimum product size is minimum product size a user can order)

function quantityForEntity() {
  var smv = order_selection.options[order_selection.selectedIndex].value;

  if (customer[note][type] != blank) {
    if (smv == "Sampling") {
      productQtySelector.setAttribute("value", "1");
      productQtySelector.setAttribute("min", "1");
      if (sampleOnlytext != null) {
        sampleOnlytext.style.display = "block";
        samplingPrice.style.display = "block";
      }
    }
  } else {
    if (sampleOnlytext != null) {
      sampleOnlytext.style.display = "none";
      samplingPrice.style.display = "none";
    }
  }
}

Body:
If you hope to access the customer information, then you had best be using some Liquid. So for your purposes, you could at least run this before your JS code.

{% if customer %}
   var customer = {{customer | json}};
{% endif %}

Note that this might not prove super useful, if you cannot see the note assigned to the customer from Shopify.

Also, you can do all this in pure Liquid and avoid all this messy Javascript since you have the customer and any related info on them in Liquid. So you'd setup all those rules in Liquid so that even before rendering the HTML it would be correct. Make your life easier. Do the right thing!


问:
Get JSON to HTML JavaScript table
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

```<code>{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}
</code>```

Table like this:

```<code>| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....
</code>```

答:
Here is a short example which can help you to understand the principle and then tune it to suit your needs.

const source = {
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  }
}

const keys = Object.keys(source); // get the names properly
const colNames = Object.keys(source[keys[0]]); // get all column names

// Let's form table and header first
const table = document.createElement('table');
const header = document.createElement('tr');
header.innerHTML = `<th>name</th>`
header.innerHTML += colNames.map(name => `<th>${name}</th>`).join('');
table.appendChild(header);

// Now lets append all the rows
const rows = keys.map((key) => {
  const tr = document.createElement('tr');
  tr.innerHTML = `<td>${key}</td>`
  tr.innerHTML += colNames.map(name => `<td>${source[key][name]}</td>`).join('');
  return tr;
});

rows.forEach(r => table.appendChild(r));

// render
document.body.appendChild(table);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td, th {
  width: 120px;
  border: 1px solid black;
}</code>```

Title: Get JSON to HTML JavaScript table

Body:
I created a new category as the main table list table. the question is how to insert this JSON data into the JavaScript HTML table with the format below:

{
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  },
  .....
}

Table like this:

| Name | Count | Time | Language | Diag |
-------------------------------------------------------------
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 |
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....

Body:
Here is a short example which can help you to understand the principle and then tune it to suit your needs.

const source = {
  query: {
    count: 10,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  test1: {
    count: 16,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  bold: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  },
  home: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US"
  }
}

const keys = Object.keys(source); // get the names properly
const colNames = Object.keys(source[keys[0]]); // get all column names

// Let's form table and header first
const table = document.createElement('table');
const header = document.createElement('tr');
header.innerHTML = `<th>name</th>`
header.innerHTML += colNames.map(name => `<th>${name}</th>`).join('');
table.appendChild(header);

// Now lets append all the rows
const rows = keys.map((key) => {
  const tr = document.createElement('tr');
  tr.innerHTML = `<td>${key}</td>`
  tr.innerHTML += colNames.map(name => `<td>${source[key][name]}</td>`).join('');
  return tr;
});

rows.forEach(r => table.appendChild(r));

// render
document.body.appendChild(table);

td, th {
  width: 120px;
  border: 1px solid black;
}


问:
How to concat a calculation and use leading '0' in a view
I have a question about concat function an dleading '0' in a view.
the code I used in the view is:

```<code>SELECT DATEPART(ISO_WEEK, GETDATE()) + 1 AS Week, YEAR(CURRENT_TIMESTAMP) % 2000 % 100 AS Year
</code>```

This gives me the correct result.
I would preferably want to have the data that is now spread over 2 columns in the same column.

Also it would be great to have a leading '0' when the result of 'Week' is a sigle digit.

Everything i tried gave an error.

Thanks for your help,

Kind regards

I expect output of (column1: '9') and (column2: '19') to be (column1: '0919')

答:
Try:

```<code>SELECT
   DATEPART(ISO_WEEK, GETDATE()) + 1 AS Week,
   YEAR(CURRENT_TIMESTAMP) % 2000 % 100 AS Year,
   RIGHT('00'+CAST(DATEPART(ISO_WEEK, '2/1/2019') + 1 AS VARCHAR(2)),2) +
      CAST(YEAR('3/1/2019') % 100 AS VARCHAR(2)) AS Combined
</code>```

I replaced  GETDATE with a constant so it is easier to test.

Body:
I have a question about concat function an dleading '0' in a view.
the code I used in the view is:

SELECT DATEPART(ISO_WEEK, GETDATE()) + 1 AS Week, YEAR(CURRENT_TIMESTAMP) % 2000 % 100 AS Year

This gives me the correct result.
I would preferably want to have the data that is now spread over 2 columns in the same column.

Also it would be great to have a leading '0' when the result of 'Week' is a sigle digit.

Everything i tried gave an error.

Thanks for your help,

Kind regards

I expect output of (column1: '9') and (column2: '19') to be (column1: '0919')

Body:
Try:

SELECT
   DATEPART(ISO_WEEK, GETDATE()) + 1 AS Week,
   YEAR(CURRENT_TIMESTAMP) % 2000 % 100 AS Year,
   RIGHT('00'+CAST(DATEPART(ISO_WEEK, '2/1/2019') + 1 AS VARCHAR(2)),2) +
      CAST(YEAR('3/1/2019') % 100 AS VARCHAR(2)) AS Combined

I replaced  GETDATE with a constant so it is easier to test.


问:
How to use the push property of an empty array?
I'm getting the "Property 'push' dos not exist on type '{}'." error, this is my code:

```<code>  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }
</code>```

How can I solve this?

This is the code of the whole file:

```<code>import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}
</code>```

答:
```<code>messages: string[] = [];
</code>```

is wrongly declared try something like

```<code>var message = [];
</code>```

Body:
I'm getting the "Property 'push' dos not exist on type '{}'." error, this is my code:

  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

How can I solve this?

This is the code of the whole file:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}

Body:
messages: string[] = [];

is wrongly declared try something like

var message = [];


问:
sql server connection not showing up
I have mysql installed (including the connector for .net) and visual studio 2019 installed but when I try to connect via the one of the connections I have on the work bench by entering the name (it doesnt show up on the dropdown) I get the following error: server was not found or not accessible

here is the relevant server information

here a few other stack overflow related questions I found but none of them were helping me:

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

SQL Server is not showing in Visual Studio

How do I ensure Remote connections are allowed?

Also I have visual studio 2019 which meant I couldn't download the special mysql toolbar but does that mean it won't work at all with visual studio 2019?

答:
You have 2 pictures in your post, in the first you try to connect to SQL Server, not to MySQL.

Your second image says that MySQL connection was made.

So I imagine that you need to connect to MySQL, not to SQL Server, so you should not choose Data Provider for SQL Server, but any driver for MySQL

Title: sql server connection not showing up


问:
Issues with Swing timers
I have 3 timers running on my application which takes care of different action. Timer 1 will deals with automatic logout of the application, timer 2 deals with updating a table, timer 3 deals with updating the color of swing buttons. First timer uses the calculation based on the variables and its values, second and third timers works out of MYSQL queries.

Now when i run this application on an average performance machine the application is not moving .I need to wait for few seconds to a normal click to happen or a window to open. Is it something to do with the timers ? If yes do I have any alternative suggestions to get rid of this timer problem?

答: From what I remember, swing timers fire events on the same thread used for rendering, so you dont tend to get exceptions due to incorrect thread interractions - I have used them in the past for animations without issue - I suspect the answer lies elsewhere in your code. Have you tried profiling the code at the point where you are having an issue?</p>

ContentLicense: CC BY-SA 3.0

Title: Issues with Swing timers


问:
Loop creating infinite grep process
I have coded a bash script to not show certain port when someone uses netstat. I have placed it in .bashrc file.

function test(){
    if [ ! -n "$1" ]; then
       netstat | grep -v 1111;
    else
       netstat "$1" | grep -v 1111;
    fi
}
alias netstat='test'
```

When executed, sometimes when executing netstat | grep 1111 (not always and it is not possible to specify in which situations) it creates an infinite number of grep processes.

The expected result is to return netstat output without the filtered port.

答:
There's no need for an alias, and you can use the command command to differentiate between your function netstat and the "real" command netstat.

```<code>netstat () {
    if [ -z "$1" ]; then
        command netstat
    else
        command netstat "$1"
    fi | grep -v 1111
}
</code>```

If your actual intention is to determine if there is an argument, rather than simply a non-empty argument (i.e., differentiate between netstat and netstat ""), you can reduce this (in bash) to

```<code>netstat () {
    command netstat "${@:1:1}" | grep -v 1111
}
</code>```

The parameter expansion "disappears" if $# really is 0.

Title: Loop creating infinite grep process

Body:
I have coded a bash script to not show certain port when someone uses netstat. I have placed it in .bashrc file.

function test(){
    if [ ! -n "$1" ]; then
       netstat | grep -v 1111;
    else
       netstat "$1" | grep -v 1111;
    fi
}
alias netstat='test'

When executed, sometimes when executing netstat | grep 1111 (not always and it is not possible to specify in which situations) it creates an infinite number of grep processes.

The expected result is to return netstat output without the filtered port.

Body:
There's no need for an alias, and you can use the command command to differentiate between your function netstat and the "real" command netstat.

netstat () {
    if [ -z "$1" ]; then
        command netstat
    else
        command netstat "$1"
    fi | grep -v 1111
}

If your actual intention is to determine if there is an argument, rather than simply a non-empty argument (i.e., differentiate between netstat and netstat ""), you can reduce this (in bash) to

netstat () {
    command netstat "${@:1:1}" | grep -v 1111
}

The parameter expansion "disappears" if $# really is 0.


答:
The main problem is how your use of netstat is specified, without a full path.  So you get the recursion experienced.

I would suggest using something like export NETSTAT=$(which netstat). Then your internal use can be based on the NETSTAT full path you have.

Title: Loop creating infinite grep process


问:
Creating ASP.NET Core SQL Cache table
I'm trying to generate the Distributed SQL Server Cache for ASP.NET Core 2.0, using the CLI, but I only get an error. The instructions say to execute

```<code>dotnet sql-cache create <connection string>  <schema>  <table name>
</code>```

but when I do, it simply responds with No executable found matching command "dotnet-sql-cache".

I have installed Microsoft.Extensions.Caching.SqlConfig.Tools 2.0.0 on that project. So it should work from the project root, no?

When I execute dotnet -h, I get .NET Command Line Tools (2.0.2), etc. Surprisingly enough, sql-cache is not listed there among the SDK commands, alongside new, restore, run, migrate, etc. Shouldn't it be?

答:
For instance I used the command:

```<code>dotnet sql-cache create "Data Source=.\Ganimedes;Initial Catalog=DistCache;Integrated Security=True;" dbo SessionCache_Test
</code>```

from PowerShell console. I  t's not neccesary to stay in Visual Studio to do this. The command is part of .Net Core SDK and you can use it from command line console (cmd, powershell, pwsh).

I have .Net Core 2.1 installed, this is the result of dotnet --info:

```<code>.NET Core SDK (reflecting any global.json):
 Version:   2.1.502
 Commit:    c74ce8f29f

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.17763
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.502\

Host (useful for support):
  Version: 2.1.6
  Commit:  3f4f8eebd8

.NET Core SDKs installed:
  1.1.0 [C:\Program Files\dotnet\sdk]
  2.0.2 [C:\Program Files\dotnet\sdk]
  2.1.4 [C:\Program Files\dotnet\sdk]
  2.1.202 [C:\Program Files\dotnet\sdk]
  2.1.403 [C:\Program Files\dotnet\sdk]
  2.1.502 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 1.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download
</code>```

Title: Creating ASP.NET Core SQL Cache table

Body:
I'm trying to generate the Distributed SQL Server Cache for ASP.NET Core 2.0, using the CLI, but I only get an error. The instructions say to execute

dotnet sql-cache create <connection string>  <schema>

but when I do, it simply responds with No executable found matching command "dotnet-sql-cache".

I have installed Microsoft.Extensions.Caching.SqlConfig.Tools 2.0.0 on that project. So it should work from the project root, no?

When I execute dotnet -h, I get .NET Command Line Tools (2.0.2), etc. Surprisingly enough, sql-cache is not listed there among the SDK commands, alongside new, restore, run, migrate, etc. Shouldn't it be?

Body:
For instance I used the command:

dotnet sql-cache create "Data Source=.\Ganimedes;Initial Catalog=DistCache;Integrated Security=True;" dbo SessionCache_Test

from PowerShell console. I  t's not neccesary to stay in Visual Studio to do this. The command is part of .Net Core SDK and you can use it from command line console (cmd, powershell, pwsh).

I have .Net Core 2.1 installed, this is the result of dotnet --info:

.NET Core SDK (reflecting any global.json):
 Version:   2.1.502
 Commit:    c74ce8f29f

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.17763
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.502\

Host (useful for support):
  Version: 2.1.6
  Commit:  3f4f8eebd8

.NET Core SDKs installed:
  1.1.0 [C:\Program Files\dotnet\sdk]
  2.0.2 [C:\Program Files\dotnet\sdk]
  2.1.4 [C:\Program Files\dotnet\sdk]
  2.1.202 [C:\Program Files\dotnet\sdk]
  2.1.403 [C:\Program Files\dotnet\sdk]
  2.1.502 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 1.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download


问:
Should I instantiate a shared Gson object for all doGet/doPost calls to a Servlet?
Currently I am using the Google's Gson class to parse incoming Ajax JSON strings into Java pojos, as part of the doGet/doPost tasks. I instantiate a new Gson object the usual out from the JSON string the usual way:

```<code>JsonObj jsonObj = new Gson().fromJson(jsonStr, jsonObj.class);
</code>```

The doubt is if I should instantiate a shared gson object in the servlet initialization to avoid doing new Gson() in every servlet doGet/doPost call.

Here Instantiate a new instance of GSON for every serialization? I've learnt that Gson is not a singleton and that some customization is possible with GsonBuilder, but this is not my case.
I am worried about the multithreading behavior of the shared Gson object.

答:
Simple answer: Gson is thread safe and you can share it between servlets. See: Is it OK to use Gson instance as a static field in a model bean (reuse)?

But you should decouple JSON serialization/deserialization logic from your business logic. For example, in Spring is done by *HttpMessageConverter layer. So, first step would be to create shared bean of Gson object and second would be creating abstract layer which allow to exchange implementation if it is needed. If you are writing web-app anyway, Spring is a good choice.

Body:
Currently I am using the Google's Gson class to parse incoming Ajax JSON strings into Java pojos, as part of the doGet/doPost tasks. I instantiate a new Gson object the usual out from the JSON string the usual way:

JsonObj jsonObj = new Gson().fromJson(jsonStr, jsonObj.class);

The doubt is if I should instantiate a shared gson object in the servlet initialization to avoid doing new Gson() in every servlet doGet/doPost call.

Here Instantiate a new instance of GSON for every serialization? I've learnt that Gson is not a singleton and that some customization is possible with GsonBuilder, but this is not my case.
I am worried about the multithreading behavior of the shared Gson object.


问:
TypeError: admin.listUsers is not a function
I have deployed the following cloud function:

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.getAllUsers = functions.https.onRequest((req: any, res: any) => {
  return admin.listUsers().then((userRecords: any) => {
    userRecords.users.forEach((user: any) => console.log(user.toJSON()));
    res.end('Retrieved all users successfully.');
  }).catch((error: any) => console.log('Request failed: ', error));
})
</code>```

But whenever I try to run it, I get the following error:

```<code>TypeError: admin.listUsers is not a function
    at exports.getAllUsers.functions.https.onRequest (/srv/functions/lib/index.js:102:11)
    at cloudFunction (/srv/functions/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at process.nextTick (/srv/node_modules/@google-cloud/functions-framework/build/src/invoker.js:243:17)
    at process._tickCallback (internal/process/next_tick.js:61:11)
</code>```

How do I resolve it? And how do I add a parameter to paginate my data, i.e. to get 100 users at a time or something? I am expecting to call the endpoint as follows: curl http://localhost:5000/sweltering-fire-5301/us-central1/getAllUsers. How would it look like with a parameter i.e. 'http://localhost:5000/sweltering-fire-5301/us-central1/getAllUsers?limit=5&page=2'

答:
If you imported the admin SDK like this:

```<code>const admin = require("firebase-admin")
</code>```

Then listUsers is available to you like this:

```<code>admin.auth().listUsers()
</code>```

You might want to check out the documentation and API reference, as they have everything you need to make this happen.

Body:
I have deployed the following cloud function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.getAllUsers = functions.https.onRequest((req: any, res: any) => {
  return admin.listUsers().then((userRecords: any) => {
    userRecords.users.forEach((user: any) => console.log(user.toJSON()));
    res.end('Retrieved all users successfully.');
  }).catch((error: any) => console.log('Request failed: ', error));
})

But whenever I try to run it, I get the following error:

TypeError: admin.listUsers is not a function
    at exports.getAllUsers.functions.https.onRequest (/srv/functions/lib/index.js:102:11)
    at cloudFunction (/srv/functions/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at process.nextTick (/srv/node_modules/@google-cloud/functions-framework/build/src/invoker.js:243:17)
    at process._tickCallback (internal/process/next_tick.js:61:11)

How do I resolve it? And how do I add a parameter to paginate my data, i.e. to get 100 users at a time or something? I am expecting to call the endpoint as follows: curl http://localhost:5000/sweltering-fire-5301/us-central1/getAllUsers. How would it look like with a parameter i.e. 'http://localhost:5000/sweltering-fire-5301/us-central1/getAllUsers?limit=5&page=2'

Body:
If you imported the admin SDK like this:

const admin = require("firebase-admin")

Then listUsers is available to you like this:

admin.auth().listUsers()

You might want to check out the documentation and API reference, as they have everything you need to make this happen.


问:
Navigation's back stack is lost when navigation is nested
I have a navigation which looks like this

```<code>Frag1 -> Frag2 -> Frag3
</code>```

Inside Frag2 there is a NavHostFragment with its own navigation

```<code>InnerFrag1 -> InnerFrag2
</code>```

If I do this

Navigate to Frag2

Navigate to InnerFrag2 inside Frag2

Navigate to Frag3

Go back

then I'll see InnerFrag2 inside Frag2, when I press back normally I would go from InnerFrag2 to InnerFrag1 inside Frag2 but now it's going to Frag1 instead.

Here is my navigation handling inside Frag2

```<code>
    private val backPressedCallback = OnBackPressedCallback {
        navHostFragment.navController.navigateUp()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().addOnBackPressedCallback(backPressedCallback)
    }

    override fun onDestroyView() {
        activity?.removeOnBackPressedCallback(backPressedCallback)
        super.onDestroyView()
    }

    private val navHostFragment: NavHostFragment
        get() = childFragmentManager.findFragmentById(R.id.innerNavHostFragment) as NavHostFragment

</code>```

When going back to Frag2 the fragment in the nav host is the correct one, but navigating back moves away from Frag2 because inner nav host's back stack is lost. Can I persist it somehow or fix it some other way?

EDIT: actually when going from Frag3 to Frag2 I see InnerFrag1 inside, the both look alike, that's why going back at this point brings me back to Frag1

EDIT2: I found my problem, I inflate Frag2s navigation from code in onViewCreated like this

```<code>    val navHostFragment = (frag2NavHostFragment as? NavHostFragment) ?: return
    val inflater = navHostFragment.navController.navInflater
    val graph = inflater.inflate(navigationId)
    navHostFragment.navController.graph = graph
</code>```

setting it in xml makes it work, I still need to set it from code somehow, Frag2 chooses which navigation to use depending on its arguments

Now my question changes from Navigation's back stack is lost to How to preserve NavHostFragment's state when settings it's graph from code

答:
You can now handle onBackPress on fragments. In your fragment just add this in onViewCreated method.

```<code>val navController = Navigation.findNavController(view)
        requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                navController.popBackStack(R.id.fragmentWhereYouWantToGo, false)
            }
        })
</code>```

I would also give a check to app:popUpTo , app:popUpToInclusive or singleTop XML attributes to the fragments inside your Frag2

Body:
I have a navigation which looks like this

Frag1 -> Frag2 -> Frag3

Inside Frag2 there is a NavHostFragment with its own navigation

InnerFrag1 -> InnerFrag2

If I do this

Navigate to Frag2

Navigate to InnerFrag2 inside Frag2

Navigate to Frag3

Go back

then I'll see InnerFrag2 inside Frag2, when I press back normally I would go from InnerFrag2 to InnerFrag1 inside Frag2 but now it's going to Frag1 instead.

Here is my navigation handling inside Frag2

    private val backPressedCallback = OnBackPressedCallback {
        navHostFragment.navController.navigateUp()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().addOnBackPressedCallback(backPressedCallback)
    }

    override fun onDestroyView() {
        activity?.removeOnBackPressedCallback(backPressedCallback)
        super.onDestroyView()
    }

    private val navHostFragment: NavHostFragment
        get() = childFragmentManager.findFragmentById(R.id.innerNavHostFragment) as NavHostFragment

When going back to Frag2 the fragment in the nav host is the correct one, but navigating back moves away from Frag2 because inner nav host's back stack is lost. Can I persist it somehow or fix it some other way?

EDIT: actually when going from Frag3 to Frag2 I see InnerFrag1 inside, the both look alike, that's why going back at this point brings me back to Frag1

EDIT2: I found my problem, I inflate Frag2s navigation from code in onViewCreated like this

    val navHostFragment = (frag2NavHostFragment as? NavHostFragment) ?: return
    val inflater = navHostFragment.navController.navInflater
    val graph = inflater.inflate(navigationId)
    navHostFragment.navController.graph = graph

setting it in xml makes it work, I still need to set it from code somehow, Frag2 chooses which navigation to use depending on its arguments

Now my question changes from Navigation's back stack is lost to How to preserve NavHostFragment's state when settings it's graph from code

Body:
You can now handle onBackPress on fragments. In your fragment just add this in onViewCreated method.

val navController = Navigation.findNavController(view)
        requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                navController.popBackStack(R.id.fragmentWhereYouWantToGo, false)
            }
        })

I would also give a check to app:popUpTo , app:popUpToInclusive or singleTop XML attributes to the fragments inside your Frag2


问:
Define WPF Resource Dictionary in Winform App
I am testing being able to create a WPF control that can be used in an existing Winforms application.  With this test, the goal is to have globally used WPF resource dictionary.

My first step of defining the style settings in the control works fine.

```<code><UserControl.Resources>
    <Style TargetType="Label">
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="Background" Value="LightYellow"/>
        <Setter Property="FontSize" Value="30"/>
    </Style>
    <Style TargetType="Label" x:Key="myHW">
        <Setter Property="Foreground" Value="Green"/>
        <Setter Property="Background" Value="LightBlue"/>
        <Setter Property="FontSize" Value="30"/>
    </Style>
    <Style TargetType="Label" x:Key="StatusMessage">
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="Background" Value="LightPink"/>
    </Style>
</UserControl.Resources>
</code>```

Second was to then extract the style information to a dictionary XAML file and then reference it via the resource dictionary.  This step is not working.

```<code><UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Dictionaries/ResourceTest.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
</code>```

Assembly name: test2

Path inside project:  /Dictionaries/ResourceTest.xaml

Error received in development is:

Exception: An error occurred while finding the resource dictionary "/Dictionaries/ResourceTest.xaml".

I have tried variations of the URI syntax as presented by Microsoft.

Does the build action type for the xaml relate to the issue?

答:
Thanks Jeff R. for the response.  That was one of the issues.

I continued messing with this and finally resolved multiple issues.  Since this was being created in a Winforms app in a sandbox, I created a WPF application and then added a resource dictionary.  A comparison was done between the two resource dictionary xaml files to identify any differences.

The resource dictionary xaml file needed the following settings updated:

Build Action = Page

Custom Tool = XamlIntelliSenseFileGenerator

Additionally, the proper opening tag on the dictionary file was missing.

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</code>```

Lastly, since manually entering the source path wasn't working, I tried using the Properties page Source drop down selection which then filled in the needed path syntax that then matched what Jeff R. recommended.

In summary, there were three issues:

Resource dictionary file property settings

XAML opening tag missing

URI reference syntax

Body:
I am testing being able to create a WPF control that can be used in an existing Winforms application.  With this test, the goal is to have globally used WPF resource dictionary.

My first step of defining the style settings in the control works fine.

<UserControl.Resources>

</UserControl.Resources>

Second was to then extract the style information to a dictionary XAML file and then reference it via the resource dictionary.  This step is not working.

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Dictionaries/ResourceTest.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

Assembly name: test2

Path inside project:  /Dictionaries/ResourceTest.xaml

Error received in development is:

Exception: An error occurred while finding the resource dictionary "/Dictionaries/ResourceTest.xaml".

I have tried variations of the URI syntax as presented by Microsoft.

Does the build action type for the xaml relate to the issue?

Body:
Thanks Jeff R. for the response.  That was one of the issues.

I continued messing with this and finally resolved multiple issues.  Since this was being created in a Winforms app in a sandbox, I created a WPF application and then added a resource dictionary.  A comparison was done between the two resource dictionary xaml files to identify any differences.

The resource dictionary xaml file needed the following settings updated:

Build Action = Page

Custom Tool = XamlIntelliSenseFileGenerator

Additionally, the proper opening tag on the dictionary file was missing.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

Lastly, since manually entering the source path wasn't working, I tried using the Properties page Source drop down selection which then filled in the needed path syntax that then matched what Jeff R. recommended.

In summary, there were three issues:

Resource dictionary file property settings

XAML opening tag missing

URI reference syntax


问:
How does Burn in WiX 3.6 bundle MSI files into an .exe?
I'm interested in knowing how WiX is bundling the EXE files created with Burn. I know that creating a self-extracting EXE file is pretty straightforward, having done it a million times in WinRAR. What directory is the EXE file being unpacked to, and how is the installation writing that location into Add/Remove Programs?

Also, how is the UX file being kept around for the uninstall? And even more interesting, what goes on during an upgrade?

答:
Burn doesn't create a typical "self-extracting .exe" that unpacks the contents then launches. Instead, it extracts the bits it needs (the UX or bootstrapper application) to a temporary directory and then caches the packages that are needed when they're needed. That way, no time is wasted extracting packages that aren't used.

The cache directory is named "Package Cache" and stored in an appdata folder, which one depending on whether it's a per-user or per-machine package.

There's nothing special about upgrades, except that when one bundle upgrades another, the previous bundle's cache is removed.


问:
Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

```<code>    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }
</code>```

The model class for state:

```<code> package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

        public void setId(long id) {
            this.id = id;
        }

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }
</code>```

Distric model:

```<code>package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}
</code>```

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

答:
I've been struggling with the same problem for days, I tried  @JsonIgnore, @JsonManagedReference and @JsonBackReference annotation, and even @JsonIdentityInfo annotation and none of them have worked.

If you (the future readers ) are in the same situation, the solution is easier than you expected, simply put @JsonIgnore or @JsonManagedReference / @JsonBackReference on the attribute's getter and not on the attribute itself. And that will do.

Here's a simple example how to do so :

Say we have two classes, Order and Product, and OneToMany relation between them.

Order class

```<code>public class Order{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id_order;
  private double price;
  @OneToMany(mappedBy = "order")
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<Product> products
  //constructor, getters & setter
}
</code>```

Product Class:

```<code>public class Product{
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private String id_product;
   private String name;
   @ManyToOne
   @JoinColumn(name = "id_order")
   private Order order;
   //consturctor, getters & setters
 }
</code>```

So in order to use @JsonManagedReference and @JsonBackReference, just add them to the getters as the following :

```<code>public class Order{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id_order;
  private double price;
  @OneToMany(mappedBy = "order")
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<Product> products
  //constructor, getters & setter
  @JsonManagedReference
  public List<Product> getProducts(){
    return products;
}
</code>```

Product class:

```<code>public class Product{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id_product;
  private String name;
  @ManyToOne
  @JoinColumn(name = "id_order")
  private Order order;
  //consturctor, getters & setters
  @JsonBackReference
  public Order getOrder(){
    return order;
  }
 }
</code>```

Body:
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }

The model class for state:

 package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

        public void setId(long id) {
            this.id = id;
        }

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }

Distric model:

package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

Body:
I've been struggling with the same problem for days, I tried  @JsonIgnore, @JsonManagedReference and @JsonBackReference annotation, and even @JsonIdentityInfo annotation and none of them have worked.

If you (the future readers ) are in the same situation, the solution is easier than you expected, simply put @JsonIgnore or @JsonManagedReference / @JsonBackReference on the attribute's getter and not on the attribute itself. And that will do.

Here's a simple example how to do so :

Say we have two classes, Order and Product, and OneToMany relation between them.

Order class

public class Order{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id_order;
  private double price;
  @OneToMany(mappedBy = "order")
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<Product> products
  //constructor, getters & setter
}

Product Class:

public class Product{
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private String id_product;
   private String name;
   @ManyToOne
   @JoinColumn(name = "id_order")
   private Order order;
   //consturctor, getters & setters
 }

So in order to use @JsonManagedReference and @JsonBackReference, just add them to the getters as the following :

public class Order{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id_order;
  private double price;
  @OneToMany(mappedBy = "order")
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<Product> products
  //constructor, getters & setter
  @JsonManagedReference
  public List<Product> getProducts(){
    return products;
}

Product class:

public class Product{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id_product;
  private String name;
  @ManyToOne
  @JoinColumn(name = "id_order")
  private Order order;
  //consturctor, getters & setters
  @JsonBackReference
  public Order getOrder(){
    return order;
  }
 }


问:
Jenkinsfile, get all modified files in the PR
I want to have a list of modified files in the PR, I tried a few solutions but I can only have access to the modified files in the last commits pushed to remote.

Example:

Create a PR with 3 commits, a new jenkins job starts;

The list of modified files includes all files from the 3 commits;

The build fails, push a new commit with the fix into the PR, a new jenkins jobs starts;

The list of modified files only includes the files of the new commit;

So, in this example I want to have the list of files from all the new commits in the PR.

Code:

```<code>  def changeLogSets = currentBuild.rawBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            def files = new ArrayList(entry.affectedFiles)
            for (int k = 0; k < files.size(); k++) {
                def file = files[k]
                print file.path
            }
        }
    }
</code>```

答:
Use the Git Plugin (if you aren't already). Then something like:

```<code>git diff --name-status $GIT_PREVIOUS_SUCCESSFUL_COMMIT..$GIT_COMMIT > allchanges
</code>```

That will give you the list of all changes since the last successful build.

Body:
I want to have a list of modified files in the PR, I tried a few solutions but I can only have access to the modified files in the last commits pushed to remote.

Example:

Create a PR with 3 commits, a new jenkins job starts;

The list of modified files includes all files from the 3 commits;

The build fails, push a new commit with the fix into the PR, a new jenkins jobs starts;

The list of modified files only includes the files of the new commit;

So, in this example I want to have the list of files from all the new commits in the PR.

Code:

  def changeLogSets = currentBuild.rawBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            def files = new ArrayList(entry.affectedFiles)
            for (int k = 0; k < files.size(); k++) {
                def file = files[k]
                print file.path
            }
        }
    }

Body:
Use the Git Plugin (if you aren't already). Then something like:

git diff --name-status $GIT_PREVIOUS_SUCCESSFUL_COMMIT..$GIT_COMMIT > allchanges

That will give you the list of all changes since the last successful build.


问:
An error occurred while loading the YAML build pipeline. The service connection name 00000000-0000-0000-0000-000000000000 is ambiguous
We have azure build pipelines, some are in visual editor and few are in yaml.
I am trying to add sonarcloud analysis to these pipelines.
This work fine in the visual editor, I am copying same yaml from visual editor to add in existed yaml pipeline. I am getting this error.

An error occurred while loading the YAML build pipeline. The service connection name 00000000-0000-0000-0000-000000000000 is ambiguous.

What I have done so far,
checked below resources and tried solutions mentioned there,

https://github.com/Microsoft/azure-pipelines-yaml/issues/31

VSTS anybody managed to use "secure file" in azure-pipelines.yml?

https://github.com/Microsoft/azure-pipelines-agent/issues/1809

create a new azure yaml pipeline

Verify sonarcloud connection in service connections in project settings.

this is my task definition

```<code>- task: SonarSource.sonarcloud.****************.SonarCloudPrepare@1
  displayName: 'Prepare analysis on SonarCloud'
  inputs:
    SonarCloud: *************
    organization: ****
    projectKey: "******"
    projectName: "************"
</code>```

答:
Check your service connections.

To get the appropriate screen...
Log into DevOps, go to the project overview, mouse over the project name, click the settings (gear) icon and then select the "Service Connections" navigation link in the left side navigation panel.

There's an odd behavior in the "Authorize" functionality; it will create a new service connection for the subscription you select (and name it after the subscription) even if it already exists. This results in multiple service connections with the exact same name.

Disconnect them all (select the "Disconnect" option in the "Actions" panel) and then add a new connection for the same subscription with a name that makes sense and then use that name (select that connection) for all task input values (e.g. ConnectedServiceNameARM or azureSubscription) where that information is needed.

Body:
We have azure build pipelines, some are in visual editor and few are in yaml.
I am trying to add sonarcloud analysis to these pipelines.
This work fine in the visual editor, I am copying same yaml from visual editor to add in existed yaml pipeline. I am getting this error.

An error occurred while loading the YAML build pipeline. The service connection name 00000000-0000-0000-0000-000000000000 is ambiguous.

What I have done so far,
checked below resources and tried solutions mentioned there,

https://github.com/Microsoft/azure-pipelines-yaml/issues/31

VSTS anybody managed to use "secure file" in azure-pipelines.yml?

https://github.com/Microsoft/azure-pipelines-agent/issues/1809

create a new azure yaml pipeline

Verify sonarcloud connection in service connections in project settings.

this is my task definition

- task: SonarSource.sonarcloud.****************.SonarCloudPrepare@1
  displayName: 'Prepare analysis on SonarCloud'
  inputs:
    SonarCloud: *************
    organization: ****
    projectKey: "******"
    projectName: "************"


问:
Get the referrer, paid/natural and keywords for the current visitor with Google Analytics
Is it possible to get the following information about the current visitor using Google Analytics API with JavaScript?

Referrer site ('Source' in GA)

Paid or natural ('Medium' in GA)

Keyword

First time/returning

Number of visits

If it's not possible with Google Analytics API is there any other easy way to do it (apart from parsing HTTP Referer, storing the visits statistics in DB etc.)?

答:
If you're still using ga.js (the legacy version of Google Analytics tracking code), you can use the below code to generate the values you want within the browser, by reading browser cookies. (Most people will have migrated to analytics.js, which does not store the campaign information in the __utmz cookie.)

I assume you have a function called readCookie(); I tend to use the one from QuirksMode

For referral, medium, and campaign information:

```<code>var utmz = readCookie('__utmz'); //using a cookie reading function
var vals = (function() {
        var pairs = utmz.split('.').slice(4).join('.').split('|');
        var ga = {};
        for (var i = 0; i < pairs.length; i++) {
            var temp = pairs[i].split('=');
                ga[temp[0]] = temp[1];
        }
        return ga;
    })();

//vals.utmcmd: medium (organic, referral, direct, etc)
//vals.utmcsr: source (google, facebook.com, etc)
//vals.utmcct: content (index.html, etc)
//vals.utmccn: campaign
//vals.utmctr: term (search term)
//vals.utmgclid: adwords-only (value is irrelevant, but means its AdWords autotagged traffic, but it implies that medium=cpc, even though it'll be set to `(none)` or `(not%20set)`
</code>```

For pageview count and visit count:

```<code>var pageviews = readCookie('__utmz').split('.')[1];
var visits = readCookie('__utma').split('.').pop() //returns number of visits
</code>```

Obviously, if (+visits)===1, then its a first time visitor. (Remember: values from cookies will be strings, so you'll need to cast them to numbers to safely do numeric comparisons, even though JS is loosely typed.

Body:
If you're still using ga.js (the legacy version of Google Analytics tracking code), you can use the below code to generate the values you want within the browser, by reading browser cookies. (Most people will have migrated to analytics.js, which does not store the campaign information in the __utmz cookie.)

I assume you have a function called readCookie(); I tend to use the one from QuirksMode

For referral, medium, and campaign information:

var utmz = readCookie('__utmz'); //using a cookie reading function
var vals = (function() {
        var pairs = utmz.split('.').slice(4).join('.').split('|');
        var ga = {};
        for (var i = 0; i < pairs.length; i++) {
            var temp = pairs[i].split('=');
                ga[temp[0]] = temp[1];
        }
        return ga;
    })();

//vals.utmcmd: medium (organic, referral, direct, etc)
//vals.utmcsr: source (google, facebook.com, etc)
//vals.utmcct: content (index.html, etc)
//vals.utmccn: campaign
//vals.utmctr: term (search term)
//vals.utmgclid: adwords-only (value is irrelevant, but means its AdWords autotagged traffic, but it implies that medium=cpc, even though it'll be set to `(none)` or `(not%20set)`

For pageview count and visit count:

var pageviews = readCookie('__utmz').split('.')[1];
var visits = readCookie('__utma').split('.').pop() //returns number of visits

Obviously, if (+visits)===1, then its a first time visitor. (Remember: values from cookies will be strings, so you'll need to cast them to numbers to safely do numeric comparisons, even though JS is loosely typed.