问:
Unable to implement POST method in spring boot
I am trying to implement a simple POST method, but unable to do so.

Tried several solutions mentioned in "stackoverflow", still getting error.

My Controller class

```<code>@RestController
@RequestMapping("api/public")
public class PublicRestApiController {

@GetMapping("users")
public List<User> users(){
    return this.userRepository.findAll();
}

@PostMapping(path="/insert",produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.ACCEPTED)
 public User add(@RequestBody UserRequest account) {
    User response = new User(account.getUsername(),account.getPassword(),account.getRoles(), account.getPermissions());
    return response;
    }

}
</code>```

UserRequest class

```<code>public class UserRequest {

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getActive() {
    return active;
}
public void setActive(int active) {
    this.active = active;
}
public String getRoles() {
    return roles;
}
public void setRoles(String roles) {
    this.roles = roles;
}
public String getPermissions() {
    return permissions;
}
public void setPermissions(String permissions) {
    this.permissions = permissions;
}
private String username;
private String password;
private int active;
private String roles = "";
private String permissions = "";

}
</code>```

User Class

```<code>@Entity
@Table(name = "USER_DETAILS")
public class User {

@Id
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(nullable = false)
private String username;

@Column(nullable = false)
private String PASSWORD;

@Column
private int ACTIVE;

@Column
private String ROLES = "";

@Column
private String PERMISSIONS = "";

public User(String username, String password, String roles, String permissions){
    this.username = username;
    this.PASSWORD = password;
    this.ROLES = roles;
    this.PERMISSIONS = permissions;
    this.ACTIVE = 1;
}

public User(){}

public int getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return PASSWORD;
}

public int getActive() {
    return ACTIVE;
}

public String getRoles() {
    return ROLES;
}

public String getPermissions() {
    return PERMISSIONS;
}

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

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.PASSWORD = password;
}

public void setActive(int active) {
    this.ACTIVE = active;
}

public void setRoles(String roles) {
    this.ROLES = roles;
}

public void setPermissions(String permissions) {
    this.PERMISSIONS = permissions;
}
}
</code>```

This error message is appearing.

```<code>2019-05-28 17:08:41.808  WARN 7712 --- [nio-8443-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
</code>```

GET methods are working fine within same controller, only getting error while trying to implement POST implement.

Request screenshot through Postman

Security Config

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/api/public/users").hasRole("ADMIN")
      .antMatchers("/api/public/insert").hasRole("ADMIN")
      .and()
      .httpBasic();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
</code>```

}

Application Class

```<code>@SpringBootApplication(scanBasePackages = {"rc.bootsecurity"})
public class BootSecurityApplication {

public static void main(String[] args) {
    SpringApplication.run(BootSecurityApplication.class, args);
}

@Bean
public ServletWebServerFactory servletContainer() {
    // Enable SSL Trafic
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };

    // Add HTTP to HTTPS redirect
    tomcat.addAdditionalTomcatConnectors(httpToHttpsRedirectConnector());

    return tomcat;
}

private Connector httpToHttpsRedirectConnector() {
    Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    connector.setScheme("http");
    connector.setPort(8082);
    connector.setSecure(false);
    connector.setRedirectPort(8443);
    return connector;
    }
}
</code>```

答:
Possible Solution 1:

Open Postman

Go to Settings using File Section

Turn off Automatically follow redirects

Possible Solution 2:

Add an extra / (trailing slash) to your endPoint
change api/public/insert to api/public/insert/

What Postman Support says about I sent a POST request, but Postman seems to be sending a GET request.

This is mostly due to a server-side redirect. If Postman receives a
  301 or 302 response code, it will automatically follow the redirect.
  Similar to the behaviour in browsers, the original request method will
  NOT be preserved, and the redirected request will be made with a GET
  method. If you want to disable the auto-follow redirect behaviour, or
  if you have other questions regarding this, please review the relevant
  documentation on redirects

Postman Support Interceptor extension Git Issue

UPDATE:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable()
      .authorizeRequests()
      .antMatchers("/api/public/users").hasRole("ADMIN")
      .antMatchers(HttpMethod.POST,"/api/public/insert").hasRole("ADMIN")
      .anyRequest().authenticated();
}
</code>```

Body:
I am trying to implement a simple POST method, but unable to do so.

Tried several solutions mentioned in "stackoverflow", still getting error.

My Controller class

@RestController
@RequestMapping("api/public")
public class PublicRestApiController {

@GetMapping("users")
public List<User> users(){
    return this.userRepository.findAll();
}

@PostMapping(path="/insert",produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.ACCEPTED)
 public User add(@RequestBody UserRequest account) {
    User response = new User(account.getUsername(),account.getPassword(),account.getRoles(), account.getPermissions());
    return response;
    }

}

UserRequest class

public class UserRequest {

public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
public int getActive() {
    return active;
}
public void setActive(int active) {
    this.active = active;
}
public String getRoles() {
    return roles;
}
public void setRoles(String roles) {
    this.roles = roles;
}
public String getPermissions() {
    return permissions;
}
public void setPermissions(String permissions) {
    this.permissions = permissions;
}
private String username;
private String password;
private int active;
private String roles = "";
private String permissions = "";

}

User Class

@Entity
@Table(name = "USER_DETAILS")
public class User {

@Id
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(nullable = false)
private String username;

@Column(nullable = false)
private String PASSWORD;

@Column
private int ACTIVE;

@Column
private String ROLES = "";

@Column
private String PERMISSIONS = "";

public User(String username, String password, String roles, String permissions){
    this.username = username;
    this.PASSWORD = password;
    this.ROLES = roles;
    this.PERMISSIONS = permissions;
    this.ACTIVE = 1;
}

public User(){}

public int getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return PASSWORD;
}

public int getActive() {
    return ACTIVE;
}

public String getRoles() {
    return ROLES;
}

public String getPermissions() {
    return PERMISSIONS;
}

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

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.PASSWORD = password;
}

public void setActive(int active) {
    this.ACTIVE = active;
}

public void setRoles(String roles) {
    this.ROLES = roles;
}

public void setPermissions(String permissions) {
    this.PERMISSIONS = permissions;
}
}

This error message is appearing.

2019-05-28 17:08:41.808  WARN 7712 --- [nio-8443-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]

GET methods are working fine within same controller, only getting error while trying to implement POST implement.

Request screenshot through Postman

Security Config

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/api/public/users").hasRole("ADMIN")
      .antMatchers("/api/public/insert").hasRole("ADMIN")
      .and()
      .httpBasic();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

}

Application Class

@SpringBootApplication(scanBasePackages = {"rc.bootsecurity"})
public class BootSecurityApplication {

public static void main(String[] args) {
    SpringApplication.run(BootSecurityApplication.class, args);
}

@Bean
public ServletWebServerFactory servletContainer() {
    // Enable SSL Trafic
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };

    // Add HTTP to HTTPS redirect
    tomcat.addAdditionalTomcatConnectors(httpToHttpsRedirectConnector());

    return tomcat;
}

private Connector httpToHttpsRedirectConnector() {
    Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    connector.setScheme("http");
    connector.setPort(8082);
    connector.setSecure(false);
    connector.setRedirectPort(8443);
    return connector;
    }
}

Body:
Possible Solution 1:

Open Postman

Go to Settings using File Section

Turn off Automatically follow redirects

Possible Solution 2:

Add an extra / (trailing slash) to your endPoint
change api/public/insert to api/public/insert/

What Postman Support says about I sent a POST request, but Postman seems to be sending a GET request.

This is mostly due to a server-side redirect. If Postman receives a
  301 or 302 response code, it will automatically follow the redirect.
  Similar to the behaviour in browsers, the original request method will
  NOT be preserved, and the redirected request will be made with a GET
  method. If you want to disable the auto-follow redirect behaviour, or
  if you have other questions regarding this, please review the relevant
  documentation on redirects

Postman Support Interceptor extension Git Issue

UPDATE:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable()
      .authorizeRequests()
      .antMatchers("/api/public/users").hasRole("ADMIN")
      .antMatchers(HttpMethod.POST,"/api/public/insert").hasRole("ADMIN")
      .anyRequest().authenticated();
}


来源: stackexchange

问:
alert-dismissible not closing wen clicking close button bootstrap laravel
When I click the close button it doesn't close the notification. Am I missing something?

(The 'x' symbol at the upper right corner of the alert)

Here is the specific code of this alert. I'm using Laravel version 5.8.15 and latest bootstrap if that helps

```<code><div class="mg-auto justify-content-center">
        @if ($errors->any())
            <div class="alert alert-warning alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="alert-heading">Oops! Something went wrong!</h4>
                <p>
                    @foreach ($errors->all() as $error)
                        - {{ $error }}<br>
                    @endforeach
                </p>
            </div>
        @endif
    </div>
</code>```

My script files alignment:

```<code><script src="{{ asset('js.jquery-341.js') }}"></script>
<script src="{{ asset('js/bootstrap.min.js') }}"></script>
</code>```

答:
Did you make sure you correctly integrated bootstrap's javascript plugin? You have to call it after you called jQuery like so :

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js" ></script>
</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

        @if ($errors->any())

                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                </button>

Oops! Something went wrong!

                    @foreach ($errors->all() as $error)
                        - {{ $error }}

                    @endforeach

        @endif

```

ContentLicense: CC BY-SA 4.0

Body:
When I click the close button it doesn't close the notification. Am I missing something?

(The 'x' symbol at the upper right corner of the alert)

Here is the specific code of this alert. I'm using Laravel version 5.8.15 and latest bootstrap if that helps

        @if ($errors->any())

                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    ×
                </button>

Oops! Something went wrong!

                    @foreach ($errors->all() as $error)
                        - {{ $error }}

                    @endforeach

        @endif

My script files alignment:

Body:
Did you make sure you correctly integrated bootstrap's javascript plugin? You have to call it after you called jQuery like so :

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js" ></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js" ></script>

<div class="mg-auto justify-content-center">
        @if ($errors->any())
            <div class="alert alert-warning alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="alert-heading">Oops! Something went wrong!</h4>
                <p>
                    @foreach ($errors->all() as $error)
                        - {{ $error }}<br>
                    @endforeach
                </p>
            </div>
        @endif
    </div>


问:
How to Automatically add thousand separators as number is input in EditText
Im creating a convertor application. I want to set the EditText so that when the user is inputting the number to be converted, a thousand separator (,) should be added automatically in realtime to the number once it increments by 3 figures: thousand, million, billion etc.

And when erased to below 4 figures the number goes back to normal.

Any help?

答:
The answers here lack a method to handle actual user input, such as deleting characters or copying and pasting. This is an EditText field. If you want to add formatting in, you need to support editing that formatted value.

This implementation still has a deficiency depending on your use case. I didn't care about decimal values and assumed I would only be handling whole numbers. There's enough of how to handle that on this page and how to handle actual internationalization that I'll leave that as an exercise to the reader. If you need to do that, it shouldn't be too difficult to add "." to the regular expression to keep the decimal; you'll just have to be careful to acknowledge the numeral string still has a non numerical character.

This is designed to be used throughout multiple activities. New it once, give it your edit text and your data model and ignore it. The model binding can be removed if you don't need it.

```<code>public class EditNumberFormatter implements TextWatcher {

    private EditText watched;
    private Object model;
    private Field field;
    private IEditNumberFormatterListener listener;

    private ActiveEdit activeEdit;

    /**
     * Binds an EditText to a data model field (Such as a room entity's public variable)
     * Whenever the edit text is changed, the text is formatted to the local numerical format.
     *
     * Handles copy/paste/backspace/select&delete/typing
     *
     * @param model An object with a public field to bind to
     * @param fieldName A field defined on the object
     * @param watched The edit text to watch for changes
     * @param listener Another object that wants to know after changes & formatting are done.
     */
    public EditNumberFormatter(Object model, String fieldName, EditText watched, IEditNumberFormatterListener listener) {

        this.model = model;
        this.watched = watched;
        this.listener = listener;

        try {
            field = model.getClass().getDeclaredField(fieldName);
        } catch(Exception e) { }

        watched.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        activeEdit = new ActiveEdit(s.toString(), start, count);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        activeEdit.recordChangedText(s.toString(),count);
    }

    @Override
    public void afterTextChanged(Editable s) {
        this.watched.removeTextChangedListener(this);

        activeEdit.processEdit(); // Override the user's edit of the formatted string with what the user intended to do to the numeral.

        watched.setText(activeEdit.getCurrentFormattedString());
        watched.setSelection(activeEdit.getCursorPosition());
        updateDataModel(activeEdit.getCurrentRawValue());

        listener.FormatUpdated(watched.getId(), activeEdit.getCurrentRawValue(), activeEdit.getCurrentFormattedString());

        this.watched.addTextChangedListener(this);
    }

    private void updateDataModel(int rawValue) {
        try {
            field.set(model, rawValue);
        } catch (IllegalAccessException e) { }
    }

    /**
     * Tracks the active editing of an EditText formatted for integer input
     */
    private class ActiveEdit {

        private String priorFormattedString;
        private String currentFormattedString;
        private String currentNumericalString;
        private int currentRawValue;

        private boolean removal;
        private boolean addition;

        private int changeStart;
        private int removedCount;
        private int additionCount;

        private int numeralCountBeforeSelection;
        private int numeralCountAdded;
        private int numeralCountRemoved;

        /**
         * Call in beforeEdit to begin recording changes
         *
         * @param beforeEdit string before edit began
         * @param start start position of edit
         * @param removed number of characters removed
         */
        public ActiveEdit(String beforeEdit, int start, int removed) {
            removal = (removed > 0);

            priorFormattedString = beforeEdit;
            changeStart = start;
            removedCount = removed;

            numeralCountBeforeSelection = countNumerals(priorFormattedString.substring(0, changeStart));
            numeralCountRemoved = countNumerals(priorFormattedString.substring(changeStart, changeStart + removedCount));
        }

        /**
         * Call in onTextChanged to record new text and how many characters were added after changeStart
         *
         * @param afterEdit new string after user input
         * @param added how many characters were added (same start position as before)
         */
        public void recordChangedText(String afterEdit, int added) {
            addition = (added > 0);
            additionCount = added;
            numeralCountAdded = countNumerals(afterEdit.substring(changeStart, changeStart + additionCount));

            currentNumericalString = afterEdit.replaceAll("[^0-9]", "");
        }

        /**
         * Re-process the edit for our particular formatting needs.
         */
        public void processEdit() {
            forceRemovalPastFormatting();
            finalizeEdit();
        }

        /**
         * @return Integer value of the field after an edit.
         */
        public int getCurrentRawValue() {
            return currentRawValue;
        }

        /**
         * @return Formatted number after an edit.
         */
        public String getCurrentFormattedString() {
            return currentFormattedString;
        }

        /**
         * @return Cursor position after an edit
         */
        public int getCursorPosition() {
            int numeralPosition = numeralCountBeforeSelection + numeralCountAdded;
            return positionAfterNumeralN(currentFormattedString,numeralPosition);
        }

        /**
         * If a user deletes a value, but no numerals are deleted, then delete the numeral proceeding
         * their cursor. Otherwise, we'll just add back the formatting character.
         *
         * Assumes formatting uses a single character and not multiple formatting characters in a row.
         */
        private void forceRemovalPastFormatting() {
            if (removal && (!addition) && (numeralCountRemoved == 0)) {
                String before = currentNumericalString.substring(0, numeralCountBeforeSelection - 1);
                String after = currentNumericalString.substring(numeralCountBeforeSelection);

                currentNumericalString =  before + after;
                numeralCountRemoved++;
                numeralCountBeforeSelection--;
            }
        }

        /**
         * Determine the result of the edit, including new display value and raw value
         */
        private void finalizeEdit() {
            currentFormattedString = "";
            currentRawValue = 0;
            if (currentNumericalString.length() == 0) {
                return; // There is no entry now.
            }
            try {
                currentRawValue = Integer.parseInt(currentNumericalString);
            } catch (NumberFormatException nfe) {
                abortEdit();  // Value is not an integer, return to previous state.
                return;
            }
            currentFormattedString = String.format("%,d", currentRawValue);
        }

        /**
         * Current text, same as the old text.
         */
        private void abortEdit() {
            currentFormattedString = priorFormattedString;
            currentNumericalString = currentFormattedString.replaceAll("[^0-9]", "");
            numeralCountRemoved = 0;
            numeralCountAdded = 0;
            try {
                currentRawValue = Integer.parseInt(currentNumericalString);
            } catch (Exception e) { currentRawValue = 0; }
        }

        /**
         * Determine how many numerical characters exist in a string
         * @param s
         * @return the number of numerical characters in the string
         */
        private int countNumerals(String s) {
            String newString = s.replaceAll("[^0-9]", "");
            return newString.length();
        }

        /**
         * Determine how to place a cursor after the Nth Numeral in a formatted string.
         * @param s - Formatted string
         * @param n - The position of the cursor should follow the "Nth" number in the string
         * @return the position of the nth character in a formatted string
         */
        private int positionAfterNumeralN(String s, int n) {
            int numeralsFound = 0;

            if (n == 0) {
                return 0;
            }

            for (int i = 0; i < s.length(); i++) {
                if(s.substring(i,i+1).matches("[0-9]")) {
                    if(++numeralsFound == n) {
                        return i + 1;
                    }
                }
            }
            return s.length();
        }
    }
}
</code>```

At a highlevel, what that does is:

Determine which numbers were actually in the string after it was edited

Process the edit to the numeral version of the string if the numbers weren't edited

Convert the numeral back to a formatted string

Determine, where the cursor should be based on where editing began and how much text was added

It also nicely handles edge cases like completely deleted input, integer overflow and erroneous input.

Body:
The answers here lack a method to handle actual user input, such as deleting characters or copying and pasting. This is an EditText field. If you want to add formatting in, you need to support editing that formatted value.

This implementation still has a deficiency depending on your use case. I didn't care about decimal values and assumed I would only be handling whole numbers. There's enough of how to handle that on this page and how to handle actual internationalization that I'll leave that as an exercise to the reader. If you need to do that, it shouldn't be too difficult to add "." to the regular expression to keep the decimal; you'll just have to be careful to acknowledge the numeral string still has a non numerical character.

This is designed to be used throughout multiple activities. New it once, give it your edit text and your data model and ignore it. The model binding can be removed if you don't need it.

public class EditNumberFormatter implements TextWatcher {

    private EditText watched;
    private Object model;
    private Field field;
    private IEditNumberFormatterListener listener;

    private ActiveEdit activeEdit;

    /**
     * Binds an EditText to a data model field (Such as a room entity's public variable)
     * Whenever the edit text is changed, the text is formatted to the local numerical format.
     *
     * Handles copy/paste/backspace/select&delete/typing
     *
     * @param model An object with a public field to bind to
     * @param fieldName A field defined on the object
     * @param watched The edit text to watch for changes
     * @param listener Another object that wants to know after changes & formatting are done.
     */
    public EditNumberFormatter(Object model, String fieldName, EditText watched, IEditNumberFormatterListener listener) {

        this.model = model;
        this.watched = watched;
        this.listener = listener;

        try {
            field = model.getClass().getDeclaredField(fieldName);
        } catch(Exception e) { }

        watched.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        activeEdit = new ActiveEdit(s.toString(), start, count);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        activeEdit.recordChangedText(s.toString(),count);
    }

    @Override
    public void afterTextChanged(Editable s) {
        this.watched.removeTextChangedListener(this);

        activeEdit.processEdit(); // Override the user's edit of the formatted string with what the user intended to do to the numeral.

        watched.setText(activeEdit.getCurrentFormattedString());
        watched.setSelection(activeEdit.getCursorPosition());
        updateDataModel(activeEdit.getCurrentRawValue());

        listener.FormatUpdated(watched.getId(), activeEdit.getCurrentRawValue(), activeEdit.getCurrentFormattedString());

        this.watched.addTextChangedListener(this);
    }

    private void updateDataModel(int rawValue) {
        try {
            field.set(model, rawValue);
        } catch (IllegalAccessException e) { }
    }

    /**
     * Tracks the active editing of an EditText formatted for integer input
     */
    private class ActiveEdit {

        private String priorFormattedString;
        private String currentFormattedString;
        private String currentNumericalString;
        private int currentRawValue;

        private boolean removal;
        private boolean addition;

        private int changeStart;
        private int removedCount;
        private int additionCount;

        private int numeralCountBeforeSelection;
        private int numeralCountAdded;
        private int numeralCountRemoved;

        /**
         * Call in beforeEdit to begin recording changes
         *
         * @param beforeEdit string before edit began
         * @param start start position of edit
         * @param removed number of characters removed
         */
        public ActiveEdit(String beforeEdit, int start, int removed) {
            removal = (removed > 0);

            priorFormattedString = beforeEdit;
            changeStart = start;
            removedCount = removed;

            numeralCountBeforeSelection = countNumerals(priorFormattedString.substring(0, changeStart));
            numeralCountRemoved = countNumerals(priorFormattedString.substring(changeStart, changeStart + removedCount));
        }

        /**
         * Call in onTextChanged to record new text and how many characters were added after changeStart
         *
         * @param afterEdit new string after user input
         * @param added how many characters were added (same start position as before)
         */
        public void recordChangedText(String afterEdit, int added) {
            addition = (added > 0);
            additionCount = added;
            numeralCountAdded = countNumerals(afterEdit.substring(changeStart, changeStart + additionCount));

            currentNumericalString = afterEdit.replaceAll("[^0-9]", "");
        }

        /**
         * Re-process the edit for our particular formatting needs.
         */
        public void processEdit() {
            forceRemovalPastFormatting();
            finalizeEdit();
        }

        /**
         * @return Integer value of the field after an edit.
         */
        public int getCurrentRawValue() {
            return currentRawValue;
        }

        /**
         * @return Formatted number after an edit.
         */
        public String getCurrentFormattedString() {
            return currentFormattedString;
        }

        /**
         * @return Cursor position after an edit
         */
        public int getCursorPosition() {
            int numeralPosition = numeralCountBeforeSelection + numeralCountAdded;
            return positionAfterNumeralN(currentFormattedString,numeralPosition);
        }

        /**
         * If a user deletes a value, but no numerals are deleted, then delete the numeral proceeding
         * their cursor. Otherwise, we'll just add back the formatting character.
         *
         * Assumes formatting uses a single character and not multiple formatting characters in a row.
         */
        private void forceRemovalPastFormatting() {
            if (removal && (!addition) && (numeralCountRemoved == 0)) {
                String before = currentNumericalString.substring(0, numeralCountBeforeSelection - 1);
                String after = currentNumericalString.substring(numeralCountBeforeSelection);

                currentNumericalString =  before + after;
                numeralCountRemoved++;
                numeralCountBeforeSelection--;
            }
        }

        /**
         * Determine the result of the edit, including new display value and raw value
         */
        private void finalizeEdit() {
            currentFormattedString = "";
            currentRawValue = 0;
            if (currentNumericalString.length() == 0) {
                return; // There is no entry now.
            }
            try {
                currentRawValue = Integer.parseInt(currentNumericalString);
            } catch (NumberFormatException nfe) {
                abortEdit();  // Value is not an integer, return to previous state.
                return;
            }
            currentFormattedString = String.format("%,d", currentRawValue);
        }

        /**
         * Current text, same as the old text.
         */
        private void abortEdit() {
            currentFormattedString = priorFormattedString;
            currentNumericalString = currentFormattedString.replaceAll("[^0-9]", "");
            numeralCountRemoved = 0;
            numeralCountAdded = 0;
            try {
                currentRawValue = Integer.parseInt(currentNumericalString);
            } catch (Exception e) { currentRawValue = 0; }
        }

        /**
         * Determine how many numerical characters exist in a string
         * @param s
         * @return the number of numerical characters in the string
         */
        private int countNumerals(String s) {
            String newString = s.replaceAll("[^0-9]", "");
            return newString.length();
        }

        /**
         * Determine how to place a cursor after the Nth Numeral in a formatted string.
         * @param s - Formatted string
         * @param n - The position of the cursor should follow the "Nth" number in the string
         * @return the position of the nth character in a formatted string
         */
        private int positionAfterNumeralN(String s, int n) {
            int numeralsFound = 0;

            if (n == 0) {
                return 0;
            }

            for (int i = 0; i < s.length(); i++) {
                if(s.substring(i,i+1).matches("[0-9]")) {
                    if(++numeralsFound == n) {
                        return i + 1;
                    }
                }
            }
            return s.length();
        }
    }
}

At a highlevel, what that does is:

Determine which numbers were actually in the string after it was edited

Process the edit to the numeral version of the string if the numbers weren't edited

Convert the numeral back to a formatted string

Determine, where the cursor should be based on where editing began and how much text was added

It also nicely handles edge cases like completely deleted input, integer overflow and erroneous input.


问:
memset for a given range in an array
I know how we use memset to set the contents of an array to a particular value. Now, I am interested in something that does the same for a given range.

```<code>scanf("%d %d",&a,&b);
//set the content from A[a] to A[b] as '0' without looping
</code>```

I don't want to go through for loop. Please tell if there is some other and efficient method to achieve this.

答:
Assigning values with memset works only with 2 values : 0 and -1,

Rest will only give garbage values

Still, Let me help you to use memset for a range.

I'm using an example to explain your query below:

```<code>#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a[10]; // Array of 10 elements with val of 0;
    memset(a,0,sizeof(a));
    // Sets all array elements to 0

    memset(a+2,-1,sizeof(int)*5);
    // Sets value of array elements from 2 to 6 index equals to -1

    for(int i=0;i<10;i++)
       cout<<a[i]<<" ";
       cout<<endl;

       return 0;
}
</code>```

Output: 0 0 -1 -1 -1 -1 -1 0 0 0

* I've checked the code on various IDE's before posting.
 Hope it helps a bit!

ContentLicense: CC BY-SA 3.0

Title: memset for a given range in an array

Body:
I know how we use memset to set the contents of an array to a particular value. Now, I am interested in something that does the same for a given range.

scanf("%d %d",&a,&b);
//set the content from A[a] to A[b] as '0' without looping

I don't want to go through for loop. Please tell if there is some other and efficient method to achieve this.

Body:
Assigning values with memset works only with 2 values : 0 and -1,

Rest will only give garbage values

Still, Let me help you to use memset for a range.

I'm using an example to explain your query below:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a[10]; // Array of 10 elements with val of 0;
    memset(a,0,sizeof(a));
    // Sets all array elements to 0

    memset(a+2,-1,sizeof(int)*5);
    // Sets value of array elements from 2 to 6 index equals to -1

    for(int i=0;i<10;i++)
       cout<<a[i]<<" ";
       cout<<endl;

       return 0;
}

Output: 0 0 -1 -1 -1 -1 -1 0 0 0

* I've checked the code on various IDE's before posting.
 Hope it helps a bit!


问:
Neural network architecture recomendation
Its my first time working with neural networks and I have been given the task of predicting some values of a dataset and I could make good use of some help on deciding which is the smartest architecture for the task. I'm working with Keras using Tensorflow as backend.

I'm not going into details but basically I have performed lots of CFD simulations on similar but slightly different geometries to obtain a stress value on the surface of the geometries. All the geometries have the same conectivity and number of nodes and I have the stress value for each of those nodes.

Simply put, I have an input matrix of [2500,3,300] where 2500 is the amount of nodes in each geometry, 3 represents the x,y,z coordinates in space of each node on the mesh and 300 is the total number of geometries I have. For the stress I have an output matrix of [2500,300] where 2500 is the value of stress for each node and 300 once again corresponds to the number of instances. I would like to train some kind of neural network so I can predict the stress values given the geometry.

I have been basing my architecture on the following paper but I can't not make use of the part in which the convolutional networks are employed. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5805990/

The simplest approach I can think of is a fully connected network but I struggle to figure out the layer architecture to relate the 3D matrix of the geometry to the 2D of the output stress matrix with my scarce knowledge of the subject.

Any suggestiong is more than welcomed. Thanks for your help!!!

答:
Since I have been working with stress values prediction using DL, I would like to recommend you to work with CNN models which you have filters due to intelligent learning capacity even correlation between parameters your suppose to following. Nevertheless RNN and its promised version like LSTM & GRU have good performance on sufficient data if you have.  Unfortunately I can't address you to paper because that this issue is still under study!

Another point I can turn out is reshape of your data is kind of important when you feed to NN models especially when you are dealing with time-series data.


问:
Retrieve inserted row ID in SQL
How do I retrieve the ID of an inserted row in SQL?

Users Table:

```<code>Column  | Type
--------|--------------------------------
ID      | * Auto-incrementing primary key
Name    |
Age     |
</code>```

Query Sample:

```<code>insert into users (Name, Age) values ('charuka',12)
</code>```

答:
I had the same need and found this answer ..

This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.

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

```<code>CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]

 @comp_name varchar(55) = 'Big Company',

 @comp_regno nchar(8) = '12345678',

 @comp_email nvarchar(50) = 'no1@home.com',

 @recID INT OUTPUT
</code>```

-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab

```<code>AS
 Begin

  SET NOCOUNT ON

  DECLARE @tableVar TABLE (tempID INT)
</code>```

-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.

```<code>  INSERT INTO comp(comp_name, comp_regno, comp_email)

  OUTPUT inserted.comp_id INTO @tableVar
</code>```

-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.

```<code>  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)
</code>```

-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.

```<code>  INSERT INTO staff(Staff_comp_id)
  VALUES (@recID)

 End
</code>```

-- So there you go. I was looking for something like this for ages, with this detailed break down, I hope this helps.

ContentLicense: CC BY-SA 2.5

Title: Retrieve inserted row ID in SQL

Body:
How do I retrieve the ID of an inserted row in SQL?

Users Table:

Column  | Type
--------|--------------------------------
ID      | * Auto-incrementing primary key
Name    |
Age     |

Query Sample:

insert into users (Name, Age) values ('charuka',12)

Body:
I had the same need and found this answer ..

This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.

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

CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]

 @comp_name varchar(55) = 'Big Company',

 @comp_regno nchar(8) = '12345678',

 @comp_email nvarchar(50) = 'no1@home.com',

 @recID INT OUTPUT

-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab

AS
 Begin

  SET NOCOUNT ON

  DECLARE @tableVar TABLE (tempID INT)

-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.

  INSERT INTO comp(comp_name, comp_regno, comp_email)

  OUTPUT inserted.comp_id INTO @tableVar

-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.

  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)

-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.

  INSERT INTO staff(Staff_comp_id)
  VALUES (@recID)

 End

-- So there you go. I was looking for something like this for ages, with this detailed break down, I hope this helps.


问:
Arduino Serial library cannot find "availableForWrite()" function
I'm trying to get Arduino to send some chars back to my raspberry pi via the serial USB port.

However, when I try to use the function "Serial.availableForWrite()", the compiler failed with:
error: ‘class HardwareSerial’ has no member named ‘availableForWrite’
the rest of the code piece works fine though.

Here is the entire code:

void setup() {
  // connect to serial
  Serial.begin(9600);
}

void loop() {

  // write value
  if (Serial.availableForWrite() > 0) {
    Serial.write("0.587");
  }
  Serial.write("Error");
  delay(1000);
}
```

I am pretty sure my Arduino IDE is up to date, and also I don't think I have spelling mistakes. What could be causing this problem?

答: i dont have any problems with this code neither when compiling and i can even upload this sketch to my arduino uno this problem might be ocuring due to the usage of an raspbery pei maybe try and use an arduino board</p>

Body:
I'm trying to get Arduino to send some chars back to my raspberry pi via the serial USB port.

However, when I try to use the function "Serial.availableForWrite()", the compiler failed with:
error: ‘class HardwareSerial’ has no member named ‘availableForWrite’
the rest of the code piece works fine though.

Here is the entire code:

void setup() {
  // connect to serial
  Serial.begin(9600);
}

void loop() {

  // write value
  if (Serial.availableForWrite() > 0) {
    Serial.write("0.587");
  }
  Serial.write("Error");
  delay(1000);
}

I am pretty sure my Arduino IDE is up to date, and also I don't think I have spelling mistakes. What could be causing this problem?


问:
why environment variable removed from my OS?
I have several environment variable from a text.txt file , i set them with export variable = value manually one by one myself in terminal Ubuntu 18.04 but now no one of them appear in printenv !
I need to set them somehow never remove again(unless i delete them myself).any idea?thank you

答:
Add your variables in ~/.bashrc or in /etc/environment this way on every reboot they will be exported.
in bashrc should be like this

```<code>export VARIABLE='<value>'
</code>```

in /etc/environment

```<code>VARIABLE=<value>
</code>```

Body:
Add your variables in ~/.bashrc or in /etc/environment this way on every reboot they will be exported.
in bashrc should be like this

export VARIABLE='<value>'

in /etc/environment

VARIABLE=<value>


问:
Use an explicit return of undefined as type guard and/or filter?
I am trying to combine the array methods filter and map into one function called malter. I have come so far:

type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
  malter<S = any>(mapFn: mapFn<T, S>): S[];
}

function notUndefined<T>(v: T | undefined): v is T {
  return typeof v !== "undefined"
}

Array.prototype.malter = function malter<T, S = any>(mapFn: mapFn<T, S>): S[] {
  return this.reduce(function(acc: S[], val: T, index: number, orgArr: T[]) {
    const el = mapFn(val, index, orgArr);
    if (notUndefined(el)) {
      acc.push(el);
    }
    return acc;
  }, []);
};
```

<p>It basically works.
But when using it, it throws a TypeError in line 5-7.
Another test function that did implicitly return undefined did also throw that error.</p>

```Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'."
```

<pre class="lang-ts prettyprint-override"><code>const test = [2, 3, 4, 5, 3];

function test1(): string[] {
   return test.malter<number, string>(num =>
      num > 3
       ? num.toFixed(2)
       : undefined
   );
}
</code>```

A solution that would work type savely, is to provide 2 arguments for malter. A filter and a map function and call them seperately. That would ensure type savety, but also make it less simple.

Sure I could simply do that in line 5-7:

(num > 3 ? num.toFixed(2) : undefined) as string
```

It may be the best compromise?
What do you think? Is there a solution I didn't think of, or do you go with a compromise?

答:
You are using undefined as the value to be filtered. We can allow the inner function to return undefined and then filter it out using Exclude, much like the implementation does:

```<code>type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
    malter<S>(mapFn: mapFn<T, S>): Exclude<S, undefined>[];
}

function notUndefined<T>(v: T | undefined): v is T {
    return typeof v !== "undefined"
}

Array.prototype.malter = function malter<T, S>(mapFn: mapFn<T, S>): Exclude<S, undefined>[] {
    return this.reduce(function (acc: S[], val: T, index: number, orgArr: T[]) {
        const el = mapFn(val, index, orgArr);
        if (notUndefined(el)) {
            acc.push(el);
        }
        return acc;
    }, []);
};

const test = [2, 3, 4, 5, 3];

function test1(): string[] {
    return test.malter(num =>
        num > 3
            ? num.toFixed(2)
            : undefined
    );
}
</code>```

Body:
I am trying to combine the array methods filter and map into one function called malter. I have come so far:

type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
  malter<S = any>(mapFn: mapFn<T, S>): S[];
}

function notUndefined<T>(v: T | undefined): v is T {
  return typeof v !== "undefined"
}

Array.prototype.malter = function malter<T, S = any>(mapFn: mapFn<T, S>): S[] {
  return this.reduce(function(acc: S[], val: T, index: number, orgArr: T[]) {
    const el = mapFn(val, index, orgArr);
    if (notUndefined(el)) {
      acc.push(el);
    }
    return acc;
  }, []);
};

It basically works.
But when using it, it throws a TypeError in line 5-7.
Another test function that did implicitly return undefined did also throw that error.

Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'."

const test = [2, 3, 4, 5, 3];

function test1(): string[] {
   return test.malter<number, string>(num =>
      num > 3
       ? num.toFixed(2)
       : undefined
   );
}

A solution that would work type savely, is to provide 2 arguments for malter. A filter and a map function and call them seperately. That would ensure type savety, but also make it less simple.

Sure I could simply do that in line 5-7:

(num > 3 ? num.toFixed(2) : undefined) as string

It may be the best compromise?
What do you think? Is there a solution I didn't think of, or do you go with a compromise?

Body:
You are using undefined as the value to be filtered. We can allow the inner function to return undefined and then filter it out using Exclude, much like the implementation does:

type mapFn<T, S> = (value: T, index: number, originalArray: Readonly<T[]>) => S;

interface Array<T> {
    malter<S>(mapFn: mapFn<T, S>): Exclude<S, undefined>[];
}

function notUndefined<T>(v: T | undefined): v is T {
    return typeof v !== "undefined"
}

Array.prototype.malter = function malter<T, S>(mapFn: mapFn<T, S>): Exclude<S, undefined>[] {
    return this.reduce(function (acc: S[], val: T, index: number, orgArr: T[]) {
        const el = mapFn(val, index, orgArr);
        if (notUndefined(el)) {
            acc.push(el);
        }
        return acc;
    }, []);
};

const test = [2, 3, 4, 5, 3];

function test1(): string[] {
    return test.malter(num =>
        num > 3
            ? num.toFixed(2)
            : undefined
    );
}


问:
Create weak delegate of Dynamic Method(ref object,object[] arr)
Source code:https://www.pastefile.com/4mzhyg

I'm trying to create delegate of format:

```<code>    public delegate TReturn MethodCallerR<TTarget, TReturn>(ref TTarget target, object[] args);

 /// <summary>
    /// Generates a strongly-typed open-instance delegate to invoke the specified method
    /// </summary>
    public static MethodCallerR<TTarget, TReturn> DelegateForCallR<TTarget, TReturn>(this MethodInfo method) {

        int key = GetKey<TTarget, TReturn>(method, kMethodCallerName);
        Delegate result;
        if (cache.TryGetValue(key, out result))
            return (MethodCallerR<TTarget, TReturn>)result;

        return GenDelegateForMember<MethodCallerR<TTarget, TReturn>, MethodInfo>(
                method, key, kMethodCallerName, GenMethodInvocationR<TTarget>,
                typeof(TReturn), typeof(TTarget).MakeByRefType(), typeof(object[]));
    }
</code>```

weak type function:

```<code>    public static MethodCallerR<object, object> DelegateForCallR(this MethodInfo method) {
        return DelegateForCallR<object, object>(method);
    }
</code>```

delegate creator:

```<code>   static TDelegate GenDelegateForMember<TDelegate, TMember>(TMember member, int key, string dynMethodName,
            Action<TMember> generator, Type returnType, params Type[] paramTypes)
    where TMember : MemberInfo
    where TDelegate : class {
        var dynMethod = new DynamicMethod(dynMethodName, returnType, paramTypes, true);

        emit.il = dynMethod.GetILGenerator();
        generator(member);

        var result = dynMethod.CreateDelegate(typeof(TDelegate));
        cache[key] = result;
        return (TDelegate)(object)result;
    }
</code>```

and IL code generator:

```<code> static void GenMethodInvocationR<TTarget>(MethodInfo method) {

        var weaklyTyped = typeof(TTarget) == typeof(object);

        // push arguments in order to call method
        var prams = method.GetParameters();
        var imax = prams.Length;
        for (int i = 0; i < imax; i++) {

            emit.ldarg1()        // stack<= paramsValuesArray[] //push array
            .ldc_i4(i)        // stack<= index push(index)
            .ldelem_ref();    // stack[top]<=paramsValuesArray[i]

            var param = prams[i];
            var dataType = param.ParameterType;

            if (dataType.IsByRef)
                dataType = dataType.GetElementType();

            emit.unbox_any(dataType);

            emit.declocal(dataType);

            emit.stloc(i);

        }

        if (!method.IsStatic)
        {
            var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
            emit.ldarg0();  //stack[top]=target;
            emit.ldind_ref();//stack[top]=ref target;
            if (weaklyTyped)
                emit.unbox_any(targetType); //stack[top]=(TargetType)target;
        }

        //load parms from local 'list' to evaluation 'steak'
        for (int i = 0; i < imax; i++) {
            var param = prams[i];

            emit.ifbyref_ldloca_else_ldloc(i, param.ParameterType);
        }

        // perform the correct call (pushes the result)
        emit.callorvirt(method);

        //check of ref and out params and
        for (int i = 0; i < prams.Length; i++) {

            var paramType = prams[i].ParameterType;
            if (paramType.IsByRef)
            {
                var byRefType = paramType.GetElementType();
                emit.ldarg1() // stack<= paramsValuesArray[]
                .ldc_i4(i) // stack<= i //push(index)
                .ldloc(i); // stack<= list[i] //push local list element at 'i' on steak
                if (byRefType.IsValueType)
                    emit.box(byRefType);   // if ex. stack[top] =(object)stack[top]
                emit.stelem_ref(); //  // paramsValuesArray[i]= pop(stack[top]);
            }
        }

        if (method.ReturnType == typeof(void))
            emit.ldnull();
        else if (weaklyTyped)
            emit.ifvaluetype_box(method.ReturnType);

        emit.ret();

    }
</code>```

Example for stuct I'm using is Vector3 with Set method:

```<code>  public struct Vector3{
    public float x;
    public float y;
    public float z;

    public Vector3(float x,float y,float z){
        this.x=x;
        this.y=y;
        this.z=z;
    }

    public void Set(float x,float y,float z){
        this.x=x;
        this.y=y;
        this.z=z;
    }
}
</code>```

so I'm doing:

```<code>   object vector3Obj=new Vector3(4,5,6);
    MethodInfo method=typeof(Vector3).GetMethod("Set");
      MethodCallerR<object,object> m = methodInfo.DelegateForCallR();
             m(ref vector3Obj,new object[]{1f,2f,3f});
    Console.Write(vector3.x);
</code>```

Never get to the executing delegate, but it blows when it calls Delegate.CreateDelegate:

see line:
dynMethod.CreateDelegate(typeof(TDelegate));

with error:

InvalidProgramException: Invalid IL code in (wrapper dynamic-method) object:MC<> (object&,object[]): IL_004f: call      0x00000009
  refereeing that actual IL code has error at emit.call(method), but when I use helper function:

```<code>    FastReflection.GenDebugAssembly<object>("my.dll",null,null,methodInfo,vector3Obj.GetType(),new Type[]{typeof(float),typeof(float),typeof(float)});
</code>```

which will generate my.dll and open with ILSpy I can see that method from same IL code is generated just fine.

```<code>    public static object MethodCallerR(ref object ptr, object[] array)
{
    float num = (float)array[0];
    float num2 = (float)array[1];
    float num3 = (float)array[2];
    ((Vector3)ptr).Set(num, num2, num3);
    return null;
}
</code>```

答:
I found solution. First although generated method was correct wasn't setting reference passed. So I tried to generated another method.

```<code>public static object MethodCallerR(ref object ptr, object[] array)
{
    float num = (float)array[0];
    float num2 = (float)array[1];
    float num3 = (float)array[2];
    Vector3 vector = (Vector3)ptr;
    vector.Set(num, num2, num3);
    ptr = vector;
    return null;
}
</code>```

So I changed IL code to:

```<code>      static void GenMethodInvocationR<TTarget>(MethodInfo method) {

        //this version winxalex generates more optimized code
        //Generated
        //            public static object MethodCallerR(ref object ptr, object[] array)
        //            {
        //                float num = (float)array[0];
        //                float num2 = (float)array[1];
        //                float num3 = (float)array[2];
        //                Vector3 vector = (Vector3)ptr;
        //                vector.Set(num, num2, num3);
        //                ptr = vector;
        //                return null;
        //            }
        //
        var weaklyTyped = typeof(TTarget) == typeof(object);
        var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
        var isNotStatic = !method.IsStatic;
        LocalBuilder targetLocal = null;

        // push arguments in order to call method
        var prams = method.GetParameters();
        var imax = prams.Length;
        for (int i = 0; i < imax; i++) {

            emit.ldarg1()        // stack<= paramsValuesArray[] //push array
            .ldc_i4(i)        // stack<= index push(index)
            .ldelem_ref();    // stack[top]<=paramsValuesArray[i]

            var param = prams[i];
            var dataType = param.ParameterType;

            if (dataType.IsByRef)
                dataType = dataType.GetElementType();

            emit.unbox_any(dataType);

            emit.declocal(dataType);

            emit.stloc(i);

        }

        if (isNotStatic)
        {

            emit.ldarg0();  //stack[top]=target;
            emit.ldind_ref();//stack[top]=ref target;
            if (weaklyTyped)
                emit.unbox_any(targetType); //stack[top]=(TargetType)target;

            targetLocal = emit.declocal(targetType); //TargetType tmpTarget; list[0]=tmpTarget;

            emit.stloc(targetLocal)     //list[0]=stack.pop();
            .ifclass_ldloc_else_ldloca(targetLocal, targetType);
        }

        //load parms from local 'list' to evaluation 'steak'
        for (int i = 0; i < imax; i++) {
            var param = prams[i];

            emit.ifbyref_ldloca_else_ldloc(i, param.ParameterType);
        }

        // perform the correct call (pushes the result)
        emit.callorvirt(method);

        if (isNotStatic && targetType.IsValueType) {
            emit.ldarg0().ldloc(targetLocal).box(targetType).stind_ref();
        }

        //check of ref and out params and
        for (int i = 0; i < prams.Length; i++) {

            var paramType = prams[i].ParameterType;
            if (paramType.IsByRef)
            {
                var byRefType = paramType.GetElementType();
                emit.ldarg1() // stack<= paramsValuesArray[]
                .ldc_i4(i) // stack<= i //push(index)
                .ldloc(i); // stack<= list[i] //push local list element at 'i' on steak

                if (byRefType.IsValueType)
                    emit.box(byRefType);   // if ex. stack[top] =(object)stack[top]
                emit.stelem_ref(); //  // paramsValuesArray[i]= pop(stack[top]);
            }
        }

        if (method.ReturnType == typeof(void))
            emit.ldnull();
        else if (weaklyTyped)
            emit.ifvaluetype_box(method.ReturnType);

        emit.ret();

        //vexe orignial modified by winxalex to use reference of object (ref obj) and to return value to reference

        //GENERATES
        //            public static object MethodCallerR(ref object ptr, object[] array)
        //            {
        //                Vector3 vector = (Vector3)ptr;
        //                float num = (float)array[0];
        //                float arg_56_1 = num;
        //                float num2 = (float)array[1];
        //                float arg_56_2 = num2;
        //                float num3 = (float)array[2];
        //                vector.Set(arg_56_1, arg_56_2, num3);
        //                ptr = vector;
        //                return null;
        //            }

        //            var weaklyTyped = typeof(TTarget) == typeof(object);
        //            var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
        //            // push target if not static (instance-method. in that case first arg is always 'this')
        //            if (!method.IsStatic)
        //            {
        //
        //                emit.declocal(targetType); //TargetType tmpTarget; list[0]=tmpTarget;
        //                emit.ldarg0();  //stack[0]=target;
        //                emit.ldind_ref();//stack[top]=ref target;
        //                if (weaklyTyped)
        //                    emit.unbox_any(targetType); //stack[0]=(TargetType)target;
        //                emit.stloc0()     //list[0]=stack.pop();
        //                .ifclass_ldloc_else_ldloca(0, targetType);
        //                // if (type.IsValueType) stack[0]=list[0].address, else stack[0]=list[0];
        //                // if (type.IsValueType) emit.ldloca(idx); else emit.ldloc(idx); return this;
        //            }
        //
        //            // if method wasn't static that means we declared a temp local to load the target
        //            // that means our local variables index for the arguments start from 1
        //            int localVarStart = method.IsStatic ? 0 : 1;
        //
        //            // push arguments in order to call method
        //            var prams = method.GetParameters();
        //            for (int i = 0, imax = prams.Length; i < imax; i++) {
        //                emit.ldarg1()        // stack<= paramsValuesArray //push array
        //                .ldc_i4(i)        // stack<= index push index
        //                .ldelem_ref();    // pop array, index and push array[index]
        //
        //                var param = prams[i];
        //                var dataType = param.ParameterType;
        //
        //                if (dataType.IsByRef)
        //                    dataType = dataType.GetElementType();
        //
        //                var tmp = emit.declocal(dataType);
        //                emit.unbox_any(dataType)
        //                .stloc(tmp)
        //                .ifbyref_ldloca_else_ldloc(tmp, param.ParameterType);
        //
        ////v2
        //
        //
        ////                emit.unbox_any(dataType);
        ////
        ////                emit.declocal(dataType);
        ////                emit.stloc(i+localVarStart)
        ////                .ifbyref_ldloca_else_ldloc(i+localVarStart, param.ParameterType);
        //
        //
        //            }
        //
        //            // perform the correct call (pushes the result)
        //            emit.callorvirt(method);
        //
        //
        //            if (!method.IsStatic && targetType.IsValueType)
        //                emit.ldarg0().ldloc0().box(targetType).stind_ref();
        //
        //
        //            for (int i = 0; i < prams.Length; i++) {
        //                var paramType = prams[i].ParameterType;
        //                if (paramType.IsByRef)
        //                {
        //                    var byRefType = paramType.GetElementType();
        //                    emit.ldarg1() // stack<= params[]
        //                    .ldc_i4(i) // stack<= i
        //                    .ldloc(i + localVarStart); // stack<= list[i+localVarStart]
        //                    if (byRefType.IsValueType)
        //                        emit.box(byRefType);   // if ex. stack =(object)stack[top]
        //                    emit.stelem_ref(); //  // stack:paramsValuesArray[i]= list[i+localVarStart];
        //                }
        //            }
        //
        //            if (method.ReturnType == typeof(void))
        //                emit.ldnull();
        //            else if (weaklyTyped)
        //                emit.ifvaluetype_box(method.ReturnType);
        //
        //            emit.ret();

    }
</code>```

Body:
Source code:https://www.pastefile.com/4mzhyg

I'm trying to create delegate of format:

    public delegate TReturn MethodCallerR<TTarget, TReturn>(ref TTarget target, object[] args);

 ///
    /// Generates a strongly-typed open-instance delegate to invoke the specified method
    ///
    public static MethodCallerR<TTarget, TReturn> DelegateForCallR<TTarget, TReturn>(this MethodInfo method) {

        int key = GetKey<TTarget, TReturn>(method, kMethodCallerName);
        Delegate result;
        if (cache.TryGetValue(key, out result))
            return (MethodCallerR<TTarget, TReturn>)result;

        return GenDelegateForMember<MethodCallerR<TTarget, TReturn>, MethodInfo>(
                method, key, kMethodCallerName, GenMethodInvocationR<TTarget>,
                typeof(TReturn), typeof(TTarget).MakeByRefType(), typeof(object[]));
    }

weak type function:

    public static MethodCallerR<object, object> DelegateForCallR(this MethodInfo method) {
        return DelegateForCallR<object, object>(method);
    }

delegate creator:

   static TDelegate GenDelegateForMember<TDelegate, TMember>(TMember member, int key, string dynMethodName,
            Action<TMember> generator, Type returnType, params Type[] paramTypes)
    where TMember : MemberInfo
    where TDelegate : class {
        var dynMethod = new DynamicMethod(dynMethodName, returnType, paramTypes, true);

        emit.il = dynMethod.GetILGenerator();
        generator(member);

        var result = dynMethod.CreateDelegate(typeof(TDelegate));
        cache[key] = result;
        return (TDelegate)(object)result;
    }

and IL code generator:

 static void GenMethodInvocationR<TTarget>(MethodInfo method) {

        var weaklyTyped = typeof(TTarget) == typeof(object);

        // push arguments in order to call method
        var prams = method.GetParameters();
        var imax = prams.Length;
        for (int i = 0; i < imax; i++) {

            emit.ldarg1()        // stack<= paramsValuesArray[] //push array
            .ldc_i4(i)        // stack<= index push(index)
            .ldelem_ref();    // stack[top]<=paramsValuesArray[i]

            var param = prams[i];
            var dataType = param.ParameterType;

            if (dataType.IsByRef)
                dataType = dataType.GetElementType();

            emit.unbox_any(dataType);

            emit.declocal(dataType);

            emit.stloc(i);

        }

        if (!method.IsStatic)
        {
            var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
            emit.ldarg0();  //stack[top]=target;
            emit.ldind_ref();//stack[top]=ref target;
            if (weaklyTyped)
                emit.unbox_any(targetType); //stack[top]=(TargetType)target;
        }

        //load parms from local 'list' to evaluation 'steak'
        for (int i = 0; i < imax; i++) {
            var param = prams[i];

            emit.ifbyref_ldloca_else_ldloc(i, param.ParameterType);
        }

        // perform the correct call (pushes the result)
        emit.callorvirt(method);

        //check of ref and out params and
        for (int i = 0; i < prams.Length; i++) {

            var paramType = prams[i].ParameterType;
            if (paramType.IsByRef)
            {
                var byRefType = paramType.GetElementType();
                emit.ldarg1() // stack<= paramsValuesArray[]
                .ldc_i4(i) // stack<= i //push(index)
                .ldloc(i); // stack<= list[i] //push local list element at 'i' on steak
                if (byRefType.IsValueType)
                    emit.box(byRefType);   // if ex. stack[top] =(object)stack[top]
                emit.stelem_ref(); //  // paramsValuesArray[i]= pop(stack[top]);
            }
        }

        if (method.ReturnType == typeof(void))
            emit.ldnull();
        else if (weaklyTyped)
            emit.ifvaluetype_box(method.ReturnType);

        emit.ret();

    }

Example for stuct I'm using is Vector3 with Set method:

  public struct Vector3{
    public float x;
    public float y;
    public float z;

    public Vector3(float x,float y,float z){
        this.x=x;
        this.y=y;
        this.z=z;
    }

    public void Set(float x,float y,float z){
        this.x=x;
        this.y=y;
        this.z=z;
    }
}

so I'm doing:

   object vector3Obj=new Vector3(4,5,6);
    MethodInfo method=typeof(Vector3).GetMethod("Set");
      MethodCallerR<object,object> m = methodInfo.DelegateForCallR();
             m(ref vector3Obj,new object[]{1f,2f,3f});
    Console.Write(vector3.x);

Never get to the executing delegate, but it blows when it calls Delegate.CreateDelegate:

see line:
dynMethod.CreateDelegate(typeof(TDelegate));

with error:

InvalidProgramException: Invalid IL code in (wrapper dynamic-method) object:MC<> (object&,object[]): IL_004f: call      0x00000009
  refereeing that actual IL code has error at emit.call(method), but when I use helper function:

    FastReflection.GenDebugAssembly<object>("my.dll",null,null,methodInfo,vector3Obj.GetType(),new Type[]{typeof(float),typeof(float),typeof(float)});

which will generate my.dll and open with ILSpy I can see that method from same IL code is generated just fine.

    public static object MethodCallerR(ref object ptr, object[] array)
{
    float num = (float)array[0];
    float num2 = (float)array[1];
    float num3 = (float)array[2];
    ((Vector3)ptr).Set(num, num2, num3);
    return null;
}

Body:
I found solution. First although generated method was correct wasn't setting reference passed. So I tried to generated another method.

public static object MethodCallerR(ref object ptr, object[] array)
{
    float num = (float)array[0];
    float num2 = (float)array[1];
    float num3 = (float)array[2];
    Vector3 vector = (Vector3)ptr;
    vector.Set(num, num2, num3);
    ptr = vector;
    return null;
}

So I changed IL code to:

      static void GenMethodInvocationR<TTarget>(MethodInfo method) {

        //this version winxalex generates more optimized code
        //Generated
        //            public static object MethodCallerR(ref object ptr, object[] array)
        //            {
        //                float num = (float)array[0];
        //                float num2 = (float)array[1];
        //                float num3 = (float)array[2];
        //                Vector3 vector = (Vector3)ptr;
        //                vector.Set(num, num2, num3);
        //                ptr = vector;
        //                return null;
        //            }
        //
        var weaklyTyped = typeof(TTarget) == typeof(object);
        var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
        var isNotStatic = !method.IsStatic;
        LocalBuilder targetLocal = null;

        // push arguments in order to call method
        var prams = method.GetParameters();
        var imax = prams.Length;
        for (int i = 0; i < imax; i++) {

            emit.ldarg1()        // stack<= paramsValuesArray[] //push array
            .ldc_i4(i)        // stack<= index push(index)
            .ldelem_ref();    // stack[top]<=paramsValuesArray[i]

            var param = prams[i];
            var dataType = param.ParameterType;

            if (dataType.IsByRef)
                dataType = dataType.GetElementType();

            emit.unbox_any(dataType);

            emit.declocal(dataType);

            emit.stloc(i);

        }

        if (isNotStatic)
        {

            emit.ldarg0();  //stack[top]=target;
            emit.ldind_ref();//stack[top]=ref target;
            if (weaklyTyped)
                emit.unbox_any(targetType); //stack[top]=(TargetType)target;

            targetLocal = emit.declocal(targetType); //TargetType tmpTarget; list[0]=tmpTarget;

            emit.stloc(targetLocal)     //list[0]=stack.pop();
            .ifclass_ldloc_else_ldloca(targetLocal, targetType);
        }

        //load parms from local 'list' to evaluation 'steak'
        for (int i = 0; i < imax; i++) {
            var param = prams[i];

            emit.ifbyref_ldloca_else_ldloc(i, param.ParameterType);
        }

        // perform the correct call (pushes the result)
        emit.callorvirt(method);

        if (isNotStatic && targetType.IsValueType) {
            emit.ldarg0().ldloc(targetLocal).box(targetType).stind_ref();
        }

        //check of ref and out params and
        for (int i = 0; i < prams.Length; i++) {

            var paramType = prams[i].ParameterType;
            if (paramType.IsByRef)
            {
                var byRefType = paramType.GetElementType();
                emit.ldarg1() // stack<= paramsValuesArray[]
                .ldc_i4(i) // stack<= i //push(index)
                .ldloc(i); // stack<= list[i] //push local list element at 'i' on steak

                if (byRefType.IsValueType)
                    emit.box(byRefType);   // if ex. stack[top] =(object)stack[top]
                emit.stelem_ref(); //  // paramsValuesArray[i]= pop(stack[top]);
            }
        }

        if (method.ReturnType == typeof(void))
            emit.ldnull();
        else if (weaklyTyped)
            emit.ifvaluetype_box(method.ReturnType);

        emit.ret();

        //vexe orignial modified by winxalex to use reference of object (ref obj) and to return value to reference

        //GENERATES
        //            public static object MethodCallerR(ref object ptr, object[] array)
        //            {
        //                Vector3 vector = (Vector3)ptr;
        //                float num = (float)array[0];
        //                float arg_56_1 = num;
        //                float num2 = (float)array[1];
        //                float arg_56_2 = num2;
        //                float num3 = (float)array[2];
        //                vector.Set(arg_56_1, arg_56_2, num3);
        //                ptr = vector;
        //                return null;
        //            }

        //            var weaklyTyped = typeof(TTarget) == typeof(object);
        //            var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
        //            // push target if not static (instance-method. in that case first arg is always 'this')
        //            if (!method.IsStatic)
        //            {
        //
        //                emit.declocal(targetType); //TargetType tmpTarget; list[0]=tmpTarget;
        //                emit.ldarg0();  //stack[0]=target;
        //                emit.ldind_ref();//stack[top]=ref target;
        //                if (weaklyTyped)
        //                    emit.unbox_any(targetType); //stack[0]=(TargetType)target;
        //                emit.stloc0()     //list[0]=stack.pop();
        //                .ifclass_ldloc_else_ldloca(0, targetType);
        //                // if (type.IsValueType) stack[0]=list[0].address, else stack[0]=list[0];
        //                // if (type.IsValueType) emit.ldloca(idx); else emit.ldloc(idx); return this;
        //            }
        //
        //            // if method wasn't static that means we declared a temp local to load the target
        //            // that means our local variables index for the arguments start from 1
        //            int localVarStart = method.IsStatic ? 0 : 1;
        //
        //            // push arguments in order to call method
        //            var prams = method.GetParameters();
        //            for (int i = 0, imax = prams.Length; i < imax; i++) {
        //                emit.ldarg1()        // stack<= paramsValuesArray //push array
        //                .ldc_i4(i)        // stack<= index push index
        //                .ldelem_ref();    // pop array, index and push array[index]
        //
        //                var param = prams[i];
        //                var dataType = param.ParameterType;
        //
        //                if (dataType.IsByRef)
        //                    dataType = dataType.GetElementType();
        //
        //                var tmp = emit.declocal(dataType);
        //                emit.unbox_any(dataType)
        //                .stloc(tmp)
        //                .ifbyref_ldloca_else_ldloc(tmp, param.ParameterType);
        //
        ////v2
        //
        //
        ////                emit.unbox_any(dataType);
        ////
        ////                emit.declocal(dataType);
        ////                emit.stloc(i+localVarStart)
        ////                .ifbyref_ldloca_else_ldloc(i+localVarStart, param.ParameterType);
        //
        //
        //            }
        //
        //            // perform the correct call (pushes the result)
        //            emit.callorvirt(method);
        //
        //
        //            if (!method.IsStatic && targetType.IsValueType)
        //                emit.ldarg0().ldloc0().box(targetType).stind_ref();
        //
        //
        //            for (int i = 0; i < prams.Length; i++) {
        //                var paramType = prams[i].ParameterType;
        //                if (paramType.IsByRef)
        //                {
        //                    var byRefType = paramType.GetElementType();
        //                    emit.ldarg1() // stack<= params[]
        //                    .ldc_i4(i) // stack<= i
        //                    .ldloc(i + localVarStart); // stack<= list[i+localVarStart]
        //                    if (byRefType.IsValueType)
        //                        emit.box(byRefType);   // if ex. stack =(object)stack[top]
        //                    emit.stelem_ref(); //  // stack:paramsValuesArray[i]= list[i+localVarStart];
        //                }
        //            }
        //
        //            if (method.ReturnType == typeof(void))
        //                emit.ldnull();
        //            else if (weaklyTyped)
        //                emit.ifvaluetype_box(method.ReturnType);
        //
        //            emit.ret();

    }


问:
Programatically unchecking items in a dialog on Android
I am displaying a list with checkboxes in a dialog. The list looks something like-

```<code>Item 1

Item 2

All
</code>```

with a checkbox beside each item. Now the requirements is-
If Item 1 or Item 2 or both are already checked, and All is selected, Item 1 & 2 should be unchecked.

To accomplish this, I implemented DialogInterface.OnMultiChoiceClickListener 's onClick listener.

```<code>public void onClick(DialogInterface dialog, int which, boolean isChecked)
{
  if(which == 2 && isChecked)
  {
    ((AlertDialog)dialog).getListView().setItemChecked(0, false);
    ((AlertDialog)dialog).getListView().setItemChecked(1, false);
  }
}
</code>```

But this does not work. I even tried invalidating the listview by calling Invalidate() & InvalidateViews(), but no success.

Any help will be really appreciated.

Thanks,

Akshay

答:
If I understand correctly, the checkboxes are in a list. There's been a question with the opposite situation: trying to uncheck all boxes. The solution seems to be to call

```<code>adapter.notifyDataSetChanged()
</code>```

Here is the link to that question: Uncheck all checkboxes in a custom ListView

EDIT: Okay, I'll try again :-) Found another question about it: android: Refresh ListView using ListAdapter and SimpleCursorAdapter Hope this helps! :-)

Body:
I am displaying a list with checkboxes in a dialog. The list looks something like-

Item 1

Item 2

All

with a checkbox beside each item. Now the requirements is-
If Item 1 or Item 2 or both are already checked, and All is selected, Item 1 & 2 should be unchecked.

To accomplish this, I implemented DialogInterface.OnMultiChoiceClickListener 's onClick listener.

public void onClick(DialogInterface dialog, int which, boolean isChecked)
{
  if(which == 2 && isChecked)
  {
    ((AlertDialog)dialog).getListView().setItemChecked(0, false);
    ((AlertDialog)dialog).getListView().setItemChecked(1, false);
  }
}

But this does not work. I even tried invalidating the listview by calling Invalidate() & InvalidateViews(), but no success.

Any help will be really appreciated.

Thanks,

Akshay

Body:
If I understand correctly, the checkboxes are in a list. There's been a question with the opposite situation: trying to uncheck all boxes. The solution seems to be to call

adapter.notifyDataSetChanged()

Here is the link to that question: Uncheck all checkboxes in a custom ListView

EDIT: Okay, I'll try again :-) Found another question about it: android: Refresh ListView using ListAdapter and SimpleCursorAdapter Hope this helps! :-)


问:
Nuget package Microsoft.TypeScript.MSBuild fails in Dockerfile
I have an ASP.NET Core project that includes several TypeScript files. The project has Microsoft.TypeScript.MSBuild reference to automatically compile these TS files to JavaScript files.

```<code>  <ItemGroup>
    <PackageReference Include="Microsoft.TypeScript.MSBuild" Version="3.2.3" />
  </ItemGroup>
</code>```

The setting worked until I tried to dockerize my project. When I follow the example here, the error occurs:

/root/.nuget/packages/microsoft.typescript.msbuild/3.2.3/tools/Microsoft.TypeScript.targets(305,5):
  error MSB6003: The specified task executable "node" could not be run.
  No such file or directory [/app/MyProject.csproj] The
  command '/bin/sh -c dotnet publish -c Release -o out' returned a
  non-zero code: 1

How to resolve the issue?

答: On Windows, Microsoft.TypeScript.MSBuild includes tsc.exe. On non-Windows platforms, such as in a Docker container, Microsoft.TypeScript.MSBuild does not include ts.exe and instead shells out to a Node for the TypeScript compiler. The official dotnet/sdk Docker images I think included Node at one point in the past, but they no longer include Node. You will either need to make or find a Docker image with both the dotnet-sdk and Node, or configure some multi-stage build involving the official Node image.

Body:
I have an ASP.NET Core project that includes several TypeScript files. The project has Microsoft.TypeScript.MSBuild reference to automatically compile these TS files to JavaScript files.

  <ItemGroup>
    <PackageReference Include="Microsoft.TypeScript.MSBuild" Version="3.2.3" />
  </ItemGroup>

The setting worked until I tried to dockerize my project. When I follow the example here, the error occurs:

/root/.nuget/packages/microsoft.typescript.msbuild/3.2.3/tools/Microsoft.TypeScript.targets(305,5):
  error MSB6003: The specified task executable "node" could not be run.
  No such file or directory [/app/MyProject.csproj] The
  command '/bin/sh -c dotnet publish -c Release -o out' returned a
  non-zero code: 1

How to resolve the issue?


问:
How to reduce complexity of a long boolean expression?
I have a boolean expression to evaluate that is pretty long with a lot of different cases:

```<code>return (a && b && c) ||
(d && e && f) ||
...
</code>```

This should return a boolean!

a, b, c, d, e and f being simple equality comparison and being all different.
This continues for 12 lines and gives me a Cyclomatic Complexity of 44

I tried to look at the Map object in order to reduce the complexity but did not find a way to do it.

How could I reduce the complexity of such an expression ?

答:
You can not reduce the complexity of the given expression.

A slower approach, but maybe a little more structured, is to group the expressions and evaluate with Array#some for the outer array and Array#every for the inner arrays with a short circuit.

```<code>return [[a, b, c], [d, e, f]].some(a => a.every(Boolean));
</code>```

Body:
I have a boolean expression to evaluate that is pretty long with a lot of different cases:

return (a && b && c) ||
(d && e && f) ||
...

This should return a boolean!

a, b, c, d, e and f being simple equality comparison and being all different.
This continues for 12 lines and gives me a Cyclomatic Complexity of 44

I tried to look at the Map object in order to reduce the complexity but did not find a way to do it.

How could I reduce the complexity of such an expression ?

Body:
You can not reduce the complexity of the given expression.

A slower approach, but maybe a little more structured, is to group the expressions and evaluate with Array#some for the outer array and Array#every for the inner arrays with a short circuit.

return [[a, b, c], [d, e, f]].some(a => a.every(Boolean));


问:
Spring boot with Jersey - Filter request body properties
I would like to know if there is some way to filter the properties of an object that a resource receives.

Let me explain myself: lets say we have this object:

UserDTO

```<code>public final class IniciativaDocument {
    private String id;
    private String name;
    private String surname;
    private String address;
    private Double balance;
}
</code>```

And for a resource I only need the properties "name" and "surname" but for other I only need "address" and "id". Is there any way to make the unneeded variables null automatically with something like Jackson?

My goal for this is that if the client sends a request with a field that isn't needed that I don't have to make it null before saving it to the database because that field is not supposed to be initialized when registering.

Thanks.

EDIT 1

For more clarity: this is for a matter of security and easiness.

Imagine I am a hacker and somehow know the fields a DTO class has. I could easily send a POST request like this to a service which is to register users:

```<code>{
   "id": "wrong",
   "name": "Wrong",
   "balance": 20000
}
</code>```

For my service I would only need id and name but the hacker is sending a balance field too.

What I want to do is that as I receive this object, I can set my endpoint /api/v1/users (which is to register) to put any initialized field that isn't id or name to null.

You might say I could just make sure it's 0 or set it to null manually. Yeah, that's true, but I want to find out if there's an automatic and more comfortable way of doing this with annotations or something similar.

EDIT 2

Resource example:

```<code>@Component
@Path("iniciativas")
@Produces(MediaType.APPLICATION_JSON)
public final class IniciativasEndpoint {
    @POST
    public Response crearIniciativa(@Valid @NotNull(message = CONSTRAINT_BODY_NOT_NULL) @ConvertGroup(to = IniciativasGroup.Create.class)
                                        final IniciativaDTO iniciativaDTO,
                                    @Context UriInfo uriInfo) {

        return Response.ok().build();
    }
}
</code>```

答:
Use a post-matching filter:
You can implement ContainerRequestFilter and annotate your Filter with @PostMaching (javax.ws.rs.container.PreMatching) and manipulate the your request with its data there.

Define an @interface for your Filter:

```<code>@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface AnnotationForYourFilter {}
</code>```

Annotate the sub-resource you want with @AnnotationForYourFilter and you are done.

Body:
I would like to know if there is some way to filter the properties of an object that a resource receives.

Let me explain myself: lets say we have this object:

UserDTO

public final class IniciativaDocument {
    private String id;
    private String name;
    private String surname;
    private String address;
    private Double balance;
}

And for a resource I only need the properties "name" and "surname" but for other I only need "address" and "id". Is there any way to make the unneeded variables null automatically with something like Jackson?

My goal for this is that if the client sends a request with a field that isn't needed that I don't have to make it null before saving it to the database because that field is not supposed to be initialized when registering.

Thanks.

EDIT 1

For more clarity: this is for a matter of security and easiness.

Imagine I am a hacker and somehow know the fields a DTO class has. I could easily send a POST request like this to a service which is to register users:

{
   "id": "wrong",
   "name": "Wrong",
   "balance": 20000
}

For my service I would only need id and name but the hacker is sending a balance field too.

What I want to do is that as I receive this object, I can set my endpoint /api/v1/users (which is to register) to put any initialized field that isn't id or name to null.

You might say I could just make sure it's 0 or set it to null manually. Yeah, that's true, but I want to find out if there's an automatic and more comfortable way of doing this with annotations or something similar.

EDIT 2

Resource example:

@Component
@Path("iniciativas")
@Produces(MediaType.APPLICATION_JSON)
public final class IniciativasEndpoint {
    @POST
    public Response crearIniciativa(@Valid @NotNull(message = CONSTRAINT_BODY_NOT_NULL) @ConvertGroup(to = IniciativasGroup.Create.class)
                                        final IniciativaDTO iniciativaDTO,
                                    @Context UriInfo uriInfo) {

        return Response.ok().build();
    }
}

Body:
Use a post-matching filter:
You can implement ContainerRequestFilter and annotate your Filter with @PostMaching (javax.ws.rs.container.PreMatching) and manipulate the your request with its data there.

Define an @interface for your Filter:

@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface AnnotationForYourFilter {}

Annotate the sub-resource you want with @AnnotationForYourFilter and you are done.


问:
How to assign group after the ldap parameter?
I would like to assign to group after specific ldap parameter.
In Django I have other groups then in ldap.

I do something in signals.py, but i want do do the same effect in settings.py, because when I create a new groups i want change something in settings.py

I do this in signals.py ant it works

```<code>global group_name

if (gidNumber =='201'):
    goup_name = 'a '
elif (gidNumber == '202'):
      user.is_staff = True
      group_name = 'b'
else:
      group_name = 'c'

if(user.groups.filter(name=group_name).exists()!= True ):
      group = Group.objects.get(name=group_name)
      user.groups.add(gruop)
</code>```

but i would ilke do this like smoething like this what i try do this in my settings.py

```<code> AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"groups.filter(name='a')":
"gidNumber=201,uid=%(user)s,ou=People,dc=yy,dc=xx ",
        }
</code>```

答:
The simplest answer is to do own dictionary in settings.py </p>

```<code>LDAP_DICTIONARY = {
    '201':'a',
    '202':'b',
    '203':'c'
    }

AUTH_LDAP_USER_ATTR_MAP = {
    'first_name' : 'gecos',
    'last_name' : 'gidNumber',
     }
</code>```

<p>and in signals.py assign property, but I have only first_name and last_name paremeters, so I gidNumber assign to last_name and clean this paremeter </p>

```<code>gidNumber = user.last_name
user.last_name=' '
group_name =LDAP_DICTIONARY[gidNumber]
group = Group.objects.get(name=group_name)
user.groups.add(group)
</code>```

Body:
I would like to assign to group after specific ldap parameter.
In Django I have other groups then in ldap.

I do something in signals.py, but i want do do the same effect in settings.py, because when I create a new groups i want change something in settings.py

I do this in signals.py ant it works

global group_name

if (gidNumber =='201'):
    goup_name = 'a '
elif (gidNumber == '202'):
      user.is_staff = True
      group_name = 'b'
else:
      group_name = 'c'

if(user.groups.filter(name=group_name).exists()!= True ):
      group = Group.objects.get(name=group_name)
      user.groups.add(gruop)

but i would ilke do this like smoething like this what i try do this in my settings.py

 AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"groups.filter(name='a')":
"gidNumber=201,uid=%(user)s,ou=People,dc=yy,dc=xx ",
        }

Body:
The simplest answer is to do own dictionary in settings.py

LDAP_DICTIONARY = {
    '201':'a',
    '202':'b',
    '203':'c'
    }

AUTH_LDAP_USER_ATTR_MAP = {
    'first_name' : 'gecos',
    'last_name' : 'gidNumber',
     }

and in signals.py assign property, but I have only first_name and last_name paremeters, so I gidNumber assign to last_name and clean this paremeter

gidNumber = user.last_name
user.last_name=' '
group_name =LDAP_DICTIONARY[gidNumber]
group = Group.objects.get(name=group_name)
user.groups.add(group)


答:
A recursive CTE (Common Table Expression) will do the job:</p>

```<code>with
x as (
  select childId, parentId, name from t where id = 3
  union all
  select t.childId, t.parentId, t.name
  from x
  join t on t.parentId = x.childId
)
select * from x
</code>```

Title: How to get all childs of parent

Body:
I want take all things whose contains to meats from one table. In the future whe can create another elements (child ID) to groups (parent ID) e.g now food -> meats -> animal meats -> pig. In the future somebody can create another record with parent id pig sth like this food -> meats -> animal meats -> pig -> bacon and next person can make another record with parent id bacon etc.
How I can make query whose will take all elements whose highest parent is MEATS? so query should return elements pig, cow, bacon.

+---------+----------+--------------+
| childId | parentId | name         |
+---------+----------+--------------+
| 1       | 0        | FOOD         |
+---------+----------+--------------+
| 2       | 1        | FRUITS       |
+---------+----------+--------------+
| 3       | 1        | VEGETABLES   |
+---------+----------+--------------+
| 4       | 1        | MEATS        |
+---------+----------+--------------+
| 5       | 2        | apple        |
+---------+----------+--------------+
| 6       | 2        | banana       |
+---------+----------+--------------+
| 7       | 3        | carrot       |
+---------+----------+--------------+
| 8       | 3        | tomatoes     |
+---------+----------+--------------+
| 9       | 4        | FISH MEATS   |
+---------+----------+--------------+
| 10      | 4        | ANIMAL MEATS |
+---------+----------+--------------+
| 11      | 9        | cod          |
+---------+----------+--------------+
| 12      | 9        | salmon       |
+---------+----------+--------------+
| 13      | 10       | cow          |
+---------+----------+--------------+
| 14      | 10       | pig          |
+---------+----------+--------------+

Body:
A recursive CTE (Common Table Expression) will do the job:

with
x as (
  select childId, parentId, name from t where id = 3
  union all
  select t.childId, t.parentId, t.name
  from x
  join t on t.parentId = x.childId
)
select * from x