问:
Change and extend keycloak Admin UI
There are lot of resources on how to create templates for the welcome screen, login and email etc but so far I have not been able to find anything how can I customize and extend the admin client itself.

What I want to do is:

Create some custom entities in keycloak database, and be able to view and edit them directly in the keycloak admin UI

From the code that comes with keycloak, it seems that they have used angular to create the admin UI, but it looks like the production version of the angular app. Are there any resources where I can get access to the dev version of the app, so can play around and build custom view and fields in the admin UI?

I believe once I have access to that, I can find my way through to how to access the data from my custom entities, but any pointers to that would also be great!

PS: I have read the docs and have been successful in creating custom entities in keycloak, it's just the admin UI part where I do not see any available resources.

Thanks!

答:
After researching alot and trying out various approaches, I have come to the following conclusion:

The best option to extend Keycloak for extra functionality is to not extend it at all.

When using Keycloak it serves a specific purpose. I have learned it that hard way, it is better to implement a microservice/module (whatever you wanna call it) that extends Keycloak functionality by leveraging its Admin APIs.

By doing this, we can add whatever extra functions we want, eg. user Profile Image, custom user profile pages, custom admin pages, etc using the products UI theme without messing around with Keycloak.

Advantages are:

Easier to update Keycloak

Can allow fine tuned access to Users to their profiles and data

Can allow fine tuned access to admins without exposing everything Keycloak offers, which might be overwhelming to certain admins.

Admin APIs are relatively stable and often do not introduce breaking changes

This ofcourse does not work if you want a specific claim added directly to the JWT token, based on the extension.

For this reason, I would recommend having a look at the following github project. I used this generate and achieve what I wanted.

Title: Change and extend keycloak Admin UI


来源: stackexchange

问:
Can't convert a char to string using standard Linq methods?
I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";

            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}
```

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'.
I tried changing "Value" to a var type, but that didn't work either.ch

答:
Flater's answer addresses your main complaint, but I did want to discuss this some:

I tried changing "Value" to a var type

There isn't a var type; var is you saying "compiler is allowed to decide the type". The compiler will then look at the type on the right hand side of the = and make a decision based on that

On the right hand side you have "(" - this is a string; nothing makes it not a string so you'll end up in exactly the same place whether you write string value or var value

By now you know you could have written:

```<code>var v = '(';
</code>```

That v would be a char, because '(' is a char;

Other things would also result in chars:

```<code>var v = "("[0];
</code>```

That's a string being indexed by an int, which is an operation that results in a char. In this case, the compiler would also infer a char type for v. That's not to say you'd do that - it's just to demo that v ends up as what the compiler determines the final outcoming type of the right hand operation is

Typically we aim to use var when it's obvious what the type is on the other side, or if it's something horrific, like the output of a LINQ query that includes other data and has a where clause etc, and we don't want type out IIncludableQueryableSomethingThatsReallyLongAndDoesntMatter v = ...

There are times when you should avoid using var if it makes the code harder to read:

```<code>//method name is poor; doesn't make it obvious what it does, or returns
//variable name is poor too; we'll have to rely on intellisense lots here
var v = DoProcess();
</code>```

There are also times where you should avoid using var because it makes life hard work. Looping over old collections that don't implement IEnumerable<T> is a good example:

```<code>foreach(var row in someDataTable.Rows)
</code>```

row here will end up typed as object, which is a nuisance to use. THis happens because .Rows is a DataRowCollection and the enumerator for it claims it returns an object - it's actually a DataRow but it's wrapped up inside an object. foreach will do a cast for you if you don't use var:

```<code>foreach(DataRow row in someDataTable.Rows)
</code>```

And this is cleaner than var'ing it and having to cast:

```<code>foreach(var row in someDataTable.Rows.Cast<DataRow>())
  ..

//or
foreach(var row in someDataTable.Rows){
  var actualRow = (DataRow)row;
  ..
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";

            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'.
I tried changing "Value" to a var type, but that didn't work either.ch

Body:
Flater's answer addresses your main complaint, but I did want to discuss this some:

I tried changing "Value" to a var type

There isn't a var type; var is you saying "compiler is allowed to decide the type". The compiler will then look at the type on the right hand side of the = and make a decision based on that

On the right hand side you have "(" - this is a string; nothing makes it not a string so you'll end up in exactly the same place whether you write string value or var value

By now you know you could have written:

var v = '(';

That v would be a char, because '(' is a char;

Other things would also result in chars:

var v = "("[0];

That's a string being indexed by an int, which is an operation that results in a char. In this case, the compiler would also infer a char type for v. That's not to say you'd do that - it's just to demo that v ends up as what the compiler determines the final outcoming type of the right hand operation is

Typically we aim to use var when it's obvious what the type is on the other side, or if it's something horrific, like the output of a LINQ query that includes other data and has a where clause etc, and we don't want type out IIncludableQueryableSomethingThatsReallyLongAndDoesntMatter v = ...

There are times when you should avoid using var if it makes the code harder to read:

//method name is poor; doesn't make it obvious what it does, or returns
//variable name is poor too; we'll have to rely on intellisense lots here
var v = DoProcess();

There are also times where you should avoid using var because it makes life hard work. Looping over old collections that don't implement IEnumerable<T> is a good example:

foreach(var row in someDataTable.Rows)

row here will end up typed as object, which is a nuisance to use. THis happens because .Rows is a DataRowCollection and the enumerator for it claims it returns an object - it's actually a DataRow but it's wrapped up inside an object. foreach will do a cast for you if you don't use var:

foreach(DataRow row in someDataTable.Rows)

And this is cleaner than var'ing it and having to cast:

foreach(var row in someDataTable.Rows.Cast<DataRow>())
  ..

//or
foreach(var row in someDataTable.Rows){
  var actualRow = (DataRow)row;
  ..
}


问:
Please do I interprete this ternary operator?
Please if this function was to be converted to a "normal" if else statement, how would it look like?

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
</code>```

I want to add another condition, but I'm finding it hard to read or digest the current flow.

答:
That's correct. You shouldn't nest ternary operators, thats bad practice.

For your case, not sure what type of data you're comparing. Examples: if it's number, you can use a[key] - b[key]. If it's string - a[key].localeCompare(b[key])

Body:
Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.


问:
Transfer files between google-drive and one drive
I have more than 10TB of content in my google shared drive  I want to copy all that content in my onedrive account. I tried mover.io but it's not working for me. What should I do. Also tried google colab but I couldn't find great code of python

It's been 2nd day and I couldn't find anything that works properly and fast.

I don't want to use any 3rd-party mover like multi-cloud ...

答:
Create a temporary RDP through GitHub action, in that RDP you will get a high-speed internet connection, download the file in it, and upload it to onedrive.
you can also use rabb.it</p>


答:
Try following code.</p>
```<code>string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
Char value = '('; // replace string char
bool result = bracketlist.Contains(value);
Console.WriteLine($"Does string contain specified substring? {result}");
if (result == true)
   {
      int freq = bracketlist.Count(f => (f == value));
      Console.WriteLine(freq);
    }
</code>```

Title: Can't convert a char to string using standard Linq methods?

Body:
Try following code.

string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
Char value = '('; // replace string char
bool result = bracketlist.Contains(value);
Console.WriteLine($"Does string contain specified substring? {result}");
if (result == true)
   {
      int freq = bracketlist.Count(f => (f == value));
      Console.WriteLine(freq);
    }


问:
Converting an integer to a string in PHP
Is there a way to convert an integer to a string in PHP?</p>

ContentLicense: CC BY-SA 3.0

Body:
My situation :

echo strval("12"); => 12
echo strval("0"); => "0"

I'm working ...

$a = "12";
$b = "0";
echo $a * 1; => 12
echo $b * 1; => 0


问:
Not able to Push React code in Github master
Not able to Push React code in Github master due to larger size.

```<code>git push -u origin master
Enumerating objects: 41025, done.
Counting objects: 100% (41025/41025), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25146/25146), done.
Writing objects: 100% (41025/41025), 190.44 MiB | 5.20 MiB/s, done.
Total 41025 (delta 14626), reused 41025 (delta 14626), pack-reused 0
remote: Resolving deltas: 100% (14626/14626), done.
remote: warning: File node_modules/.cache/default-development/20.pack is 54.54 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File node_modules/.cache/default-development/101.pack is 79.78 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 8dfc24e220167542a79ef96d0c9f68e0381fecd6e731ab98b3ad1c16716d2e46
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File node_modules/.cache/default-development/65.pack is 164.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/u121/DemoPage.git
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/u121/DemoPage.git'
</code>```

Getting this error when i use git push -u origin master  in app

答: Add node_modules in .gitignore file. It will ignore node modules when you commit your code.</p>

Body:
Not able to Push React code in Github master due to larger size.

git push -u origin master
Enumerating objects: 41025, done.
Counting objects: 100% (41025/41025), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25146/25146), done.
Writing objects: 100% (41025/41025), 190.44 MiB | 5.20 MiB/s, done.
Total 41025 (delta 14626), reused 41025 (delta 14626), pack-reused 0
remote: Resolving deltas: 100% (14626/14626), done.
remote: warning: File node_modules/.cache/default-development/20.pack is 54.54 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File node_modules/.cache/default-development/101.pack is 79.78 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 8dfc24e220167542a79ef96d0c9f68e0381fecd6e731ab98b3ad1c16716d2e46
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File node_modules/.cache/default-development/65.pack is 164.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/u121/DemoPage.git
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/u121/DemoPage.git'

Getting this error when i use git push -u origin master  in app


问:
Run C++ in command prompt - Windows
I know that everyone uses an IDE nowadays, but I just find it simpler to write my code in notepad++, compile it using a command prompt command, and run it from there too. At least that works for Java and Python. I've tried to get my head around how to do that with C++, and haven't been able to find anything good. Is there any compiler (like Java's JDK) that I can stick into my path and use the C++ equivalent of javac and java to run and compile my code from CMD?

Note: please don't post answers and comments about how IDEs are better - I know they are. I'm just used to doing it the old way :D

答:
[Working 100%] from a Windows user.
Open the terminal(powershell) where your file.cpp is created.

g++ file.cpp  //it will compile the file into a.exe

.\a.exe //this will run the program.

Title: Run C++ in command prompt - Windows


问:
I need to fetch the records that are between these DATE and DATE_TIME Column
I have a AUDIT Table in Oracle with DATE_AND_TIME as DATE and DATE_AND_TIME_24HOUR_FORMAT as Varchar2. I need to fetch records that are between two Date and DATE_AND_TIME_24HOUR_FORMAT. for example

```<code>Record  Date_AND_TIME   DATE_AND_TIME_24HOUR_FORMAT
1   02-Feb-2022 13:35:24
2   02-Feb-2022 13:35:56
3   07-Feb-2022 13:35:32
4   07-Feb-2022 13:35:23
5   07-Feb-2022 13:35:02
6   07-Feb-2022 13:36:02
</code>```

I need the Query which will fetch me records 3,4,5 if I execute it for 03-FEB-2022 13:35:00 to 07-FEB-2022 13:35:00 and record 6 if I execute the query for 07-FEB-2022 13:36:00 to 12 07-FEB-2022 13:37:00.

答:
Not sure why you have used the column's datatype like this. You can directly use the timestamp or Date column only which will contain the DateTime information in it. If you cannot change the datatype, You can use below query -</p>
```<code>SELECT *
  FROM AUDIT
 WHERE Date_AND_TIME || ' ' || DATE_AND_TIME_24HOUR_FORMAT
       BETWEEN TO_DATE('03-FEB-2022 13:35:00', 'DD-MON-YY HH24:MI:SS')
           AND TO_DATE('07-FEB-2022 13:35:00', 'DD-MON-YY HH24:MI:SS');
</code>```

Body:
I have a AUDIT Table in Oracle with DATE_AND_TIME as DATE and DATE_AND_TIME_24HOUR_FORMAT as Varchar2. I need to fetch records that are between two Date and DATE_AND_TIME_24HOUR_FORMAT. for example

Record  Date_AND_TIME   DATE_AND_TIME_24HOUR_FORMAT
1   02-Feb-2022 13:35:24
2   02-Feb-2022 13:35:56
3   07-Feb-2022 13:35:32
4   07-Feb-2022 13:35:23
5   07-Feb-2022 13:35:02
6   07-Feb-2022 13:36:02

I need the Query which will fetch me records 3,4,5 if I execute it for 03-FEB-2022 13:35:00 to 07-FEB-2022 13:35:00 and record 6 if I execute the query for 07-FEB-2022 13:36:00 to 12 07-FEB-2022 13:37:00.

Body:
Not sure why you have used the column's datatype like this. You can directly use the timestamp or Date column only which will contain the DateTime information in it. If you cannot change the datatype, You can use below query -

SELECT *
  FROM AUDIT
 WHERE Date_AND_TIME || ' ' || DATE_AND_TIME_24HOUR_FORMAT
       BETWEEN TO_DATE('03-FEB-2022 13:35:00', 'DD-MON-YY HH24:MI:SS')
           AND TO_DATE('07-FEB-2022 13:35:00', 'DD-MON-YY HH24:MI:SS');


问:
Spring circular references prohibited in 2.6 version
I have an issue for circular reference calling.
Even if I set true to this option, I cannot fix my issue.
How can I fix it?
Here are my code snippets which are shown below step by step.

Here is my application.properties file shown below.

```<code>...
spring.main.allow-circular-references= true
...
</code>```

Here is my error message shown below.

```<code>Description:

The dependencies of some of the beans in the application context form a cycle:

   userController (field com.photoapp.users.service.UserService com.photoapp.users.controller.UserController.userService)
┌─────┐
|  userServiceImpl defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\service\impl\UserServiceImpl.class]
↑     ↓
|  webSecurity defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\security\WebSecurity.class]
└─────┘

Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
</code>```

Here is my userServiceImpl class

```<code>@Service
@Transactional
public class UserServiceImpl implements UserService{

    UserMapper userMapper;

    UserRepository userRepository;

    PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper,UserRepository userRepository,PasswordEncoder passwordEncoder) {
        super();
        this.userMapper = userMapper;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDto createUser(UserDto userDetails) {
        // TODO Auto-generated method stub

        userDetails.setUserId(UUID.randomUUID().toString());

        User user = userMapper.userDtotoUser(userDetails);

        String encodedPassword = passwordEncoder.encode(userDetails.getPassword());
        user.setEncryptedPassword(encodedPassword);

        userRepository.save(user);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user = userRepository.findByEmail(username);

        if(user == null)
            throw new UsernameNotFoundException(username);

        return new org.springframework.security.core.userdetails.User(user.getEmail(),
                user.getEncryptedPassword(),
                true, true, true, true, new ArrayList<>());
    }

    @Override
    public UserDto getUserDetailsByEmail(String email) {
        User user = userRepository.findByEmail(email);

        if(user == null)
            throw new UsernameNotFoundException(email);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;
    }

    @Override
    public UserDto getUserByUserId(String userId) {
        // TODO Auto-generated method stub
        return null;
    }

}
</code>```

Here is my WebSecurity class

```<code>@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    private Environment environment;
    private UserService userService;

    @Autowired
    public WebSecurity(Environment environment, UserService userService) {
        super();
        this.environment = environment;
        this.userService = userService;
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/users").hasIpAddress(environment.getProperty("gateway.ip"))
        .and()
        .addFilter(getAuthenticationFilter());
        http.headers().frameOptions().disable();
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception{
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(userService, environment, authenticationManager());
        //authenticationFilter.setAuthenticationManager(authenticationManager());
        authenticationFilter.setFilterProcessesUrl(environment.getProperty("login.url.path"));
        return authenticationFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}
</code>```

答:
Here is my solution</p>
```<code>public UserServiceImpl(UserMapper userMapper,UserRepository userRepository,@Lazy PasswordEncoder passwordEncoder) {
        super();
        this.userMapper = userMapper;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }
</code>```

Body:
I have an issue for circular reference calling.
Even if I set true to this option, I cannot fix my issue.
How can I fix it?
Here are my code snippets which are shown below step by step.

Here is my application.properties file shown below.

...
spring.main.allow-circular-references= true
...

Here is my error message shown below.

Description:

The dependencies of some of the beans in the application context form a cycle:

   userController (field com.photoapp.users.service.UserService com.photoapp.users.controller.UserController.userService)
┌─────┐
|  userServiceImpl defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\service\impl\UserServiceImpl.class]
↑     ↓
|  webSecurity defined in file [C:\Users\de\Desktop\sts-4.9.0.RELEASE\workspace\PhotoAppApiUsers\target\classes\com\photoapp\users\security\WebSecurity.class]
└─────┘

Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Here is my userServiceImpl class

@Service
@Transactional
public class UserServiceImpl implements UserService{

    UserMapper userMapper;

    UserRepository userRepository;

    PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper,UserRepository userRepository,PasswordEncoder passwordEncoder) {
        super();
        this.userMapper = userMapper;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDto createUser(UserDto userDetails) {
        // TODO Auto-generated method stub

        userDetails.setUserId(UUID.randomUUID().toString());

        User user = userMapper.userDtotoUser(userDetails);

        String encodedPassword = passwordEncoder.encode(userDetails.getPassword());
        user.setEncryptedPassword(encodedPassword);

        userRepository.save(user);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;

    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        User user = userRepository.findByEmail(username);

        if(user == null)
            throw new UsernameNotFoundException(username);

        return new org.springframework.security.core.userdetails.User(user.getEmail(),
                user.getEncryptedPassword(),
                true, true, true, true, new ArrayList<>());
    }

    @Override
    public UserDto getUserDetailsByEmail(String email) {
        User user = userRepository.findByEmail(email);

        if(user == null)
            throw new UsernameNotFoundException(email);

        UserDto returnValue = userMapper.userToUserDto(user);

        return returnValue;
    }

    @Override
    public UserDto getUserByUserId(String userId) {
        // TODO Auto-generated method stub
        return null;
    }

}

Here is my WebSecurity class

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    private Environment environment;
    private UserService userService;

    @Autowired
    public WebSecurity(Environment environment, UserService userService) {
        super();
        this.environment = environment;
        this.userService = userService;
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/users").hasIpAddress(environment.getProperty("gateway.ip"))
        .and()
        .addFilter(getAuthenticationFilter());
        http.headers().frameOptions().disable();
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception{
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(userService, environment, authenticationManager());
        //authenticationFilter.setAuthenticationManager(authenticationManager());
        authenticationFilter.setFilterProcessesUrl(environment.getProperty("login.url.path"));
        return authenticationFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}

Body:
Here is my solution

public UserServiceImpl(UserMapper userMapper,UserRepository userRepository,@Lazy PasswordEncoder passwordEncoder) {
        super();
        this.userMapper = userMapper;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }


问:
Plotting log-scaled histograms in in plotly in R; display original values in tooltip box
I am generating histograms using the plotly package in R to interactively inspect the distribution. In some cases, I have to apply a logarithmic function to make the plot easier to interpret. However, and as you would expect, when using plotly, the log-scaled value is presented in the tooltip box. What I would like to achieve is for the original values to be placed in the tooltip box instead of the log scale values.

Here is some example data and code:-

```<code>library(tidyverse)
library(plotly)

df <- data.frame(
  sex=factor(rep(c("F", "M"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5),
                 rnorm(200, mean=65, sd=5)))
)

p <- ggplot(df, aes(x=weight)) +
  geom_histogram()+
  scale_x_log10()

ggplotly(p)
</code>```

Which gives you this outcome:-

Can someone point me in the right direction? Thanks!

答:
You can paste your weight in ggplot(aes(text = )), and only include text and y in ggplotly(tooltip = c("y", "text")).

```<code>p <- ggplot(df, aes(x = weight, text = paste("Weight:", weight))) +
  geom_histogram() +
  scale_x_log10()

ggplotly(p, tooltip = c("y", "text"))
</code>```

Body:
I am generating histograms using the plotly package in R to interactively inspect the distribution. In some cases, I have to apply a logarithmic function to make the plot easier to interpret. However, and as you would expect, when using plotly, the log-scaled value is presented in the tooltip box. What I would like to achieve is for the original values to be placed in the tooltip box instead of the log scale values.

Here is some example data and code:-

library(tidyverse)
library(plotly)

df <- data.frame(
  sex=factor(rep(c("F", "M"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5),
                 rnorm(200, mean=65, sd=5)))
)

p <- ggplot(df, aes(x=weight)) +
  geom_histogram()+
  scale_x_log10()

ggplotly(p)

Which gives you this outcome:-

Can someone point me in the right direction? Thanks!

Body:
You can paste your weight in ggplot(aes(text = )), and only include text and y in ggplotly(tooltip = c("y", "text")).

p <- ggplot(df, aes(x = weight, text = paste("Weight:", weight))) +
  geom_histogram() +
  scale_x_log10()

ggplotly(p, tooltip = c("y", "text"))


问:
How to specify Memory & CPU limit in docker compose version 3
I am unable to specify CPU and memory limitation for services specified in version 3.

With version 2 it works fine with mem_limit & cpu_shares parameters under the services. But it fails while using version 3, putting them under deploy section doesn't seem worthy unless I am using swarm mode.

Can somebody help?

    version: "3"
    services:
      node:
        build:
         context: .
          dockerfile: ./docker-build/Dockerfile.node
        restart: always
        environment:
          - VIRTUAL_HOST=localhost
        volumes:
          - logs:/app/out/
        expose:
          - 8083
        command: ["npm","start"]
        cap_drop:
          - NET_ADMIN
          - SYS_ADMIN
```

答:
I have other experiences, maybe somebody can explain this.

Maybe this is bug(i think this is a feature), but, I am able to use deployments limits (memory limits) in docker-compose without swarm, hovever CPU limits doesn't work but replication does.

```<code>$> docker-compose --version
docker-compose version 1.29.2
$> docker  --version
Docker version 20.10.12
</code>```

version: '3.2'

services:
  limits-test:
    image: alexeiled/stress-ng
    command: [
     '--vm', '1', '--vm-bytes', '20%', '--vm-method', 'all', '--verify', '-t', ' 10m', '-v'

    ]
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 1024M

```
<p>Docker stats</p>
```b647e0dad247   dc-limits_limits-test_1   0.01%     547.1MiB / 1GiB     53.43%    942B / 0B   0B / 0B     3
```

Edited, thx @Jimmix

Body:
I have other experiences, maybe somebody can explain this.

Maybe this is bug(i think this is a feature), but, I am able to use deployments limits (memory limits) in docker-compose without swarm, hovever CPU limits doesn't work but replication does.

$> docker-compose --version
docker-compose version 1.29.2
$> docker  --version
Docker version 20.10.12

version: '3.2'

services:
  limits-test:
    image: alexeiled/stress-ng
    command: [
     '--vm', '1', '--vm-bytes', '20%', '--vm-method', 'all', '--verify', '-t', ' 10m', '-v'

    ]
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 1024M

Docker stats

b647e0dad247   dc-limits_limits-test_1   0.01%     547.1MiB / 1GiB     53.43%    942B / 0B   0B / 0B     3

Edited, thx @Jimmix


问:
Replace square bracket with new line in PowerShell
I have text per below (from an api response).

```<code>$a = '[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]
[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'
</code>```

I need to replace the square brackets in the middle with ","

```<code>]
[
</code>```

So the final output should be like. Note there are also "[]" in the text that I don't want to change.

```<code>'[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
,
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'
</code>```

I've tried the following with no luck:

```<code>$a -replace "\]`n\[", ","
</code>```

This works in this example, but not in the actual file, so other alternative solutions would be appreciated.

答:
it's somehow not a newline between "]" and "[", there has to be a better way of doing this, but the following is working.

first i replaced the "[]" with a place holder "XXXX", then remove "]" and "[", and finally replace "XXXX" back with "[]"...

```<code>$a -replace "\[]", "XXXX" -replace "\[", "" -replace "\]", "" -replace "`n"," " -replace "`r"," " -replace "\Z", "," -replace "XXXX", "[]"
</code>```

Body:
I have text per below (from an api response).

$a = '[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]
[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'

I need to replace the square brackets in the middle with ","

]
[

So the final output should be like. Note there are also "[]" in the text that I don't want to change.

'[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
,
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'

I've tried the following with no luck:

$a -replace "\]`n\[", ","

This works in this example, but not in the actual file, so other alternative solutions would be appreciated.

Body:
it's somehow not a newline between "]" and "[", there has to be a better way of doing this, but the following is working.

first i replaced the "[]" with a place holder "XXXX", then remove "]" and "[", and finally replace "XXXX" back with "[]"...

$a -replace "\[]", "XXXX" -replace "\[", "" -replace "\]", "" -replace "`n"," " -replace "`r"," " -replace "\Z", "," -replace "XXXX", "[]"


问:
DBNull exception when passing null value in DB
I have this piece of code and I am getting exception

The value for column IsVisible in Features is 'DBNull'

for featureValue.IsVisible. I know that I need to verify to not be DbNull.Value or assing a Value if they are. But I don't know how to do this verifications in my context where I have code in Linq

```<code>ComboBoxEdit comboBox = new ComboBoxEdit();

var featureValues =
        from featureValue in this.productsDataSet.FeatureValues
        where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible == true)
        select featureValue.Value;

comboBox.Properties.Items.AddRange(featureValues.ToArray());
comboBox.Properties.AutoComplete = true;
comboBox.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;

return comboBox;
</code>```

I tried :

```<code> !IsDbNull(featureValue.IsVisible)
 !IsNull(featureValue.IsVisbile)
</code>```

The name 'IsNull' does not exist in the current context

```<code> featureValue.isVisbile == DBNull.Value
</code>```

Operator '==' cannot be applied to operands of type 'bool' and 'DBNull'

```<code>!featureValue.IsNull(featureValue.IsVisible)
</code>```

Cannot convert from 'int' to 'bool'
I am getting errors for all

答:
You could try the following</p>
```<code>var featureValues =
    from featureValue in this.productsDataSet.FeatureValues
    where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible.HasValue && featureValue.IsVisible == true)
    select featureValue.Value;
</code>```

Body:
I have this piece of code and I am getting exception

The value for column IsVisible in Features is 'DBNull'

for featureValue.IsVisible. I know that I need to verify to not be DbNull.Value or assing a Value if they are. But I don't know how to do this verifications in my context where I have code in Linq

ComboBoxEdit comboBox = new ComboBoxEdit();

var featureValues =
        from featureValue in this.productsDataSet.FeatureValues
        where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible == true)
        select featureValue.Value;

comboBox.Properties.Items.AddRange(featureValues.ToArray());
comboBox.Properties.AutoComplete = true;
comboBox.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;

return comboBox;

I tried :

 !IsDbNull(featureValue.IsVisible)
 !IsNull(featureValue.IsVisbile)

The name 'IsNull' does not exist in the current context

 featureValue.isVisbile == DBNull.Value

Operator '==' cannot be applied to operands of type 'bool' and 'DBNull'

!featureValue.IsNull(featureValue.IsVisible)

Cannot convert from 'int' to 'bool'
I am getting errors for all

Body:
You could try the following

var featureValues =
    from featureValue in this.productsDataSet.FeatureValues
    where (featureValue.FeatureId == feature.FeatureId && featureValue.IsVisible.HasValue && featureValue.IsVisible == true)
    select featureValue.Value;


问:
How to check if json from url is equal to downloaded version C#
I have a json that is read locally and is used in my program. Now I want the local json to be checked with the json from the api url and if it is not equal to the local json file it will be downloaded. Only the biggest problem is that it doesn't execute the code of the two if statements in the check! What is wrong with my code for this check?

This is what I tried to use

public static rootObject LoadJsonLocal()
{
    rootObject rootObject = new rootObject();
    var path = pathToJson();

    string file;
    using (StreamReader r = new StreamReader(path))
    {
        file = r.ReadToEnd();
        rootObject = JsonSerializer.Deserialize<rootObject>(file);
    }
    return rootObject;
}

public static string pathToJson()
{
    string extractPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    string path = extractPath + "/" + "getlatest.json";
    return path;
}

public static async Task UpdateOrDownloadJson()
{
    try
    {
        string str = "url";
        WebClient webClient = new WebClient();
        webClient.Headers.Add("Authorization", await Header.getAuthorizationHeader());
        string JsonSting = webClient.DownloadString(str);

        if (JsonSting.Equals(LoadJsonLocal()))
        {
            Console.WriteLine("Json is equal");
        }
        // json is not equal download it
        if (!JsonSting.Equals(LoadJsonLocal()))
        {
            await Downloader.DownloadJson();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
```

答:
You are comparing the downloaded json string to the already present local json deserialized to object form, they are not going to get compared correctly. You should override the Equals() method for your JSON model object[you named it rootObject] so that the comparison can be proper - between local json deserialized into object form and downloaded string deserialized into object form.
To use Equals() or to implement custom equality comparer refer this SO answer


问:
Chrome Javascript Extension - How do I open a page in a new tab w/o actually going to that tab?
I'm currently writing an extension for Chrome (the way you can integrate jQuery etc is pretty awesome, just like greasemonkey) however I have stumbled upon a problem:

I would like to open a page in a new tab without actually focusing that tab (so stay on the same page)

Thanks!

答:
```<code>chrome.tabs.create({url: "http://...", selected: false});
</code>```

If you need this in a content script where Chrome Tab API isn't available, you need to send a request to a background page.

Body:
chrome.tabs.create({url: "http://...", selected: false});

If you need this in a content script where Chrome Tab API isn't available, you need to send a request to a background page.


问:
Puppeteer can't click sign-in button
Currently building a puppeteer program that allows me to sign in to a website, however, after inputting login, I can not seem to make puppeteer click the sign-in button or any button for that matter.I have used dev tools, hovered over the button in question, and input its class ="sign-in-button" but it still does not work on the headless browser I am running. It says on the error sheet that there is no node found for selector: button[type=submit]. It is my third day coding, would love any assistance I can get. Thank you! Please leave any suggestions below, I want to know how to make puppeteer click buttons on screen, but I am having trouble.

Note: I have tried await page.$eval("button[class='sign-in-button']", elem => elem.click());
did not work..

sign-in-button when hovered over

this is what it says in elements in dev tools

答:
Your CSS selector points to a button element instead to an input element and is therefore not found.

Changing the selector to this should work:

```<code>await page.$eval("input[class='sign-in-button']", elem => elem.click());
</code>```

Short class selector

Alternatively you could just select it via classname, so if the input element would be changed to a button element the code would not break. Whenever you pu a dot . before a css selector it automatically treats it as class selector.

```<code>await page.$eval(".sign-in-button", elem => elem.click());

</code>```

JS handle

Instead of clicking the element within the browser context (DOM) you could use page.$ for receiving a button handle and click that.

```<code>// use $ method for receiving a handle to your sign-in button/input
const btn = await page.$('.sign-in-button')

// click it using the `puppeteer` api instead of native DOM clicking..
btn.click()

</code>```

Title: Puppeteer can't click sign-in button

Body:
Your CSS selector points to a button element instead to an input element and is therefore not found.

Changing the selector to this should work:

await page.$eval("input[class='sign-in-button']", elem => elem.click());

Short class selector

Alternatively you could just select it via classname, so if the input element would be changed to a button element the code would not break. Whenever you pu a dot . before a css selector it automatically treats it as class selector.

await page.$eval(".sign-in-button", elem => elem.click());

JS handle

Instead of clicking the element within the browser context (DOM) you could use page.$ for receiving a button handle and click that.

// use $ method for receiving a handle to your sign-in button/input
const btn = await page.$('.sign-in-button')

// click it using the `puppeteer` api instead of native DOM clicking..
btn.click()


问:
convert string to double (java/android)
I have string like "122.32,20.543". I tried to use DecimalFormatSymbols, but I had some problems.
How to convert it to double like double1 = 122.32 and double = 20.543 in Java /android.

答:
Use Double.parseDouble() which takes in a string

```<code>String s1 = "122.32";
String s2 = "20.543";
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);

</code>```

// "d1 and d2" will be a "double" formats of string "s1 and s2",

Title: convert string to double (java/android)

Body:
Use Double.parseDouble() which takes in a string

String s1 = "122.32";
String s2 = "20.543";
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);

// "d1 and d2" will be a "double" formats of string "s1 and s2",


问:
Cannot add the value in the table
Here I am trying to add the values of proId and userId in the table whose values I am getting through post method from my android app and I have also checked it by assigning a value 5 directly to the variable (which I have commented out in the table ) but it is still adding 0 in the table.
The problem here is that it is not adding the value of userId in the table instead its adding only 0 there.
I have checked in the android code , the value being passed there is fine.
I think something is wrong in the php code.
Kindly share the solution.
Here I have attached my php file and the MySQL table.

```<code><?php
$pro= $_POST['proId'];
$user = $_POST['userId'];
//$user = 5;
include "config.php";

$check_sql = "SELECT * FROM `savedProducts` WHERE `proId` = '{$pro}' AND `userId` =
'{$user}'";
$result_check =mysqli_query($conn,$check_sql) or die("result failed");

if(mysqli_num_rows($result_check)>0){
echo "Added already";
}else{
$sql="INSERT INTO `$db`.`savedProducts` (`proId`,`userId`)
VALUES ('{$pro}','{$user}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "Added successfully";
}
?>
</code>```

答:
As explained in my comments, you have to use more security checks in your code. Typically, you cannot take $_POST input values and concatenate them into your SQL query string. This will lead the user to be able to do nasty SQL injections and break your app or steal some user's data.

Check the user's session to see if he is allowed to do the operation.

Filter your user's input values and throw errors if they are missing or invalid.

Use prepared statements with PDO instead of building your SQL strings yourself.

You may also have some problems in your Android app. To help debugging, you could install a proxy such as HTTP toolkit or mitmproxy and configure your smartphone to use it. This way you'll be able to see all the requests between your app and your PHP backend.

Put your config in your config.php file, create some utility functions in another include/tools.php file and add a session handling to check that the user is allowed to do the DB query or not. Typically, the user id should probably be taken directly from the current user, that you already have in the session. There's no need to send the user id via the POST request except if an admin can save products for another user.

But assuming you transfert the user id, here would be a solution where you don't just print a string to return but where you return a JSON object to your mobile app. This way you can handle more easily what has happened. I also decided that the HTTP response code would be set to something else than the 200 (for ok) in case of error. Typically a 400 error for a bad request if your Android app doesn't send valid POST parameters but a 500 error if we are having some MySQL connection errors to say that the problem is on the server side and not the client side.

This would be an example of code (without the session handling):

<?php

// Config comming from "config.php";
define('DB_NAME', 'test');
define('DB_USER', 'sdfsadf');
define('DB_PSWD', 'test');
define('DB_DSN', 'mysql:host=localhost;dbname=' . DB_NAME . ';charset=utf8mb4');
define('DB_PDO_OPTIONS', [
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// Error codes:
define('ERROR_MISSING_PARAM', 1);
define('ERROR_WRONG_PARAM', 2);
define('ERROR_DATABASE_CONNECTION', 3);
define('ERROR_DATABASE_QUERY', 4);

/******************************** FUNCTIONS **********************************/

/**
 * Return a response to the mobile app. You can pass an object or any type of
 * variable to the mobile app. It will be converted to JSON.
 * If you are returning an error then you have to set a non-zero code value and
 * a description for the error.
 *
 * @param mixed $response A PHP object/value to return in JSON to the mobile app.
 * @param integer $error_code The app error code to return. Defaults to 0 => no error.
 * @param string $error_description An optional error description.
 * @param int $http_error_code If $error_code is not 0 then what HTTP error code to return.
 * @return void
 */
function return_json_response($response, $error_code = 0, $error_description = '', $http_error_code = 400)
{
    if ($error_code > 0) {
        http_response_code($http_error_code);
    }
    header('Content-Type: application/json; charset=utf-8');
    $data = (object)[
        'response' => $response,
        'error_code' => $error_code,
        'error_description' => $error_description,
    ];
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}

/*************************** PROGRAM STARTS HERE *****************************/

// Check the product id parameter and stop if it's missing or invalid.
if (!isset($_POST['proId'])) {
    return_json_response(false, ERROR_MISSING_PARAM, 'Missing "proId" POST parameter');
} elseif (!is_numeric($_POST['proId'])) {
    return_json_response(false, ERROR_WRONG_PARAM, 'Invalid "proId" value! It should be numeric.');
}
$product_id = intval($_POST['proId']);

// Check the user id parameter and stop if it's missing or invalid.
// If the user id can be taken from the session then I would not use
// this parameter since it could be changed by the client to make a big
// mess in the products of other users. If needed, keep it for admins
// by adding more security controls.
if (!isset($_POST['userId'])) {
    return_json_response(false, ERROR_MISSING_PARAM, 'Missing "userId" POST parameter');
} elseif (!is_numeric($_POST['userId'])) {
    return_json_response(false, ERROR_WRONG_PARAM, 'Invalid "userId" value! It should be numeric.');
}
$user_id = intval($_POST['userId']);

try {
    $pdo = new PDO(DB_DSN, DB_USER, DB_PSWD, DB_PDO_OPTIONS);
} catch (PDOException $e) {
    error_log($e->getMessage());
    return_json_response(false, ERROR_DATABASE_CONNECTION, 'Could not connect to the database.', 500);
}

try {
    // See if the product is already saved for this user.
    $search_query = "SELECT * FROM `savedProducts` WHERE " .
                    "`proId` = :proId AND `userId` = :userId";
    $statement = $pdo->prepare($search_query);
    $statement->execute([
        ':proId' => $product_id,
        ':userId' => $user_id,
    ]);
    if ($statement->rowCount()) {
        return_json_response([
            'ok' => true,
            'affected_rows' => 0,
            'already_saved' => true
        ]);
    }

    // Insert the saved product for the given user.
    $insert_query = "INSERT INTO `savedProducts` (`proId`, `userId`) VALUES (:proId, :userId)";
    $statement = $pdo->prepare($insert_query);
    $statement->execute([
        ':proId' => $product_id,
        ':userId' => $user_id,
    ]);
    if ($statement->rowCount() === 1) {
        return_json_response([
            'ok' => true,
            'affected_rows' => $statement->rowCount(),
            'already_saved' => false
        ]);
    } else {
        return_json_response(false, ERROR_DATABASE_QUERY, 'Did NOT manage to save the product.', 500);
    }
    echo $statement->rowCount();
} catch (PDOException $e) {
    error_log($e->getMessage());
    return_json_response(false, ERROR_DATABASE_QUERY, 'SQL query error.', 500);
}
```
<p>HTTP 200 response if the product was already saved:</p>
<pre class="lang-json prettyprint-override"><code>{
    "response": {
        "ok": true,
        "affected_rows": 0,
        "already_saved": true
    },
    "error_code": 0,
    "error_description": ""
}
</code>```

HTTP 200 response if the product wasn't saved before and was added correctly:

{
    "response": {
        "ok": true,
        "affected_rows": 1,
        "already_saved": false
    },
    "error_code": 0,
    "error_description": ""
}
```
<p>HTTP 400 response if the "proId" POST param is missing:</p>
<pre class="lang-json prettyprint-override"><code>{
    "response": false,
    "error_code": 1,
    "error_description": "Missing \"proId\" POST parameter"
}
</code>```

HTTP 500 response if we didn't manage to connect to the DB:

{
    "response": false,
    "error_code": 3,
    "error_description": "Could not connect to the database."
}
```

Title: Cannot add the value in the table

Body:
Here I am trying to add the values of proId and userId in the table whose values I am getting through post method from my android app and I have also checked it by assigning a value 5 directly to the variable (which I have commented out in the table ) but it is still adding 0 in the table.
The problem here is that it is not adding the value of userId in the table instead its adding only 0 there.
I have checked in the android code , the value being passed there is fine.
I think something is wrong in the php code.
Kindly share the solution.
Here I have attached my php file and the MySQL table.

<?php
$pro= $_POST['proId'];
$user = $_POST['userId'];
//$user = 5;
include "config.php";

$check_sql = "SELECT * FROM `savedProducts` WHERE `proId` = '{$pro}' AND `userId` =
'{$user}'";
$result_check =mysqli_query($conn,$check_sql) or die("result failed");

if(mysqli_num_rows($result_check)>0){
echo "Added already";
}else{
$sql="INSERT INTO `$db`.`savedProducts` (`proId`,`userId`)
VALUES ('{$pro}','{$user}')";
$result=mysqli_query($conn,$sql) or die("result failed");
echo "Added successfully";
}
?>

Body:
As explained in my comments, you have to use more security checks in your code. Typically, you cannot take $_POST input values and concatenate them into your SQL query string. This will lead the user to be able to do nasty SQL injections and break your app or steal some user's data.

Check the user's session to see if he is allowed to do the operation.

Filter your user's input values and throw errors if they are missing or invalid.

Use prepared statements with PDO instead of building your SQL strings yourself.

You may also have some problems in your Android app. To help debugging, you could install a proxy such as HTTP toolkit or mitmproxy and configure your smartphone to use it. This way you'll be able to see all the requests between your app and your PHP backend.

Put your config in your config.php file, create some utility functions in another include/tools.php file and add a session handling to check that the user is allowed to do the DB query or not. Typically, the user id should probably be taken directly from the current user, that you already have in the session. There's no need to send the user id via the POST request except if an admin can save products for another user.

But assuming you transfert the user id, here would be a solution where you don't just print a string to return but where you return a JSON object to your mobile app. This way you can handle more easily what has happened. I also decided that the HTTP response code would be set to something else than the 200 (for ok) in case of error. Typically a 400 error for a bad request if your Android app doesn't send valid POST parameters but a 500 error if we are having some MySQL connection errors to say that the problem is on the server side and not the client side.

This would be an example of code (without the session handling):

<?php

// Config comming from "config.php";
define('DB_NAME', 'test');
define('DB_USER', 'sdfsadf');
define('DB_PSWD', 'test');
define('DB_DSN', 'mysql:host=localhost;dbname=' . DB_NAME . ';charset=utf8mb4');
define('DB_PDO_OPTIONS', [
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// Error codes:
define('ERROR_MISSING_PARAM', 1);
define('ERROR_WRONG_PARAM', 2);
define('ERROR_DATABASE_CONNECTION', 3);
define('ERROR_DATABASE_QUERY', 4);

/******************************** FUNCTIONS **********************************/

/**
 * Return a response to the mobile app. You can pass an object or any type of
 * variable to the mobile app. It will be converted to JSON.
 * If you are returning an error then you have to set a non-zero code value and
 * a description for the error.
 *
 * @param mixed $response A PHP object/value to return in JSON to the mobile app.
 * @param integer $error_code The app error code to return. Defaults to 0 => no error.
 * @param string $error_description An optional error description.
 * @param int $http_error_code If $error_code is not 0 then what HTTP error code to return.
 * @return void
 */
function return_json_response($response, $error_code = 0, $error_description = '', $http_error_code = 400)
{
    if ($error_code > 0) {
        http_response_code($http_error_code);
    }
    header('Content-Type: application/json; charset=utf-8');
    $data = (object)[
        'response' => $response,
        'error_code' => $error_code,
        'error_description' => $error_description,
    ];
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}

/*************************** PROGRAM STARTS HERE *****************************/

// Check the product id parameter and stop if it's missing or invalid.
if (!isset($_POST['proId'])) {
    return_json_response(false, ERROR_MISSING_PARAM, 'Missing "proId" POST parameter');
} elseif (!is_numeric($_POST['proId'])) {
    return_json_response(false, ERROR_WRONG_PARAM, 'Invalid "proId" value! It should be numeric.');
}
$product_id = intval($_POST['proId']);

// Check the user id parameter and stop if it's missing or invalid.
// If the user id can be taken from the session then I would not use
// this parameter since it could be changed by the client to make a big
// mess in the products of other users. If needed, keep it for admins
// by adding more security controls.
if (!isset($_POST['userId'])) {
    return_json_response(false, ERROR_MISSING_PARAM, 'Missing "userId" POST parameter');
} elseif (!is_numeric($_POST['userId'])) {
    return_json_response(false, ERROR_WRONG_PARAM, 'Invalid "userId" value! It should be numeric.');
}
$user_id = intval($_POST['userId']);

try {
    $pdo = new PDO(DB_DSN, DB_USER, DB_PSWD, DB_PDO_OPTIONS);
} catch (PDOException $e) {
    error_log($e->getMessage());
    return_json_response(false, ERROR_DATABASE_CONNECTION, 'Could not connect to the database.', 500);
}

try {
    // See if the product is already saved for this user.
    $search_query = "SELECT * FROM `savedProducts` WHERE " .
                    "`proId` = :proId AND `userId` = :userId";
    $statement = $pdo->prepare($search_query);
    $statement->execute([
        ':proId' => $product_id,
        ':userId' => $user_id,
    ]);
    if ($statement->rowCount()) {
        return_json_response([
            'ok' => true,
            'affected_rows' => 0,
            'already_saved' => true
        ]);
    }

    // Insert the saved product for the given user.
    $insert_query = "INSERT INTO `savedProducts` (`proId`, `userId`) VALUES (:proId, :userId)";
    $statement = $pdo->prepare($insert_query);
    $statement->execute([
        ':proId' => $product_id,
        ':userId' => $user_id,
    ]);
    if ($statement->rowCount() === 1) {
        return_json_response([
            'ok' => true,
            'affected_rows' => $statement->rowCount(),
            'already_saved' => false
        ]);
    } else {
        return_json_response(false, ERROR_DATABASE_QUERY, 'Did NOT manage to save the product.', 500);
    }
    echo $statement->rowCount();
} catch (PDOException $e) {
    error_log($e->getMessage());
    return_json_response(false, ERROR_DATABASE_QUERY, 'SQL query error.', 500);
}

HTTP 200 response if the product was already saved:

{
    "response": {
        "ok": true,
        "affected_rows": 0,
        "already_saved": true
    },
    "error_code": 0,
    "error_description": ""
}

HTTP 200 response if the product wasn't saved before and was added correctly:

{
    "response": {
        "ok": true,
        "affected_rows": 1,
        "already_saved": false
    },
    "error_code": 0,
    "error_description": ""
}

HTTP 400 response if the "proId" POST param is missing:

{
    "response": false,
    "error_code": 1,
    "error_description": "Missing \"proId\" POST parameter"
}

HTTP 500 response if we didn't manage to connect to the DB:

{
    "response": false,
    "error_code": 3,
    "error_description": "Could not connect to the database."
}


问:
how to do localization for UIDatepicker in swift?
I am able to do localization of my datepicker by adding following line in my code

datePicker.locale = Locale(identifier: "fr_US")

datePicker.calendar.locale = Locale(identifier: "fr_US")

But still the time label is showing in english language can someone explain how i can change this to french aswell. TIA

current condition of UIDatepicker

答:
you need to add your language in locakizations file
as this image enter image description here

this image after i try this in this image

enter image description here


问:
Xdebug not stepping at breakpoints in VSCode, MAMP and Xdebug
Previously, my Xdebug was only stopping at the first breakpoint of my code. Then, I decided to reinstall all my set-up (simple MAMP [not PRO] and Xdebug) to try to fix it. But, actually my debugger is not even stepping at the first breakpoint.

I also have been searching and modifying the two php.ini files like I was doing before (https://dillieodigital.wordpress.com/2015/03/10/quick-tip-enabling-xdebug-in-mamp-for-osx/) but none of this work.

Here is my php.ini file:

```<code>[xdebug]
zend_extension="/Applications/MAMP/bin/php/php7.4.21/lib/php/extensions/no-debug-non-zts-20190902/xdebug.so"
xdebug.remote_autostart=1
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_handler=dbgp
xdebug.remote_port=9000
xdebug.remote_connect_back = 0
</code>```

My launch.json or workspace in my case:

```<code>{
    "folders": [
        {
            "path": "."
        }
    ],
    "launch": {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Listen for Xdebug",
                "type": "php",
                "request": "launch",
                "port": 9003
            },
            {
                "name": "Launch currently open script",
                "type": "php",
                "request": "launch",
                "program": "${file}",
                "cwd": "${fileDirname}",
                "port": 0,
                "runtimeArgs": [
                    "-dxdebug.start_with_request=yes"
                ],
                "env": {
                    "XDEBUG_MODE": "debug,develop",
                    "XDEBUG_CONFIG": "client_port=${port}"
                }
            },
            {
                "name": "Launch Built-in web server",
                "type": "php",
                "request": "launch",
                "runtimeArgs": [
                    "-dxdebug.mode=debug",
                    "-dxdebug.start_with_request=yes",
                    "-S",
                    "localhost:0"
                ],
                "program": "",
                "cwd": "${workspaceRoot}",
                "port": 9003,
                "serverReadyAction": {
                    "pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
                    "uriFormat": "http://localhost:%s",
                    "action": "openExternally"
                }
            }
        ]
    }
}
</code>```

What I am doing wrong? Probably is something very simple but I don't have any clue.

答:
Are you using Xdebug 3? Because in that case, the names of the php.ini settings have changed, you can find the changes in the upgrade guide.

In order to diagnose other issues, please try to debug a PHP file with xdebug_info() in it, which will tell you whether Xdebug tried to make a connection to your IDE and whether it was successful. If not, it will tell you why.

Body:
Previously, my Xdebug was only stopping at the first breakpoint of my code. Then, I decided to reinstall all my set-up (simple MAMP [not PRO] and Xdebug) to try to fix it. But, actually my debugger is not even stepping at the first breakpoint.

I also have been searching and modifying the two php.ini files like I was doing before (https://dillieodigital.wordpress.com/2015/03/10/quick-tip-enabling-xdebug-in-mamp-for-osx/) but none of this work.

Here is my php.ini file:

[xdebug]
zend_extension="/Applications/MAMP/bin/php/php7.4.21/lib/php/extensions/no-debug-non-zts-20190902/xdebug.so"
xdebug.remote_autostart=1
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_handler=dbgp
xdebug.remote_port=9000
xdebug.remote_connect_back = 0

My launch.json or workspace in my case:

{
    "folders": [
        {
            "path": "."
        }
    ],
    "launch": {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Listen for Xdebug",
                "type": "php",
                "request": "launch",
                "port": 9003
            },
            {
                "name": "Launch currently open script",
                "type": "php",
                "request": "launch",
                "program": "${file}",
                "cwd": "${fileDirname}",
                "port": 0,
                "runtimeArgs": [
                    "-dxdebug.start_with_request=yes"
                ],
                "env": {
                    "XDEBUG_MODE": "debug,develop",
                    "XDEBUG_CONFIG": "client_port=${port}"
                }
            },
            {
                "name": "Launch Built-in web server",
                "type": "php",
                "request": "launch",
                "runtimeArgs": [
                    "-dxdebug.mode=debug",
                    "-dxdebug.start_with_request=yes",
                    "-S",
                    "localhost:0"
                ],
                "program": "",
                "cwd": "${workspaceRoot}",
                "port": 9003,
                "serverReadyAction": {
                    "pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
                    "uriFormat": "http://localhost:%s",
                    "action": "openExternally"
                }
            }
        ]
    }
}

What I am doing wrong? Probably is something very simple but I don't have any clue.


问:
How do I resolve "Host key verification" error on Heroku deployment?
When trying to deploy a branch on a Heroku app, I'm getting the following error:

```<code>   Host key verification failed.
   fatal: Could not read from remote repository.
</code>```

There is one exception to this verification failed: I can deploy my branch on one specific pre-existing app with no issue. However, other than that specific app, I can't seem to deploy the branch - even when I create entirely new apps.

Heroku has a support page for this particular issue here: https://help.heroku.com/SP5I8HXO/host-key-verification-error-when-accessing-private-github-repository

However, it's not clear to me what I should do once I generate the PAT. Also, it's not clear to me why this issue would show up on review apps (part of the same pipeline as the one app that's working) and on entirely new apps.

How do I resolve this issue?

Edit:

Here's the complete deployment log.

```<code>   Building on the Heroku-18 stack
   Determining which buildpack to use for this app
   Node.js app detected

   Creating runtime environment

   NPM_CONFIG_LOGLEVEL=error
   USE_YARN_CACHE=true
   NODE_ENV=production
   NODE_MODULES_CACHE=true
   NODE_VERBOSE=false

   Installing binaries
   engines.node (package.json):  16.x
   engines.npm (package.json):   unspecified (use default)
   engines.yarn (package.json):  1.22.x

   Resolving node version 16.x...
   Downloading and installing node 16.13.1...
   Using default npm version: 8.1.2
   Resolving yarn version 1.22.x...
   Downloading and installing yarn (1.22.17)
   Installed yarn 1.22.17

   Installing dependencies
   Installing node modules (yarn.lock)
   yarn install v1.22.17
   [1/4] Resolving packages...
   warning react-scripts > webpack-dev-server > chokidar > fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
   [2/4] Fetching packages...
   error Command failed.
   Exit code: 128
   Command: git
   Arguments: ls-remote --tags --heads ssh://git@github.com/ljharb/qs.git
   Directory: /tmp/build_5650c4ab
   Output:
   Host key verification failed.
   fatal: Could not read from remote repository.

   Please make sure you have the correct access rights
   and the repository exists.
   info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
</code>```

答:
I recently solved this issue which occurred when switching over to yarn from npm.

The solution was to clear the buildpack cache.

I was deploying using a github actions script, here is what I did.

In the file .github/workflows/deploy.yml which configured the deployment to heroku through github actions I added buildpack: false.

This cleared the buildpack cache in heroku and then the deployment completed successfully.

Afterwards I enabled buildpack caching again and all was well.

Body:
When trying to deploy a branch on a Heroku app, I'm getting the following error:

   Host key verification failed.
   fatal: Could not read from remote repository.

There is one exception to this verification failed: I can deploy my branch on one specific pre-existing app with no issue. However, other than that specific app, I can't seem to deploy the branch - even when I create entirely new apps.

Heroku has a support page for this particular issue here: https://help.heroku.com/SP5I8HXO/host-key-verification-error-when-accessing-private-github-repository

However, it's not clear to me what I should do once I generate the PAT. Also, it's not clear to me why this issue would show up on review apps (part of the same pipeline as the one app that's working) and on entirely new apps.

How do I resolve this issue?

Edit:

Here's the complete deployment log.

   Building on the Heroku-18 stack
   Determining which buildpack to use for this app
   Node.js app detected

   Creating runtime environment

   NPM_CONFIG_LOGLEVEL=error
   USE_YARN_CACHE=true
   NODE_ENV=production
   NODE_MODULES_CACHE=true
   NODE_VERBOSE=false

   Installing binaries
   engines.node (package.json):  16.x
   engines.npm (package.json):   unspecified (use default)
   engines.yarn (package.json):  1.22.x

   Resolving node version 16.x...
   Downloading and installing node 16.13.1...
   Using default npm version: 8.1.2
   Resolving yarn version 1.22.x...
   Downloading and installing yarn (1.22.17)
   Installed yarn 1.22.17

   Installing dependencies
   Installing node modules (yarn.lock)
   yarn install v1.22.17
   [1/4] Resolving packages...
   warning react-scripts > webpack-dev-server > chokidar > fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
   [2/4] Fetching packages...
   error Command failed.
   Exit code: 128
   Command: git
   Arguments: ls-remote --tags --heads ssh://git@github.com/ljharb/qs.git
   Directory: /tmp/build_5650c4ab
   Output:
   Host key verification failed.
   fatal: Could not read from remote repository.

   Please make sure you have the correct access rights
   and the repository exists.
   info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.


问:
laravel project storing data to my database doesn't work
i have problem that store function does not work, this is forum website application using laravel 8. When user want to add a discussion :
create discussion
and when they finish input the data, nothing happenned , and nothing added on database
basically, my code look like:

First the on the TopicController :

```<code>public function store(CreateTopicRequest $request)
    {
        $topic = new Topic;
        $topic = auth()->user()->$topic->create()([
            'genre_id' => $request->genre,
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description
        ]);

        session()->flash('success', 'Discussion posted!');

        return redirect()->route(('topic.index'));
    }
</code>```

for Topic Model :

```<code>class Topic extends Model
{
    use HasFactory;

    protected $table = 'topics';
    protected $primaryKey = 'topicID';
    protected $fillable = ['genre', 'title', 'description', 'created_at', 'updated_at'];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
</code>```

for User Model :

```<code>class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     *
     */
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $fillable = [

        'nama',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function topics(): HasMany
    {
        return $this->hasMany(Topic::class);
    }

    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

</code>```

my create discussion source code, just incase

```<code><!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <link rel="shortcut icon" href="http://127.0.0.1:8000/image/favicon.ico">
  <title>Forum - Create Discussions</title>

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/trix/1.3.1/trix.css">
    </head>

<body>

  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-music-note-beamed" viewBox="0 0 16 16">
        <path d="M6 13c0 1.105-1.12 2-2.5 2S1 14.105 1 13c0-1.104 1.12-2 2.5-2s2.5.896 2.5 2zm9-2c0 1.105-1.12 2-2.5 2s-2.5-.895-2.5-2 1.12-2 2.5-2 2.5.895 2.5 2z" />
        <path fill-rule="evenodd" d="M14 11V2h1v9h-1zM6 3v10H5V3h1z" />
        <path d="M5 2.905a1 1 0 0 1 .9-.995l8-.8a1 1 0 0 1 1.1.995V3L5 4V2.905z" />
      </svg>

      <div class="collapse navbar-collapse" id="navbarTogglerDemo02">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="/topic">Home</a>
          </li>

          <li class="nav-item">
            <a class="nav-link " href="/playlistpop">Playlist</a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="http://127.0.0.1:8000/about">About</a>
          </li>
        </ul>
                <li class="nav-item dropdown">
          <a id="navbarDropdown" class="nav-link dropdown-toggle" href="/profile" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
            Andi
          </a>

          <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="/profile">
              Profile
            </a>
            <hr>
            <a class="dropdown-item" href="/logout">
              Logout
            </a>

          </div>
        </li>
              </div>

    </div>
  </nav>

  <div class="col-md">
    <div class="container">
    <br>
    <div class="row justify-content-center">
        <div class="col-md-15">

            <div class="card">
                <div class="card-header">Add Discussions </div>

                <div class="card-body">
                    <form action="http://127.0.0.1:8000/topic" method="POST">
                        <input type="hidden" name="_token" value="0PrvW3jQoQVM79yGTTissffS2JG69IhcCgYt34dT">                        <div class=form-group>
                            <label for="genre">Genre</label>
                            <br>
                            <select name="genre" id="genre" class="form-control">
                                                                <option value="">Pop</option>
                                                                <option value="">Rock</option>
                                                                <option value="">Jazz</option>
                                                                <option value="">Classic</option>
                                                            </select>
                        </div>
                        <br>
                        <div class="form-group">
                            <label for="floatingInput">Judul</label>
                            <br>
                            <input type="text" id="title" name="title" class="form-control" placeholder="Judul" required="required">
                        </div>
                        <br>
                        <div class="form-group">
                            <label for="description">Description</label>
                            <br>
                            <input id="description" type="hidden" name="description">
                            <trix-editor input="description"></trix-editor>
                        </div>

                        <br>
                        <button type="submit" class="btn btn-success">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

      </div>
  </div>

  <!-- Optional JavaScript; choose one of the two! -->

  <!-- Option 1: Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <!-- Option 2: Separate Popper and Bootstrap JS -->
  <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    -->

  <script src="http://127.0.0.1:8000/js/app.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/trix/1.3.1/trix.js">

    </script>
    </body>

</html>
</code>```

答:
The topic model is supposed to have a user_id column
While TopicController code here should look like this

```<code>use app\Models\Topic;
public function store(CreateTopicRequest $request)
    {
        $topic = Topic::create([
            'genre_id' => $request->genre,
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
             'user_id' => auth()->user()->id
        ]);

        session()->flash('success', 'Discussion posted!');

        return redirect()->route(('topic.index'));
    }
</code>```

Remember to add user_id column to fillable in Topic Model

Body:
i have problem that store function does not work, this is forum website application using laravel 8. When user want to add a discussion :
create discussion
and when they finish input the data, nothing happenned , and nothing added on database
basically, my code look like:

First the on the TopicController :

public function store(CreateTopicRequest $request)
    {
        $topic = new Topic;
        $topic = auth()->user()->$topic->create()([
            'genre_id' => $request->genre,
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description
        ]);

        session()->flash('success', 'Discussion posted!');

        return redirect()->route(('topic.index'));
    }

for Topic Model :

class Topic extends Model
{
    use HasFactory;

    protected $table = 'topics';
    protected $primaryKey = 'topicID';
    protected $fillable = ['genre', 'title', 'description', 'created_at', 'updated_at'];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

for User Model :

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     *
     */
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $fillable = [

        'nama',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function topics(): HasMany
    {
        return $this->hasMany(Topic::class);
    }

    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

my create discussion source code, just incase

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <link rel="shortcut icon" href="http://127.0.0.1:8000/image/favicon.ico">
  <title>Forum - Create Discussions</title>

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/trix/1.3.1/trix.css">

      <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-music-note-beamed" viewBox="0 0 16 16">
        <path d="M6 13c0 1.105-1.12 2-2.5 2S1 14.105 1 13c0-1.104 1.12-2 2.5-2s2.5.896 2.5 2zm9-2c0 1.105-1.12 2-2.5 2s-2.5-.895-2.5-2 1.12-2 2.5-2 2.5.895 2.5 2z" />
        <path fill-rule="evenodd" d="M14 11V2h1v9h-1zM6 3v10H5V3h1z" />
        <path d="M5 2.905a1 1 0 0 1 .9-.995l8-.8a1 1 0 0 1 1.1.995V3L5 4V2.905z" />
      </svg>

            Home

            Playlist

            About

            Andi

              Profile

              Logout

Add Discussions

                    <form action="http://127.0.0.1:8000/topic" method="POST">
                        <input type="hidden" name="_token" value="0PrvW3jQoQVM79yGTTissffS2JG69IhcCgYt34dT">

                            Genre

                            <select name="genre" id="genre" class="form-control">
                                                                <option value="">Pop</option>
                                                                <option value="">Rock</option>
                                                                <option value="">Jazz</option>
                                                                <option value="">Classic</option>
                                                            </select>

                            Judul

                            <input type="text" id="title" name="title" class="form-control" placeholder="Judul" required="required">

                            Description

                            <input id="description" type="hidden" name="description">
                            <trix-editor input="description"></trix-editor>

                        <button type="submit" class="btn btn-success">Submit</button>
                    </form>

Body:
The topic model is supposed to have a user_id column
While TopicController code here should look like this

use app\Models\Topic;
public function store(CreateTopicRequest $request)
    {
        $topic = Topic::create([
            'genre_id' => $request->genre,
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'description' => $request->description,
             'user_id' => auth()->user()->id
        ]);

        session()->flash('success', 'Discussion posted!');

        return redirect()->route(('topic.index'));
    }

Remember to add user_id column to fillable in Topic Model


问:
Synchronise sql server changes between databases
What is the best/easiest way to replicate the changes in one databases to another database?

I say replicate, because the changes may just be one way. However, in some cases there may need to be changes going both ways so also 2 way sync.

This is for a work environment so free or cheap and easy-to-implement solutions are best. Diff has been mentioned, how would this work? (On the database's create script)? What other wwy is there?

Thanks

答: I blogged about this a while back, mentioning a long list of schema comparison tools - several of them very cheap or free. The thrust of the post, though, is that you get what you pay for: just spending the money on a tool that you know will work is much more cost effective than wasting time on tools that might not (or writing your own solution). I highly recommend you give Red-Gate SQL Compare a trial, as well as a few of the free ones, and you can compare for yourself whether it's worth the money.</p>


问:
Between in createdCriteria not works
I have a very strange problem. I create 3 entities with the following data:

```<code>CCB ccb1 = new Ccb(1)
CCB ccb2 = new Ccb(2)
CCB ccb3 = new Ccb(3)
</code>```

Where the parameter (Long) is the object id.

Then, when wanting to create a list with the between clause, it is created with size = 0:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", 1, 5)
                projections {
                    id()
                }
            }
    )
</code>```

I've tried this alternative and it doesn't work either:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", "1", "5")
                projections {
                    id()
                }
            }
    )
</code>```

The incredible thing is that if I replace the between with the eq:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                eq("id", 2)
                projections {
                    id()
                }
            }
    )
</code>```

Now the list returns me the element with id 2!
I can't understand where is the error.

Thanks!

EDIT:

Config of DataSource.groovy:

```<code>    dataSource {
        dbCreate = "create-drop"
        driverClassName = "org.h2.Driver"
        dialect = "org.hibernate.dialect.H2Dialect"
        url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
</code>```

答:
Can't you stream the list and filter by ID?

def list = foolist.stream().filter(f -> f.getId() > 0 && f.getId() < 4).collect(Collectors.toList())

Title: Between in createdCriteria not works

Body:
I have a very strange problem. I create 3 entities with the following data:

CCB ccb1 = new Ccb(1)
CCB ccb2 = new Ccb(2)
CCB ccb3 = new Ccb(3)

Where the parameter (Long) is the object id.

Then, when wanting to create a list with the between clause, it is created with size = 0:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", 1, 5)
                projections {
                    id()
                }
            }
    )

I've tried this alternative and it doesn't work either:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", "1", "5")
                projections {
                    id()
                }
            }
    )

The incredible thing is that if I replace the between with the eq:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                eq("id", 2)
                projections {
                    id()
                }
            }
    )

Now the list returns me the element with id 2!
I can't understand where is the error.

Thanks!

EDIT:

Config of DataSource.groovy:

    dataSource {
        dbCreate = "create-drop"
        driverClassName = "org.h2.Driver"
        dialect = "org.hibernate.dialect.H2Dialect"
        url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }


问:
Pandas df.mean() throws TypeError: 'NoneType' object is not callable or returns empty Series
The title says it all.

```<code>df = pd.DataFrame({"A":np.array([1,2,3,4]),"B":np.array([1,2,3,4])})
df_mean = df.mean(axis=0)
print(df_mean)
</code>```

The code above outputs an empty series object:

```<code>Series([], dtype: float64)
</code>```

Using df.mean() on a dataframe filled with MNIST data throws the following stacktrace:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-bab38039484e> in <module>
      2
      3 X_train_class, y_train_class, X_valid_class, \
----> 4         y_valid_class, X_test_class, y_test_class = prepare_load_classification_data()
      5 X_train_class.mean()
      6 # ebm = ExplainableBoostingClassifier()

<ipython-input-37-b1dcfdd01adc> in prepare_load_classification_data()
     45     train_features, train_labels, dev_features, \
     46         dev_labels, test_features, test_labels = load_data()
---> 47     feature_mean, label_mean = train_features.mean(axis=0), train_labels.mean(axis=0)
     48
     49     train_features = pd.DataFrame(data=np.where(train_features > feature_mean, 1, 0), columns=FEATURE_NAMES)

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\generic.py in mean(self, axis, skipna, level, numeric_only, **kwargs)
  11107         )
  11108         def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
> 11109             return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs)
  11110
  11111         # pandas\core\generic.py:10924: error: Cannot assign to a method

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\generic.py in mean(self, axis, skipna, level, numeric_only, **kwargs)
  10718     def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
  10719         return self._stat_function(
> 10720             "mean", nanops.nanmean, axis, skipna, level, numeric_only, **kwargs
  10721         )
  10722

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\generic.py in _stat_function(self, name, func, axis, skipna, level, numeric_only, **kwargs)
  10703             return self._agg_by_level(name, axis=axis, level=level, skipna=skipna)
  10704         return self._reduce(
> 10705             func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only
  10706         )
  10707

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\series.py in _reduce(self, op, name, axis, skipna, numeric_only, filter_type, **kwds)
   4150                 )
   4151             with np.errstate(all="ignore"):
-> 4152                 return op(delegate, skipna=skipna, **kwds)
   4153
   4154     def _reindex_indexer(self, new_index, indexer, copy):

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\nanops.py in _f(*args, **kwargs)
     69             try:
     70                 with np.errstate(invalid="ignore"):
---> 71                     return f(*args, **kwargs)
     72             except ValueError as e:
     73                 # we want to transform an object array

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\nanops.py in f(values, axis, skipna, **kwds)
    122                     #  TypeError if called
    123                     kwds.pop("mask", None)
--> 124                     result = bn_func(values, axis=axis, **kwds)
    125
    126                     # prefer to treat inf/-inf as NA, but must compute the func

TypeError: 'NoneType' object is not callable
</code>```

It appears to be related to a somehow corrupted instalation of pandas or numpy but after reinstalling both downgrading or starting a new Conda environment the issues still remain. Any help would be greatly apreciated!

答:
for me, the issue was caused by importing pandas before importing numpy

so instead of:

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

i changed it to

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

and it fixed the issue

Body:
The title says it all.

df = pd.DataFrame({"A":np.array([1,2,3,4]),"B":np.array([1,2,3,4])})
df_mean = df.mean(axis=0)
print(df_mean)

The code above outputs an empty series object:

Series([], dtype: float64)

Using df.mean() on a dataframe filled with MNIST data throws the following stacktrace:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-bab38039484e> in <module>
      2
      3 X_train_class, y_train_class, X_valid_class, \
----> 4         y_valid_class, X_test_class, y_test_class = prepare_load_classification_data()
      5 X_train_class.mean()
      6 # ebm = ExplainableBoostingClassifier()

<ipython-input-37-b1dcfdd01adc> in prepare_load_classification_data()
     45     train_features, train_labels, dev_features, \
     46         dev_labels, test_features, test_labels = load_data()
---> 47     feature_mean, label_mean = train_features.mean(axis=0), train_labels.mean(axis=0)
     48
     49     train_features = pd.DataFrame(data=np.where(train_features > feature_mean, 1, 0), columns=FEATURE_NAMES)

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\generic.py in mean(self, axis, skipna, level, numeric_only, **kwargs)
  11107         )
  11108         def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
> 11109             return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs)
  11110
  11111         # pandas\core\generic.py:10924: error: Cannot assign to a method

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\generic.py in mean(self, axis, skipna, level, numeric_only, **kwargs)
  10718     def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
  10719         return self._stat_function(
> 10720             "mean", nanops.nanmean, axis, skipna, level, numeric_only, **kwargs
  10721         )
  10722

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\generic.py in _stat_function(self, name, func, axis, skipna, level, numeric_only, **kwargs)
  10703             return self._agg_by_level(name, axis=axis, level=level, skipna=skipna)
  10704         return self._reduce(
> 10705             func, name=name, axis=axis, skipna=skipna, numeric_only=numeric_only
  10706         )
  10707

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\series.py in _reduce(self, op, name, axis, skipna, numeric_only, filter_type, **kwds)
   4150                 )
   4151             with np.errstate(all="ignore"):
-> 4152                 return op(delegate, skipna=skipna, **kwds)
   4153
   4154     def _reindex_indexer(self, new_index, indexer, copy):

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\nanops.py in _f(*args, **kwargs)
     69             try:
     70                 with np.errstate(invalid="ignore"):
---> 71                     return f(*args, **kwargs)
     72             except ValueError as e:
     73                 # we want to transform an object array

c:\users\fmijs\anaconda3\lib\site-packages\pandas\core\nanops.py in f(values, axis, skipna, **kwds)
    122                     #  TypeError if called
    123                     kwds.pop("mask", None)
--> 124                     result = bn_func(values, axis=axis, **kwds)
    125
    126                     # prefer to treat inf/-inf as NA, but must compute the func

TypeError: 'NoneType' object is not callable

It appears to be related to a somehow corrupted instalation of pandas or numpy but after reinstalling both downgrading or starting a new Conda environment the issues still remain. Any help would be greatly apreciated!

Body:
for me, the issue was caused by importing pandas before importing numpy

so instead of:

import pandas as pd
import numpy as np

i changed it to

import numpy as np
import pandas as pd

and it fixed the issue