问:
What is wrong in this Spring Security configuration? How can I make an endpoint accessible to users having different authorities?
I am working on a Spring Boot protecting my APIs using Spring Security and JWT tokens and I have the following iusse.

I have an API handling endpoint like this: http://localhost:8019/api/admin/user/54/wallet

I have 2 user types:

ADMIN USER: having ADMIN autority  defined into the JWT tokend.

CLIENT USER: having CLIENT autority  defined into the JWT tokend.

The previous API must be accessible by both the user types (I know that the /admin/ section in the URI is not the best...it will be refactored in the near future).

Then I have this class extending the Spring Boot WebSecurityConfigurerAdapter class and implementing my security configuration:

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final String[] USER_MATCHER = { "/api/user/email/**"};

    private static final String[] CLIENT_MATCHER = {

                                                        "/api/users/email/*",
                                                        //"/api/admin/**",
                                                        "/api/admin/user/{userID}/wallet"
                                                    };

    private static final String[] ADMIN_MATCHER = {
                                                        "/api/users/email/**",
                                                        "/api/admin/users",
                                                        "/api/admin/user/{userID}/wallet",
                                                        "/api/admin/**"

                                                   };

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*
         * NOTE:
         * Using hasRole expects the authority names to start with 'ROLE_' prefix
         * Instead, we use hasAuthority as we can use the names as it is
         */
        http.csrf().disable()
                   .authorizeRequests()

                   .antMatchers(USER_MATCHER).hasAnyAuthority("USER")
                   .antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN")
                   //.antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers("/api/users/test").authenticated()
                   .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
                   .anyRequest().denyAll()
                   .and()
                   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(
            new TokenVerificationFilter(authenticationManager(), jwtConfig, jwtTokenUtil),UsernamePasswordAuthenticationFilter.class);
    }

    /* To allow Pre-flight [OPTIONS] request from browser */
    @Override
    public void configure(WebSecurity web)
    {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring().antMatchers("/swagger-ui/**",
                                    "/webjars/**",
                                    "/v2/**",
                                    "/swagger-resources/**",
                                    "/swagger-ui.html");
    }

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

}
</code>```

The problem is that as it is defined in the previous configuration if I try to call the previous API (http://localhost:8019/api/admin/user/54/wallet) with a token related to an user having the CLIENT autority I am obtaining this error message:

```<code>{
    "timestamp": "2022-02-13T20:22:10.418+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/admin/user/54/wallet"
}
</code>```

Viceversa if I try to call the previous API passing a token of an user having the AMDIN authority I obtain the expected API output.

It seems pretty strange to me because into the CLIENT_MATCHER I have defined this rule:

```<code>"/api/admin/user/{userID}/wallet"
</code>```

The strangest thing is that if I remove this line from the ADMIN_MATCHER:

```<code>"/api/admin/user/{userID}/wallet",
</code>```

that become something like:

```<code>private static final String[] ADMIN_MATCHER = {
                                                    "/api/users/email/**",
                                                    "/api/admin/users",
                                                    //"/api/admin/user/{userID}/wallet",
                                                    "/api/admin/**"
                                                    }
</code>```

Now the behavior is the complete opposite: using a JWT token of an user having the CLIENT authority I retrieve the expected output, but now using a JWT token of an user having the ADMIN authoruty I obtain this error message:

{
"timestamp": "2022-02-13T20:27:47.793+00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/admin/user/54/wallet"
}

and this seems pretty strange to me because the ADMIN_MATCHER contaisn this rule:

```<code>"/api/admin/**"
</code>```

that should meaning: access to all the API having an enptoint starting with "/api/admin/" folloed by anything else.

What is wrong in my Spring configuration? What am I missing? How can I fix it in such a way that this API could be accessible using a JWT token having ADMIN or CLIENT authority?

答:
instead of

```<code>.antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN")
</code>```

try

```<code>.antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN", "CLIENT")
</code>```

and removing this from CLIENT_MATCHER

```<code>"/api/admin/user/{userID}/wallet"
</code>```

Body:
I am working on a Spring Boot protecting my APIs using Spring Security and JWT tokens and I have the following iusse.

I have an API handling endpoint like this: http://localhost:8019/api/admin/user/54/wallet

I have 2 user types:

ADMIN USER: having ADMIN autority  defined into the JWT tokend.

CLIENT USER: having CLIENT autority  defined into the JWT tokend.

The previous API must be accessible by both the user types (I know that the /admin/ section in the URI is not the best...it will be refactored in the near future).

Then I have this class extending the Spring Boot WebSecurityConfigurerAdapter class and implementing my security configuration:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final String[] USER_MATCHER = { "/api/user/email/**"};

    private static final String[] CLIENT_MATCHER = {

                                                        "/api/users/email/*",
                                                        //"/api/admin/**",
                                                        "/api/admin/user/{userID}/wallet"
                                                    };

    private static final String[] ADMIN_MATCHER = {
                                                        "/api/users/email/**",
                                                        "/api/admin/users",
                                                        "/api/admin/user/{userID}/wallet",
                                                        "/api/admin/**"

                                                   };

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*
         * NOTE:
         * Using hasRole expects the authority names to start with 'ROLE_' prefix
         * Instead, we use hasAuthority as we can use the names as it is
         */
        http.csrf().disable()
                   .authorizeRequests()

                   .antMatchers(USER_MATCHER).hasAnyAuthority("USER")
                   .antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN")
                   //.antMatchers(CLIENT_MATCHER).hasAnyAuthority("CLIENT")
                   .antMatchers("/api/users/test").authenticated()
                   .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
                   .anyRequest().denyAll()
                   .and()
                   .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(
            new TokenVerificationFilter(authenticationManager(), jwtConfig, jwtTokenUtil),UsernamePasswordAuthenticationFilter.class);
    }

    /* To allow Pre-flight [OPTIONS] request from browser */
    @Override
    public void configure(WebSecurity web)
    {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        web.ignoring().antMatchers("/swagger-ui/**",
                                    "/webjars/**",
                                    "/v2/**",
                                    "/swagger-resources/**",
                                    "/swagger-ui.html");
    }

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

}

The problem is that as it is defined in the previous configuration if I try to call the previous API (http://localhost:8019/api/admin/user/54/wallet) with a token related to an user having the CLIENT autority I am obtaining this error message:

{
    "timestamp": "2022-02-13T20:22:10.418+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/admin/user/54/wallet"
}

Viceversa if I try to call the previous API passing a token of an user having the AMDIN authority I obtain the expected API output.

It seems pretty strange to me because into the CLIENT_MATCHER I have defined this rule:

"/api/admin/user/{userID}/wallet"

The strangest thing is that if I remove this line from the ADMIN_MATCHER:

"/api/admin/user/{userID}/wallet",

that become something like:

private static final String[] ADMIN_MATCHER = {
                                                    "/api/users/email/**",
                                                    "/api/admin/users",
                                                    //"/api/admin/user/{userID}/wallet",
                                                    "/api/admin/**"
                                                    }

Now the behavior is the complete opposite: using a JWT token of an user having the CLIENT authority I retrieve the expected output, but now using a JWT token of an user having the ADMIN authoruty I obtain this error message:

{
"timestamp": "2022-02-13T20:27:47.793+00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/admin/user/54/wallet"
}

and this seems pretty strange to me because the ADMIN_MATCHER contaisn this rule:

"/api/admin/**"

that should meaning: access to all the API having an enptoint starting with "/api/admin/" folloed by anything else.

What is wrong in my Spring configuration? What am I missing? How can I fix it in such a way that this API could be accessible using a JWT token having ADMIN or CLIENT authority?

Body:
instead of

.antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN")

try

.antMatchers(ADMIN_MATCHER).hasAnyAuthority("ADMIN", "CLIENT")

and removing this from CLIENT_MATCHER

"/api/admin/user/{userID}/wallet"


来源: stackexchange

问:
Caddy V2 IP whitelist
I am trying to implement IP whitelist on my Caddy v2 configuration. Something equivalent to NGINX configuration like:

```<code>allow 1.1.1.1;
allow 8.8.8.8;
deny all;
</code>```

My current Caddy configuration pretty straight forward:

```<code>my.website.com {
        reverse_proxy http://127.0.0.1:3000 {
    }
}
</code>```

Thanks

答:
I'm not saying qed's answer is wrong, however I couldn't get it to work in my case (possibly due to using import templates inside a handle?)...

My solution was... Old config:

```<code>private.example.com {
  import my_template argument_1 /path/to/example/argument2
}
</code>```

This changed to:

```<code>private.example.com {
  @blocked not remote_ip 1.2.3.4
  respond @blocked "<h1>Access Denied</h1>" 403
  import my_template argument_1 /path/to/example/argument2
}
</code>```

Simply adding those two lines allows my site to be accessed on that IP. A test curl from a different IP returned the 403 error.

This is done on Caddy 2.4.6

ContentLicense: CC BY-SA 4.0

Title: Caddy V2 IP whitelist

Body:
I am trying to implement IP whitelist on my Caddy v2 configuration. Something equivalent to NGINX configuration like:

allow 1.1.1.1;
allow 8.8.8.8;
deny all;

My current Caddy configuration pretty straight forward:

my.website.com {
        reverse_proxy http://127.0.0.1:3000 {
    }
}

Thanks

Body:
I'm not saying qed's answer is wrong, however I couldn't get it to work in my case (possibly due to using import templates inside a handle?)...

My solution was... Old config:

private.example.com {
  import my_template argument_1 /path/to/example/argument2
}

This changed to:

private.example.com {
  @blocked not remote_ip 1.2.3.4
  respond @blocked "<h1>Access Denied</h1>" 403
  import my_template argument_1 /path/to/example/argument2
}

Simply adding those two lines allows my site to be accessed on that IP. A test curl from a different IP returned the 403 error.

This is done on Caddy 2.4.6


问:
my terminal inserts and enters the letter "Y" after most git commands
Myself and a coworker have started experiencing an odd issue where the "Y" character is inserted and then entered after nearly every git command. (Git add. , git commit, git push etc)

I am using Visual studio and typing my commands in the terminal window.

This issue does not break any functionality, it's just weird and very hard to google.

答:
Even I had this similar issue with the vscode terminal in windows. Its kinda irritating when it keeps adding that "Y" after git commands automatically. (I did not turn on the feature. This is the default behaviour)

Add this to your vscode settings.json file and it should get disabled.

"terminal.integrated.autoReplies": {
"Terminate batch job (Y/N)": null   }


问:
FontAwesome react-native warnings
i am trying to use fontawesome in react-native-web-app

Did everything as suggested in docs, but for some reason getting this warning in console.

<FontAwesomeIcon icon={faSearch} style={[styles.icon]} /> - this is the part which triggers all warnings. If I will remove it , warning are gone too.

Warnings:

Warning: React does not recognize the secondaryFill prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase secondaryfill instead. If you accidentally passed it from a parent component, remove it from the DOM element.

Warning: React does not recognize the secondaryOpacity prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase secondaryopacity instead. If you accidentally passed it from a parent component, remove it from the DOM element.

Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Path which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node

Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Svg which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node

答:
It looks like this is a known issue with an open pull request in the library: https://github.com/FortAwesome/react-native-fontawesome/pull/74

For now, the last comment in that thread offers a workaround. You can use @fortawesome/react-fontawesome for web, and react-native-fontawesome for Android/iOS.

Copying their code snippet here:

```<code>import {FontAwesomeIcon as FontAwesomeReact} from '@fortawesome/react-fontawesome';
import {FontAwesomeIcon as FontAwesomeNative} from '@fortawesome/react-native-fontawesome';
import {number} from 'prop-types';
import React from 'react';
import {Platform, StyleSheet} from 'react-native';

FaIcon.propTypes = {
  size: number,
};
export default function FaIcon({size, style, ...props}) {
  if (Platform.OS === 'web') {
    const webStyles = StyleSheet.flatten([style, {width: size, height: size}]);
    return <FontAwesomeReact {...props} style={webStyles} />;
  }

  return <FontAwesomeNative {...props} size={size} style={style} />;
}
</code>```

Title: FontAwesome react-native warnings

Body:
It looks like this is a known issue with an open pull request in the library: https://github.com/FortAwesome/react-native-fontawesome/pull/74

For now, the last comment in that thread offers a workaround. You can use @fortawesome/react-fontawesome for web, and react-native-fontawesome for Android/iOS.

Copying their code snippet here:

import {FontAwesomeIcon as FontAwesomeReact} from '@fortawesome/react-fontawesome';
import {FontAwesomeIcon as FontAwesomeNative} from '@fortawesome/react-native-fontawesome';
import {number} from 'prop-types';
import React from 'react';
import {Platform, StyleSheet} from 'react-native';

FaIcon.propTypes = {
  size: number,
};
export default function FaIcon({size, style, ...props}) {
  if (Platform.OS === 'web') {
    const webStyles = StyleSheet.flatten([style, {width: size, height: size}]);
    return <FontAwesomeReact {...props} style={webStyles} />;
  }

  return <FontAwesomeNative {...props} size={size} style={style} />;
}


问:
PHP curl not getting the intended page content, Firefox does. Possible causes?
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

```<code>// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);
</code>```

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

```<code># Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK
</code>```

答:
```<code>// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

$cookieFile = "cookie_china"; // I've changed this value and it seems to be working fine, I get the same results

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK


问:
How to place a button at the same height as a title to the right?
I would like to put my button at the top right at the same height as the title.

Here is an example:

enter image description here

My result for now

enter image description here

I think I have a problem with my divs? The button does not want to be placed at the top right.

<!DOCTYPE html>

<title>HTML CSS JS</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Signalétique de SOLVAY BE (Euronext Brussels)

    <button type="button" (click)="goBack()" class="btn btn-primary mb-2 mr-5 ">Retour</button>

```

答:
You can use rows and columns to keep content aligned in bootstrap. Rows have 12 columns so here I've used 10 columns for the heading and 2 columns for the button and aligned the button right.

<!DOCTYPE html>

<title>HTML CSS JS</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Signalétique de SOLVAY BE (Euronext Brussels)

        <button type="button" (click)="goBack()" class="btn btn-primary">Retour</button>

```

Body:
You can use rows and columns to keep content aligned in bootstrap. Rows have 12 columns so here I've used 10 columns for the heading and 2 columns for the button and aligned the button right.

<!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div class="home-content container">
  <div class="row">
    <div class="col-10 my-2">
        <h2 class="text-start">Signalétique de SOLVAY BE (Euronext Brussels)</h2>
    </div>
    <div class="col-2 my-2 text-right">
        <button type="button" (click)="goBack()" class="btn btn-primary">Retour</button>
    </div>
    <hr class="ms-2 mt-1 mb-5" style="width: 97%">
</div>

</div>
</body>
</html>


问:
After overriding the Application.getClasses() by a custom MessageBodyReader, methods on resource classes cannot be invoked
In a RESTEasy project running on Wildfly server, there is a resource class:

```<code>@Path("/company")
public class CompanyResource {
  @Inject
  CompanyService companyService;

  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public void update(Company company) {
    companyService.update(company);
  }
}
</code>```

Initially the REST API configuration class just extends Application without any extra @override on the existing methods of Application class. An http request, http://localhost:8080/workcontext/company, with PUT as the http request method could work, meaning the CompanyResource.update() can be invoked successfully when receiving the aforementioned http request.

However, I then tried to add a custom MessageBodyReader<Company>:

```<code>public class CompanyReader implements MessageBodyReader<Company> {

  @Override
  public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return true;
}

  @Override
  public Company readFrom(Class<Company> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    try(JsonReader reader = Json.createReader(entityStream)) {
        JsonObject companyJson = reader.readObject();
        Company company = new Company();
        company.setCompanyCode(companyJson.getString("companyCode"));
        company.setName(companyJson.getString("name"));
        company.setHeadquarter(Region.valueOf(companyJson.getString("headquarter")));
        return company;
    }
  }

}
</code>```

In order to make this custom MessageBodyReader<Company> work, I registered this class by overriding the Application.getClasses():

```<code>public class JaxRsConfiguration extends Application {
  @Override
  public Set<Class<?>> getClasses() {
      Set<Class<?>> classes = new HashSet<>();
      classes.add(CompanyReader.class);
      return classes;
  }
}
</code>```

I expected that this MessageBodyReader<Company> could be invoked when sending the same http PUT request, but on the opposite the response is: RESTEASY003210: Could not find resource for full path: http://localhost:8080/workcontext/company

Question: How to make this custom MessageBodyReader work?

答:
You should annotate you're CompanyReader with @Provider. In your application if you return any classes in Application.getClasses() or Application.getSingletons() then, per the spec, those are the only classes allowed to be used in your application.

If either getClasses or getSingletons returns a non-empty collection then only those classes or singletons returned MUST be included in the published JAX-RS application.

Body:
In a RESTEasy project running on Wildfly server, there is a resource class:

@Path("/company")
public class CompanyResource {
  @Inject
  CompanyService companyService;

  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public void update(Company company) {
    companyService.update(company);
  }
}

Initially the REST API configuration class just extends Application without any extra @override on the existing methods of Application class. An http request, http://localhost:8080/workcontext/company, with PUT as the http request method could work, meaning the CompanyResource.update() can be invoked successfully when receiving the aforementioned http request.

However, I then tried to add a custom MessageBodyReader<Company>:

public class CompanyReader implements MessageBodyReader<Company> {

  @Override
  public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return true;
}

  @Override
  public Company readFrom(Class<Company> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    try(JsonReader reader = Json.createReader(entityStream)) {
        JsonObject companyJson = reader.readObject();
        Company company = new Company();
        company.setCompanyCode(companyJson.getString("companyCode"));
        company.setName(companyJson.getString("name"));
        company.setHeadquarter(Region.valueOf(companyJson.getString("headquarter")));
        return company;
    }
  }

}

In order to make this custom MessageBodyReader<Company> work, I registered this class by overriding the Application.getClasses():

public class JaxRsConfiguration extends Application {
  @Override
  public Set<Class<?>> getClasses() {
      Set<Class<?>> classes = new HashSet<>();
      classes.add(CompanyReader.class);
      return classes;
  }
}

I expected that this MessageBodyReader<Company> could be invoked when sending the same http PUT request, but on the opposite the response is: RESTEASY003210: Could not find resource for full path: http://localhost:8080/workcontext/company

Question: How to make this custom MessageBodyReader work?


问:
Extract values at specific location in string in Python
Given a data stream, how do I extract the information (between \x15 and \x15\n) that comes right after a *PAR?

Here is the data stream.

```<code>'%gra:bla bla bla\n',
'*PAR:\tthe cat wants\n',
'\tcookies . \x159400_14000\x15\n',
'%mor:\tdet:art|the adj|cat\n',
'\tpro:rel|which aux|be&3S part|tip-PRESP coord|and pro:sub|he\n',
'\tv|want-3S n|cookie-PL .\n',
'%gra:\t1|3|DET 2|3|MOD 3|4|SUBJ 4|0|ROOT 5|4|JCT 6|7|DET 7|5|POBJ 8|10|LINK\n',
'\t9|10|AUX 10|7|CMOD 11|13|LINK 12|13|SUBJ 13|10|CJCT 14|13|OBJ 15|16|INF\n',
'\t16|14|XMOD 17|16|JCT 18|19|DET 19|17|POBJ 20|4|PUNCT\n',
'*PAR:\ cookies biscuit\n',
'\tis eating a cookie . \x1514000_18647\x15\n',
</code>```

My output should be:

```<code>"9400_14000"
"14000_18647"
...
</code>```

答:
I don't know the type of the data stream so, here is a generator:

```<code>def generator(data_stream):
    pattern = r"\x15([^\x15]+)\x15\n"
    search_next=False
    for line in data_stream:
        if search_next:
            for out in re.findall(pattern, line):
                yield out
            search_next = False
        if line.find("*PAR") > -1:
            search_next = True
</code>```

If it can be converted to a list, you can use this:

```<code>[x for x in generator(data)]
</code>```

Body:
Given a data stream, how do I extract the information (between \x15 and \x15\n) that comes right after a *PAR?

Here is the data stream.

'%gra:bla bla bla\n',
'*PAR:\tthe cat wants\n',
'\tcookies . \x159400_14000\x15\n',
'%mor:\tdet:art|the adj|cat\n',
'\tpro:rel|which aux|be&3S part|tip-PRESP coord|and pro:sub|he\n',
'\tv|want-3S n|cookie-PL .\n',
'%gra:\t1|3|DET 2|3|MOD 3|4|SUBJ 4|0|ROOT 5|4|JCT 6|7|DET 7|5|POBJ 8|10|LINK\n',
'\t9|10|AUX 10|7|CMOD 11|13|LINK 12|13|SUBJ 13|10|CJCT 14|13|OBJ 15|16|INF\n',
'\t16|14|XMOD 17|16|JCT 18|19|DET 19|17|POBJ 20|4|PUNCT\n',
'*PAR:\ cookies biscuit\n',
'\tis eating a cookie . \x1514000_18647\x15\n',

My output should be:

"9400_14000"
"14000_18647"
...

Body:
I don't know the type of the data stream so, here is a generator:

def generator(data_stream):
    pattern = r"\x15([^\x15]+)\x15\n"
    search_next=False
    for line in data_stream:
        if search_next:
            for out in re.findall(pattern, line):
                yield out
            search_next = False
        if line.find("*PAR") > -1:
            search_next = True

If it can be converted to a list, you can use this:

[x for x in generator(data)]


问:
IntelliJ disable warnings
IntelliJ displays yellow markers in the scrollbar on the right for warnings. Is there a way to disable warnings or just the yellow markers in the scrollbar?

Follow-up: The file in question is from Adobe Flex SDK 4.1 frameworks/projects/framework/src/mx/controls/listClasses/ListBase.as. I have all inspections disabled. I've also disabled the JavaScript Intention Power Pack plugin. I have Highlighting Level set to None. With all this I still see warnings.

答:
I wouldn't disable all warnings -- they are there for a purpose.

You can right-click on the yellow warning marker -> "Customize Highlighting Level" -> "Configure Inspections" to tune the severity or turn off particular warnings...

Title: IntelliJ disable warnings


答:
You could use the newer regex module with

```<code>(?:\G(?!\A)|\*PAR)        # fast forward to *PAR
(?:(?!:\*PAR).)+?\\x15\K  # do not overrun another *PAR, fast forward to \x15
.+?                       # start matching...
(?=\\x15|\z)              # ... up to either \x15 or the end
</code>```

See a demo on regex101.com (and mind the singleline and verbose modifier!).

Title: Extract values at specific location in string in Python

Body:
You could use the newer regex module with

(?:\G(?!\A)|\*PAR)        # fast forward to *PAR
(?:(?!:\*PAR).)+?\\x15\K  # do not overrun another *PAR, fast forward to \x15
.+?                       # start matching...
(?=\\x15|\z)              # ... up to either \x15 or the end

See a demo on regex101.com (and mind the singleline and verbose modifier!).


问:
Python create an xml file for every row in excel
I have the following code which creates a xml file from each row in excel. I want to write the xml files in a new folder (currently generates files in same folder as python), how do i change the "output.write()" statement? I am new in programming, started with python 2 weeks ago.

wb_data

df_data is a list of dictionaries.

```<code>[{'Nume': 'Ciuica', 'Prenume': 'Larisa Bianca', 'Data': '30/01/1991 00:00:00', 'Cod': 789454, 'Localitate': 'Targu Jiu'},
 {'Nume': 'Balasa', 'Prenume': 'Valentin', 'Data': '14/09/1989 00:00:00', 'Cod': 215487, 'Localitate': 'Bucuresti'},
 {'Nume': 'Vinatoru', 'Prenume': 'Costin', 'Data': '06/12/1980 00:00:00', 'Cod': 254896, 'Localitate': 'Titu'}]
</code>```

Code:

```<code>import xml.etree.ElementTree as Et
import pandas as pd

wb_data = pd.read_excel("test.xlsx", sheet_name="Data", header=0)
wb_xml = pd.read_excel("test.xlsx", sheet_name="XML", header=0)

df_data = wb_data.to_dict("records")

lista_xml = []
index_lista = 0

for xml in wb_xml["Denumire_xml"]:
    lista_xml.append(xml)

for row in df_data:
    document = Et.Element("Document")
    for key, value in row.items():
        element = Et.SubElement(document, key)
        element.text = str(value)
    output = Et.ElementTree(document)
    Et.indent(output)
    output.write(lista_xml[index_lista])
    index_lista = index_lista + 1
</code>```

答:
Simply use absolute path especially with os.path.join to concatenate folder and file name:

import os
...

xml_file_path = "/path/to/my/xml/outputs"

output.write(
    os.path.join(xml_file_path, lista_xml[index_lista])
)
```
<p>However, consider the new <strong><code>DataFrame.to_xml()</code></strong> to export data frame rows to XML files:</p>
<pre class="lang-py prettyprint-override"><code>import os
import pandas as pd

xml_file_path = "/path/to/my/xml/outputs"

wb_data = pd.read_excel("test.xlsx", sheet_name="Data", header=0)
wb_xml = pd.read_excel("test.xlsx", sheet_name="XML", header=0)

# LIST COMPREHENSION
lista_xml = [xml for xml in wb_xml["Denumire_xml"]]

# SERIES TO LIST CONVERSION
lista_xml = wb_xml["Denumire_xml"].tolist()

# GROUP BY INDEX (I.E., ROW) WITH LOOP NUMBER
for n, (i, sub_df) in enumerate(wb_data.groupby(level=0)):
    sub_df.to_xml(
        os.path.join(xml_file_path, lista_xml[n])
    )
</code>```

Body:
I have the following code which creates a xml file from each row in excel. I want to write the xml files in a new folder (currently generates files in same folder as python), how do i change the "output.write()" statement? I am new in programming, started with python 2 weeks ago.

wb_data

df_data is a list of dictionaries.

[{'Nume': 'Ciuica', 'Prenume': 'Larisa Bianca', 'Data': '30/01/1991 00:00:00', 'Cod': 789454, 'Localitate': 'Targu Jiu'},
 {'Nume': 'Balasa', 'Prenume': 'Valentin', 'Data': '14/09/1989 00:00:00', 'Cod': 215487, 'Localitate': 'Bucuresti'},
 {'Nume': 'Vinatoru', 'Prenume': 'Costin', 'Data': '06/12/1980 00:00:00', 'Cod': 254896, 'Localitate': 'Titu'}]

Code:

import xml.etree.ElementTree as Et
import pandas as pd

wb_data = pd.read_excel("test.xlsx", sheet_name="Data", header=0)
wb_xml = pd.read_excel("test.xlsx", sheet_name="XML", header=0)

df_data = wb_data.to_dict("records")

lista_xml = []
index_lista = 0

for xml in wb_xml["Denumire_xml"]:
    lista_xml.append(xml)

for row in df_data:
    document = Et.Element("Document")
    for key, value in row.items():
        element = Et.SubElement(document, key)
        element.text = str(value)
    output = Et.ElementTree(document)
    Et.indent(output)
    output.write(lista_xml[index_lista])
    index_lista = index_lista + 1

Body:
Simply use absolute path especially with os.path.join to concatenate folder and file name:

import os
...

xml_file_path = "/path/to/my/xml/outputs"

output.write(
    os.path.join(xml_file_path, lista_xml[index_lista])
)

However, consider the new DataFrame.to_xml() to export data frame rows to XML files:

import os
import pandas as pd

xml_file_path = "/path/to/my/xml/outputs"

wb_data = pd.read_excel("test.xlsx", sheet_name="Data", header=0)
wb_xml = pd.read_excel("test.xlsx", sheet_name="XML", header=0)

# LIST COMPREHENSION
lista_xml = [xml for xml in wb_xml["Denumire_xml"]]

# SERIES TO LIST CONVERSION
lista_xml = wb_xml["Denumire_xml"].tolist()

# GROUP BY INDEX (I.E., ROW) WITH LOOP NUMBER
for n, (i, sub_df) in enumerate(wb_data.groupby(level=0)):
    sub_df.to_xml(
        os.path.join(xml_file_path, lista_xml[n])
    )


问:
how to select coefficient in texreg in an easier way
I am analysing a panel dataset with dummy variable fixed effects.
For example, my model looks like

```<code>model1 <- lm_robust(y ~ x1 + x2 + factor(x3):factor(x3), clusters = clusters, data = data)
</code>```

While there are a lot of categories of x3 and x4 generating hundreds of dummies in the table which I do not want to show.
Is there an easier way with texreg to keep only the estimates of x1 and x2 in the output table?

As I am using lm_robust for clustering, so stargazer is not the option here.
Thank you very much in advance.

答:
I do not know how to do this in texreg, but here is one option using
the modelsummary package for
R (disclaimer: I
am the author).

You can use the coef_map argument to select the coefficients to
display. You may also want to look at the coef_omit argument.

library(estimatr)
library(modelsummary)

mod <- lm_robust(hp ~ ., data = mtcars)

modelsummary(mod, coef_map = c("cyl", "disp"))
```

Model 1

cyl
8.204

(10.203)

disp
0.439

(0.179)

Num.Obs.
32

R2
0.903

R2 Adj.
0.857

Std.Errors
HC2

Body:
I am analysing a panel dataset with dummy variable fixed effects.
For example, my model looks like

model1 <- lm_robust(y ~ x1 + x2 + factor(x3):factor(x3), clusters = clusters, data = data)

While there are a lot of categories of x3 and x4 generating hundreds of dummies in the table which I do not want to show.
Is there an easier way with texreg to keep only the estimates of x1 and x2 in the output table?

As I am using lm_robust for clustering, so stargazer is not the option here.
Thank you very much in advance.

Body:
I do not know how to do this in texreg, but here is one option using
the modelsummary package for
R (disclaimer: I
am the author).

You can use the coef_map argument to select the coefficients to
display. You may also want to look at the coef_omit argument.

library(estimatr)
library(modelsummary)

mod <- lm_robust(hp ~ ., data = mtcars)

modelsummary(mod, coef_map = c("cyl", "disp"))

Model 1

cyl
8.204

(10.203)

disp
0.439

(0.179)

Num.Obs.
32

R2
0.903

R2 Adj.
0.857

Std.Errors
HC2


问:
Django - Transferring data to a new database
I am using Django as my web framework with Django REST API. Time and time again, when I try to migrate the table on production, I get a litany of errors. I believe my migrations on development are out of sync with production, and as a result, chaos. Thus each time I attempt major migrations on production I end up needing to use the nuclear option - delete all migrations, and if that fails, nuke the database. (Are migrations even supposed to be committed?)

This time however, I have too much data to lose. I would like to preserve the data. I would like to construct a new database with the new schema, and then manually transfer the old database to the new one. I am not exactly sure how to go about this. Does anyone have any suggestions? Additionally, how can I prevent this from occurring in the future?

答:
From what you're saying, it sounds like you have migration files that are out of wack and you're constantly running into issues relating to database migrations. I would recommend you just remove all of your migration files and start with a new initial migration after you make all the necessary model changes and restructuring of the schema.

When it comes time to make the migration on your production server, it might make the most sense to --fake-initial and manually making the database changes outside of Django so it matches your schema.

I might get a lot of backlash about this and obviously use your best judgement, but from my experience it was much easier to go about this problem this way and not wasting time making custom migration files that try to fix all of your problems.

Addressing your other questions

Time and time again, when I try to migrate the table on production, I get a litany of errors.

I highly recommend you take the time to get acquainted with how to make migrations by reading the official Django docs, you will save yourself a LOT of headache.

... each time I attempt major migrations on production I end up needing to use the nuclear option - delete all migrations

You shouldn't be deleting your migration files every time there's an issue.

Are migrations even supposed to be committed?

You should definitely be committing your migrations. If you're working on a team, they would be using the migration files you created to make the necessary changes on their local DB as well as any dev/prod server you may have.


问:
Post json via cURL
I have a big problem. I can't manage to find a solution. Data is submitted through a form via GET. Apparently the results are then reloaded via AJAX.
I have tried every way possible via cURL.
The server even throws SQL error messages. But unfortunately I can't get it to work. Can anyone help me?</p>
```<code>#{
#  "searchdata": {
#    "required": "1",
#    "statistics": "1",
#    "offer_name": null,
#    "zip": "01069",
#    "location": null,
#    "maxdistance": "5",
#    "target_group": null,
#    "age_group": null,
#    "language": null,
#    "sort": "zip_asc",
#    "record_offset": 0
#  }
#}

#Test-URL = https://pflegefinder.bkk-dachverband.de/aua/searchresult.php?searchdata%5Brequired%5D=1&searchdata%5Bstatistics%5D=1&searchdata%5Boffer_name%5D=&searchdata%5Bzip%5D=01069&searchdata%5Blocation%5D=&searchdata%5Bmaxdistance%5D=5&searchdata%5Btarget_group%5D=&searchdata%5Bage_group%5D=&searchdata%5Blanguage%5D=&searchdata%5Bsort%5D=zip_asc&searchdata%5Brecord_offset%5D=0

 $data = array("required" => "1","statistics"=>"1","offer_name" => null,"zip" => "51143","location" => null,"maxdistance" => "20","target_group" =>  null,"age_group" =>  null,"language" => null, "sort" => "zip_asc", "record_offset" => 0);
 $data_string = urlencode(json_encode($data));

    $url = "https://pflegefinder.bkk-dachverband.de/aua/rest_searchresult.php?".date("U");
    $ch = curl_init();
    // set post fields
    curl_setopt($ch, CURLOPT_URL, ($url));
#   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cookie: MK_CookieConsent={"required":true,"statistics":true},PHPSESSID="6ldq1ffekjeum41gr3b4bp5tqm"'));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    #curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    #curl_setopt($ch, CURLOPT_POSTFIELDS,'searchdata[required]=1&searchdata[statistics]=1&searchdata[offer_name]=&searchdata[zip]=01069&searchdata[location]=&searchdata[maxdistance]=5&searchdata[target_group]=&searchdata[age_group]=&searchdata[language]=&searchdata[sort]=distance_asc&searchdata[record_offset]=0');
    curl_setopt($ch, CURLOPT_POSTFIELDS,array("searchdata"=>$data_string));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
    curl_setopt($ch, CURLOPT_REFERER, 'https://pflegefinder.bkk-dachverband.de/aua/searchresult.php?searchdata%5Brequired%5D=1&searchdata%5Bstatistics%5D=1&searchdata%5Boffer_name%5D=&searchdata%5Bzip%5D=51143&searchdata%5Blocation%5D=&searchdata%5Bmaxdistance%5D=5&searchdata%5Btarget_group%5D=&searchdata%5Bage_group%5D=&searchdata%5Blanguage%5D=&searchdata%5Bsort%5D=distance_asc&searchdata%5Brecord_offset%5D=0');
#   curl_setopt($ch, CURLOPT_REFERER, 'https://pflegefinder.bkk-dachverband.de/aua/');
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_VERBOSE, '0');
    curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile2.txt");
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile2.txt");
    curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
    $seite = curl_exec($ch);
    curl_close($ch);
</code>```

答:
The misspelling of laguage (supposed to be language is causing the SQL errors that you are seeing.

I don't write much PHP anymore, I used the Insomnia HTTP client to enter your request which is how I spotted the mistake. I exported the code below which works great for me.

<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://pflegefinder.bkk-dachverband.de/aua/rest_searchresult.php",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\n\t\"searchdata\": {\n\t\t\"required\": 1,\n\t\t\"offer_name\": null,\n\t\t\"zip\": 51143,\n\t\t\"location\": null,\n\t\t\"maxdistance\": 20,\n\t\t\"target_group\": null,\n\t\t\"age_group\": null,\n\t\t\"language\": null,\n\t\t\"sort\": \"zip_asc\",\n\t\t\"record_offset\": 0\n\t}\n}",
  CURLOPT_COOKIE => "PHPSESSID=2a4tctjc0ec6potr1p5a0tonir",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
```

Title: Post json via cURL

Body:
I have a big problem. I can't manage to find a solution. Data is submitted through a form via GET. Apparently the results are then reloaded via AJAX.
I have tried every way possible via cURL.
The server even throws SQL error messages. But unfortunately I can't get it to work. Can anyone help me?

#{
#  "searchdata": {
#    "required": "1",
#    "statistics": "1",
#    "offer_name": null,
#    "zip": "01069",
#    "location": null,
#    "maxdistance": "5",
#    "target_group": null,
#    "age_group": null,
#    "language": null,
#    "sort": "zip_asc",
#    "record_offset": 0
#  }
#}

#Test-URL = https://pflegefinder.bkk-dachverband.de/aua/searchresult.php?searchdata%5Brequired%5D=1&searchdata%5Bstatistics%5D=1&searchdata%5Boffer_name%5D=&searchdata%5Bzip%5D=01069&searchdata%5Blocation%5D=&searchdata%5Bmaxdistance%5D=5&searchdata%5Btarget_group%5D=&searchdata%5Bage_group%5D=&searchdata%5Blanguage%5D=&searchdata%5Bsort%5D=zip_asc&searchdata%5Brecord_offset%5D=0

 $data = array("required" => "1","statistics"=>"1","offer_name" => null,"zip" => "51143","location" => null,"maxdistance" => "20","target_group" =>  null,"age_group" =>  null,"language" => null, "sort" => "zip_asc", "record_offset" => 0);
 $data_string = urlencode(json_encode($data));

    $url = "https://pflegefinder.bkk-dachverband.de/aua/rest_searchresult.php?".date("U");
    $ch = curl_init();
    // set post fields
    curl_setopt($ch, CURLOPT_URL, ($url));
#   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cookie: MK_CookieConsent={"required":true,"statistics":true},PHPSESSID="6ldq1ffekjeum41gr3b4bp5tqm"'));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    #curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    #curl_setopt($ch, CURLOPT_POSTFIELDS,'searchdata[required]=1&searchdata[statistics]=1&searchdata[offer_name]=&searchdata[zip]=01069&searchdata[location]=&searchdata[maxdistance]=5&searchdata[target_group]=&searchdata[age_group]=&searchdata[language]=&searchdata[sort]=distance_asc&searchdata[record_offset]=0');
    curl_setopt($ch, CURLOPT_POSTFIELDS,array("searchdata"=>$data_string));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
    curl_setopt($ch, CURLOPT_REFERER, 'https://pflegefinder.bkk-dachverband.de/aua/searchresult.php?searchdata%5Brequired%5D=1&searchdata%5Bstatistics%5D=1&searchdata%5Boffer_name%5D=&searchdata%5Bzip%5D=51143&searchdata%5Blocation%5D=&searchdata%5Bmaxdistance%5D=5&searchdata%5Btarget_group%5D=&searchdata%5Bage_group%5D=&searchdata%5Blanguage%5D=&searchdata%5Bsort%5D=distance_asc&searchdata%5Brecord_offset%5D=0');
#   curl_setopt($ch, CURLOPT_REFERER, 'https://pflegefinder.bkk-dachverband.de/aua/');
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_VERBOSE, '0');
    curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile2.txt");
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile2.txt");
    curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
    $seite = curl_exec($ch);
    curl_close($ch);


问:
Python values not getting added to Tuple
Hello I have a situation where I am trying to make a filter in my code customizable so there is minimum duplication of code below is the code that I want to update

```<code>for ent in NACLS:
        response = ec2.describe_network_acls(Filters=[{'Name': 'network-acl-id', 'Values': [naclID]},
                                                      {'Name': 'entry.rule-number', 'Values': [str(ent[0])]},
                                                      {'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]},
                                                      {'Name': 'entry.port-range.from', 'Values': [str(ent[2])]},
                                                      {'Name': 'entry.port-range.to', 'Values': [str(ent[2])]},
                                                      {'Name': 'entry.rule-action', 'Values': ["deny"]},
                                                      ])
</code>```

I want the filter to customizable for example

```<code>for ent in NACLS:
  if add = True:
     response = ec2.describe_network_acls(Filters=[{'Name': 'network-acl-id', 'Values': [naclID]},
                                                   {'Name': 'entry.rule-number', 'Values': [str(ent[0])]},
                                              ])
  else:
    response = ec2.describe_network_acls(Filters=[{'Name': 'network-acl-id', 'Values': [naclID]},
                                                  {'Name': 'entry.rule-number', 'Values': [str(ent[0])]},
                                                  {'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]},
                                                  {'Name': 'entry.port-range.from', 'Values': [str(ent[2])]},
                                                  {'Name': 'entry.port-range.to', 'Values': [str(ent[2])]},
                                                  {'Name': 'entry.rule-action', 'Values': ["deny"]},
                                                  ])
</code>```

This is what I was wanting to do but doesn't work please let me know if there is a better way to achieve this

```<code>for ent in NACLS:
    filters = {'Name': 'network-acl-id', 'Values': [naclID]}, {'Name': 'entry.rule-number', 'Values': [str(ent[0])]}
    filters = filters + tuple({'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]}) //we can add more but this was just to test
print(str(filters)[1:-1])
</code>```

The output for this is -

```<code>{'Name': 'network-acl-id', 'Values': ['acl-08128a2540']}, {'Name': 'entry.rule-number', 'Values': ['80']}, 'Name', 'Values'
</code>```

When I try to add the value in tuple it shows as blank can someone please guide me on what I am doing wrong here?

答:
I suspect that by adding tuples, you meant to add the dictionary to the tuple of filters, which is not what you are doing in your current script. I suggest that you replace

```<code>filters = filters + tuple({'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]})
</code>```

with

```<code>filters = filters + ({'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]},)
</code>```

Body:
Hello I have a situation where I am trying to make a filter in my code customizable so there is minimum duplication of code below is the code that I want to update

for ent in NACLS:
        response = ec2.describe_network_acls(Filters=[{'Name': 'network-acl-id', 'Values': [naclID]},
                                                      {'Name': 'entry.rule-number', 'Values': [str(ent[0])]},
                                                      {'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]},
                                                      {'Name': 'entry.port-range.from', 'Values': [str(ent[2])]},
                                                      {'Name': 'entry.port-range.to', 'Values': [str(ent[2])]},
                                                      {'Name': 'entry.rule-action', 'Values': ["deny"]},
                                                      ])

I want the filter to customizable for example

for ent in NACLS:
  if add = True:
     response = ec2.describe_network_acls(Filters=[{'Name': 'network-acl-id', 'Values': [naclID]},
                                                   {'Name': 'entry.rule-number', 'Values': [str(ent[0])]},
                                              ])
  else:
    response = ec2.describe_network_acls(Filters=[{'Name': 'network-acl-id', 'Values': [naclID]},
                                                  {'Name': 'entry.rule-number', 'Values': [str(ent[0])]},
                                                  {'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]},
                                                  {'Name': 'entry.port-range.from', 'Values': [str(ent[2])]},
                                                  {'Name': 'entry.port-range.to', 'Values': [str(ent[2])]},
                                                  {'Name': 'entry.rule-action', 'Values': ["deny"]},
                                                  ])

This is what I was wanting to do but doesn't work please let me know if there is a better way to achieve this

for ent in NACLS:
    filters = {'Name': 'network-acl-id', 'Values': [naclID]}, {'Name': 'entry.rule-number', 'Values': [str(ent[0])]}
    filters = filters + tuple({'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]}) //we can add more but this was just to test
print(str(filters)[1:-1])

The output for this is -

{'Name': 'network-acl-id', 'Values': ['acl-08128a2540']}, {'Name': 'entry.rule-number', 'Values': ['80']}, 'Name', 'Values'

When I try to add the value in tuple it shows as blank can someone please guide me on what I am doing wrong here?

Body:
I suspect that by adding tuples, you meant to add the dictionary to the tuple of filters, which is not what you are doing in your current script. I suggest that you replace

filters = filters + tuple({'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]})

with

filters = filters + ({'Name': 'entry.protocol', 'Values': [ProtoDict[ent[1]]]},)


问:
Is there a simpler way to check radio buttons?
I'm new to coding and learning HTML as well as JavaScript. I wrote a set of radio buttons in HTML so that you could toggle an option and click the submit button, and it would use JS to display the option you chose below. The code works fine, however:

The code is quite clunky, I'm positive there must be a much more effective way of writing this code.

I didn't use the form tag, should I? I'm still not entirely sure what form does other than I know it's used to collect data somehow

var x;

function displayText() {
  if (document.getElementById("lsd").checked === true) {
    x = document.getElementById("lsd").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("shrooms").checked === true) {
    x = document.getElementById("shrooms").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("dmt").checked === true) {
    x = document.getElementById("dmt").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("peyote").checked === true) {
    x = document.getElementById("peyote").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("toad").checked === true) {
    x = document.getElementById("toad").value;
    document.getElementById("output").innerHTML = x;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p></code>```

答:
You can simplify it like this:
You can paste it directly in HTML file and test.
I would not recommend this for prod but for learning purposes it is good.

<!doctype html>

  <meta charset="UTF-8">
  <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
        name="viewport">
  <meta content="ie=edge" http-equiv="X-UA-Compatible">
  <title>Document</title>

What's your preferred psychedelic substance?

<form id="form">

</form>

<button onclick="displayText()">Submit!</button>

  User's favorite drug is:

```

Body:
I'm new to coding and learning HTML as well as JavaScript. I wrote a set of radio buttons in HTML so that you could toggle an option and click the submit button, and it would use JS to display the option you chose below. The code works fine, however:

The code is quite clunky, I'm positive there must be a much more effective way of writing this code.

I didn't use the form tag, should I? I'm still not entirely sure what form does other than I know it's used to collect data somehow

var x;

function displayText() {
  if (document.getElementById("lsd").checked === true) {
    x = document.getElementById("lsd").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("shrooms").checked === true) {
    x = document.getElementById("shrooms").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("dmt").checked === true) {
    x = document.getElementById("dmt").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("peyote").checked === true) {
    x = document.getElementById("peyote").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("toad").checked === true) {
    x = document.getElementById("toad").value;
    document.getElementById("output").innerHTML = x;
  }
}

What's your preferred psychedelic substance?

<input type="radio" id="lsd" name="drugs" value="lsd">
LSD

<input type="radio" id="shrooms" name="drugs" value="shrooms">
Magic Mushrooms/psilocybin

<input type="radio" id="dmt" name="drugs" value="dmt">
DMT

<input type="radio" id="peyote" name="drugs" value="peyote">
Peyote

<input type="radio" id="toad" name="drugs" value="toad">
The Toad/5-MeO-DMT

<button onclick="displayText()">Submit!</button>

  User's favorite drug is:

Body:
You can simplify it like this:
You can paste it directly in HTML file and test.
I would not recommend this for prod but for learning purposes it is good.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
        name="viewport">
  <meta content="ie=edge" http-equiv="X-UA-Compatible">
  <title>Document</title>
</head>
<body>
<p>What's your preferred psychedelic substance?</p>
<form id="form">

</form>

<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p>
</body>
<script>
  const drugs = {
    "lsd": "LSD",
    "shrooms": "Magic Mushrooms/psilocybin",
    "dmt": "DMT",
    "peyote": "Peyote",
    "toad": "The Toad/5-MeO-DMT"
  };

  const form = document.getElementById("form");
  for (const key in drugs) {
    form.innerHTML += `
  <label style="display: block" for="lsd">
    <input type="radio" id="${key}" name="drugs" value="${key}">
    ${drugs[key]}
  </label>`;
  }

  function displayText() {
    const drugs = document.getElementsByName("drugs");
    for (let i = 0; i < drugs.length; i++) {
      if (drugs[i].checked) {
        document.getElementById("output").innerHTML = drugs[i].value;
      }
    }
  }
</script>
</html>


问:
Breaking google sheet table into smaller tables and send gmail to corresponding emails(google script)
Is there a way that we can break the main table below into smaller tables and email (gmail) them to the corresponding email on the first column?

Bank's Email
Client name
Age
Bank with

bank1@hotmail.com
Client 1
19
Bank 1

bank1@hotmail.com
Client 2
32
Bank 1

bank1@hotmail.com
Client 3
22
Bank 1

bank2@hotmail.com
Client 4
34
Bank 2

bank2@hotmail.com
Client 5
22
Bank 2

bank1@hotmail.com
Client 5
28
Bank 3

For example, send the below table as gmail to bank 1's email ?

Client name
Age
Bank with

Client 1
19
Bank 1

Client 2
32
Bank 1

Client 3
22
Bank 1

and below to bank 2's email (same with bank 3)?

Client name
Age
Bank with

Client 4
34
Bank 2

Client 5
22
Bank 2

Thanks!

答:
You can try this.  I leave it up to you to adjust the styling to suit your taste.  I edited this to add the first part. Sorting the clients.</p>
```<code>function test() {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getSheetByName("Sheet2");
    // dont get header
    var data = sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
    var banks = [];
    data.forEach( row => banks.push(row[0]) );
    banks = [...new Set(banks)];
    var results = [];
    function addClient(row) {
      var i = banks.indexOf(row[0]);
      if( results[i] === undefined ) results[i] = [];
      row.shift();
      results[i].push(row);
    }
    data.forEach( addClient );
    results.forEach( (bank,index) => createTable(banks[index],bank) );
  }
  catch(err) {
    console.log(err);
  }
}

function createTable(email,data) {
  try {
    var table = "<table style='border-width:thin;border-style:solid;border-color:black'>";
    function addCell(value) {
      table = table.concat("<td style='border-width:thin;border-style:solid;border-color:black;width:20px'>");
      table = table.concat(value.toString());
      table = table.concat("</td>");
    }
    function addRow(row) {
      table = table.concat("<tr>");
      row.forEach( addCell );
      table = table.concat("</tr>");
    }
    data.forEach( addRow )
    table = table.concat("</table>")
    console.log(table);
    MailApp.sendEmail( {
      to: "thewized@gmail.com",
      subject: "Test",
      htmlBody: table });
  }
  catch(err) {
    console.log(err);
  }
}
</code>```

Body:
You can try this.  I leave it up to you to adjust the styling to suit your taste.  I edited this to add the first part. Sorting the clients.

function test() {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getSheetByName("Sheet2");
    // dont get header
    var data = sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
    var banks = [];
    data.forEach( row => banks.push(row[0]) );
    banks = [...new Set(banks)];
    var results = [];
    function addClient(row) {
      var i = banks.indexOf(row[0]);
      if( results[i] === undefined ) results[i] = [];
      row.shift();
      results[i].push(row);
    }
    data.forEach( addClient );
    results.forEach( (bank,index) => createTable(banks[index],bank) );
  }
  catch(err) {
    console.log(err);
  }
}

function createTable(email,data) {
  try {
    var table = "<table style='border-width:thin;border-style:solid;border-color:black'>";
    function addCell(value) {
      table = table.concat("<td style='border-width:thin;border-style:solid;border-color:black;width:20px'>");
      table = table.concat(value.toString());
      table = table.concat("</td>");
    }
    function addRow(row) {
      table = table.concat("<tr>");
      row.forEach( addCell );
      table = table.concat("</tr>");
    }
    data.forEach( addRow )
    table = table.concat("</table>")
    console.log(table);
    MailApp.sendEmail( {
      to: "thewized@gmail.com",
      subject: "Test",
      htmlBody: table });
  }
  catch(err) {
    console.log(err);
  }
}


问:
Expression in Polars select context that refers to earlier alias
Is there a way to allow an expression in Polars to refer to a previous aliased expression? For example, this code that defines two new columns errors because the second new column refers to the first:

import polars as pl

df = pl.DataFrame(dict(x=[0, 0, 1]))

df.select([
  (pl.col('x') + 1).alias('y'),
  (pl.col('y') * 2).alias('z')],
)
# pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value:
# NotFound("Unable to get field named \"y\". Valid fields: [\"x\"]")
```

The error makes it obvious that the failure is caused by the first alias not being visible to the second expression. Is there a straightforward way to make this work?

答:
One workaround is to pull out each new column into its own with_column call and then do a final select to keep the columns you were supposed to keep. You will probably want to make sure this is done lazily.

import polars as pl

df = pl.DataFrame(dict(x=[0, 0, 1]))

(df
  .lazy()
  .with_column((pl.col("x") + 1).alias("y"))
  .with_column((pl.col("y") * 2).alias("z"))
  .select(["y", "z"])
  .collect()
)
# shape: (3, 2)
# ┌─────┬─────┐
# │ y   ┆ z   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 1   ┆ 2   │
# ├╌╌╌╌╌┼╌╌╌╌╌┤
# │ 1   ┆ 2   │
# ├╌╌╌╌╌┼╌╌╌╌╌┤
# │ 2   ┆ 4   │
# └─────┴─────┘
```

Body:
Is there a way to allow an expression in Polars to refer to a previous aliased expression? For example, this code that defines two new columns errors because the second new column refers to the first:

import polars as pl

df = pl.DataFrame(dict(x=[0, 0, 1]))

df.select([
  (pl.col('x') + 1).alias('y'),
  (pl.col('y') * 2).alias('z')],
)
# pyo3_runtime.PanicException: called `Result::unwrap()` on an `Err` value:
# NotFound("Unable to get field named \"y\". Valid fields: [\"x\"]")

The error makes it obvious that the failure is caused by the first alias not being visible to the second expression. Is there a straightforward way to make this work?


问:
insmod: ERROR: could not insert module HelloWorld.ko: Operation not permitted
I am trying to learn linux and kernel development.

I am able to build the module but am unable to load it.

HelloWorld.c

```<code>/*
 *  hello-1.c - The simplest kernel module.
 */
#include <linux/module.h>   /* Needed by all modules */
#include <linux/kernel.h>   /* Needed for KERN_INFO */

int init_module(void)
{
    printk(KERN_INFO "Hello world 1.\n");

    /*
     * A non 0 return means init_module failed; module can't be loaded.
     */
    return 0;
}

void cleanup_module(void)
{
    printk(KERN_INFO "Goodbye world 1.\n");
}
</code>```

And here is my make file:

```<code>KERNEL_SOURCE := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

obj-m += HelloWorld.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code>```

while doing insmod for loading the module permission is getting denied. I tried even doing it with root and also with modprobe, but no use.

I also tried Link but issue still the same.

Hope i get some help. I am using ubuntu 18.04LTS.

答:
If $ sudo insmod file_name.ko fails with mentioned error, then do dmesg | tail -1

and it will give idea of what exactly went wrong while installing kernel-module.

In my case it was because another module was overlapping on same /sys/class location.

After doing sudo rmmod <that_module.ko> I was able to load my new kernel module.

Body:
I am trying to learn linux and kernel development.

I am able to build the module but am unable to load it.

HelloWorld.c

/*
 *  hello-1.c - The simplest kernel module.
 */
#include <linux/module.h>   /* Needed by all modules */
#include <linux/kernel.h>   /* Needed for KERN_INFO */

int init_module(void)
{
    printk(KERN_INFO "Hello world 1.\n");

    /*
     * A non 0 return means init_module failed; module can't be loaded.
     */
    return 0;
}

void cleanup_module(void)
{
    printk(KERN_INFO "Goodbye world 1.\n");
}

And here is my make file:

KERNEL_SOURCE := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

obj-m += HelloWorld.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

while doing insmod for loading the module permission is getting denied. I tried even doing it with root and also with modprobe, but no use.

I also tried Link but issue still the same.

Hope i get some help. I am using ubuntu 18.04LTS.


问:
WPF's DataContext questions
I asked about how does it work with INotifyPropertyChanged interface( How does WPF INotifyPropertyChanged work? ), and it requires me to connect XAML's DataContext to the INotifyPropertyChanged inherit instances as follows.

```<code>MainViewModel model = new MainViewModel();
this.DataContext = model;
</code>```

And I also found a recommendation to have a comment for DataContext that each XMAL uses( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml-tip-datacontext-comment/ ).

When I have multiple XAML files, and when I want to link the DataContext to different ViewModel, I guess I need to make the each XAML.CS file to contain this code (model varies for each xaml.cs) :this.DataContext = model;.

Is this correct?

How can I do the same thing in XAML file?

What's the magic behind this DataContext thing? I mean, how does DataContext work?

答:
The DataContext is really one of the main keys to the binding system in WPF.  When you design your View (the XAML), you're setting up data bindings, but these are all being done by name (effectively, as a string).  The "nearest" DataContext up the visual hierarchy is the object that WPF uses to find the matching property (by name) and wire up the binding.

The suggestion of putting the comment in place is a good one - it helps because the names chosen really depend on the ViewModel (DataContext), so a View's XAML file is really tied to a specific type of DataContext.

Note also that there are other approaches available to wire up the DataContext other than setting it in code behind, including using locators, DataTemplates, setting it directly in XAML, etc.

Title: WPF's DataContext questions

Body:
I asked about how does it work with INotifyPropertyChanged interface( How does WPF INotifyPropertyChanged work? ), and it requires me to connect XAML's DataContext to the INotifyPropertyChanged inherit instances as follows.

MainViewModel model = new MainViewModel();
this.DataContext = model;

And I also found a recommendation to have a comment for DataContext that each XMAL uses( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml-tip-datacontext-comment/ ).

When I have multiple XAML files, and when I want to link the DataContext to different ViewModel, I guess I need to make the each XAML.CS file to contain this code (model varies for each xaml.cs) :this.DataContext = model;.

Is this correct?

How can I do the same thing in XAML file?

What's the magic behind this DataContext thing? I mean, how does DataContext work?


问:
How do I create an array of objects?
I only know Java, and I am learning how to do c++ right now. I currently have an object called "node". I want to make an array of those elements in a different class, and I have to perform many operations on this array. Because of this, I am trying to declare a global array variable that gets initialized in my constructor. In Java, this would've been done by

```<code>ObjectName[] variableName = new ObjectName[size];
</code>```

but I am not sure how to do it in c++. I've tried declaring it similar to how I declared the other global arrays, with

```<code>Node* nodes;
</code>```

and then in my constructor:

```<code>nodes = new Node[size]
</code>```

but I got a bunch of compiler errors. How am I supposed to do this? This is only my second week of coding in c++, so try to keep answers basic.

答:
In C++ you use vector more often than array. You also distinguish between creating objects on the stack and on the heap (you already mentioned that concept; in C++ you are more actively involved in thinking about that).

You also may want to pay attention which C++ Standard you are using. Some concepts are not available in older standards. I tried to mention some in the example code below.

When dealing with arrays in C/C++ you should understand the notion of pointers, which I believe is the probable cause of your confusion. new creates an object on the heap and returns a pointer. When creating an array, then the returned pointer points to the first element.

Avoid new if you can. In newer C++ standards there are better concepts of smart pointers (e.g. std::unique_ptr<...>); I will not dive into that since you are just beginning. Be patient with learning C++, I am sure you will succeed, it takes time really.

```<code>#include <iostream>
#include <array>
#include <vector>

struct Node {
    std::string name = "node";
};

int main() {

    const size_t size = 10;

    // you can create it on the stack
    // will be deleted when leaving the block/scope
    Node nodes1[size];
    nodes1[0].name = "first node1";
    std::cout << nodes1[0].name << std::endl;

    // you can create it on the heap
    // you have to delete the objects yourself then
    Node *nodes2 = new Node[size];
    nodes2[0].name = "first node2";
    std::cout << nodes2[0].name << std::endl;

    // in C++ 11 and later you can use std::array<...>
    // you have to include the header <array> for that
    std::array<Node, size> nodes3;
    nodes3[0].name = "first node3";
    std::cout << nodes3[0].name << std::endl;

    // in C++ you use array "seldom"
    // instead you use the containers quite a lot as far as I have learned
    // e.g. you can include <vector>; can be used like an array
    std::vector<Node> nodes4(size);
    nodes4[0].name = "first node4";
    std::cout << nodes4[0].name << std::endl;

    // you can iterate over a vector like you know it from an array
    for (size_t i = 0; i < nodes4.size(); ++i) {
        if (i == 0) {
            std::cout << nodes4[i].name << std::endl;
        }
    }

    // in C++ you will soon learn about iterators too
    for (auto iter = nodes4.begin(); iter != nodes4.end(); iter++) {
        if (iter == nodes4.begin()) {
            std::cout << iter->name << std::endl;
        }
    }

    return 0;
}
</code>```

Title: How do I create an array of objects?

Body:
I only know Java, and I am learning how to do c++ right now. I currently have an object called "node". I want to make an array of those elements in a different class, and I have to perform many operations on this array. Because of this, I am trying to declare a global array variable that gets initialized in my constructor. In Java, this would've been done by

ObjectName[] variableName = new ObjectName[size];

but I am not sure how to do it in c++. I've tried declaring it similar to how I declared the other global arrays, with

Node* nodes;

and then in my constructor:

nodes = new Node[size]

but I got a bunch of compiler errors. How am I supposed to do this? This is only my second week of coding in c++, so try to keep answers basic.

Body:
In C++ you use vector more often than array. You also distinguish between creating objects on the stack and on the heap (you already mentioned that concept; in C++ you are more actively involved in thinking about that).

You also may want to pay attention which C++ Standard you are using. Some concepts are not available in older standards. I tried to mention some in the example code below.

When dealing with arrays in C/C++ you should understand the notion of pointers, which I believe is the probable cause of your confusion. new creates an object on the heap and returns a pointer. When creating an array, then the returned pointer points to the first element.

Avoid new if you can. In newer C++ standards there are better concepts of smart pointers (e.g. std::unique_ptr<...>); I will not dive into that since you are just beginning. Be patient with learning C++, I am sure you will succeed, it takes time really.

#include <iostream>
#include <array>
#include <vector>

struct Node {
    std::string name = "node";
};

int main() {

    const size_t size = 10;

    // you can create it on the stack
    // will be deleted when leaving the block/scope
    Node nodes1[size];
    nodes1[0].name = "first node1";
    std::cout << nodes1[0].name << std::endl;

    // you can create it on the heap
    // you have to delete the objects yourself then
    Node *nodes2 = new Node[size];
    nodes2[0].name = "first node2";
    std::cout << nodes2[0].name << std::endl;

    // in C++ 11 and later you can use std::array<...>
    // you have to include the header <array> for that
    std::array<Node, size> nodes3;
    nodes3[0].name = "first node3";
    std::cout << nodes3[0].name << std::endl;

    // in C++ you use array "seldom"
    // instead you use the containers quite a lot as far as I have learned
    // e.g. you can include <vector>; can be used like an array
    std::vector<Node> nodes4(size);
    nodes4[0].name = "first node4";
    std::cout << nodes4[0].name << std::endl;

    // you can iterate over a vector like you know it from an array
    for (size_t i = 0; i < nodes4.size(); ++i) {
        if (i == 0) {
            std::cout << nodes4[i].name << std::endl;
        }
    }

    // in C++ you will soon learn about iterators too
    for (auto iter = nodes4.begin(); iter != nodes4.end(); iter++) {
        if (iter == nodes4.begin()) {
            std::cout << iter->name << std::endl;
        }
    }

    return 0;
}


问:
Firebase onDataChange returns null value after internet reconnection
I have this code to read data and write the value into an object

```<code>if(SpecialFunction.isNetworkAvailable()) {
    databaseContent.loadAccountFromDatabase(account -> {
        this.account = account;
        binding.textView3.setText(account.toString());
    });
} else {
    startActivity(new Intent(this, InternetTroubleActivity.class));
}
</code>```

Where databaseContent is a class which contains Firebase logic which I need.
In loadAccountFromDatabase I have next code which works with one problem.

```<code>  public void loadAccountFromDatabase(FirebaseCallbackAccount accountFirebaseCallback) {
     ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()) {
                account = snapshot.getValue(Account.class);
            } else {
                account = new Account();
                setDefaultAccount();
            }
            accountFirebaseCallback.onCallback(account);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Log.e("loadAccountFromDatabase", "Error:  " + error.toString());
        }
    };
    database.addValueEventListener(valueEventListener);
}
</code>```

When I try to read data after internet reconnection or when I turn on internet after onStart() and run loadAccountFromDatabase I get null value of my snapshot.
I have a method (isNetworkAvailable()) which works well and when I don't have internet connection it returns false.
The next part of code doesn't work properly. The snapshot.exists returns true and snapshot.getValue returns null although the value is other.

```<code>if (snapshot.exists()) {
    account = snapshot.getValue(Account.class);
}
</code>```

If I run an application with internet connection everything works well while I don't turn off internet and try to read again.
I also tried to use database.get().addOnCompleteListener(onCompleteListener)... but I got the same result. Everything works well while I don't try to read data after internet reconnection.

database.keepSynced(true) also doesn't help.

UPDATE##

Database init:

```<code>private final String USER_KEY = "Account", PURCHASES = "purchases";

    public void init() {
        mAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();
        database = firebaseDatabase.getReference(String.format("%s/%s", USER_KEY, mAuth.getUid()));
    }
</code>```

Structure:
console

UPDATE 2##

To help you understand the problem I add screenshot of log. GREEN box: I run my app with internet connection. The data was read and wrote correct. RED box: I closed my app, destroyed activity, turned off internet. Then I run my app, but method isNetworkAvailable didn't let me run MainActivity. Then I turned on internet and clicked on button. The data was being tried to read but I got object with null variables althrough they are not null. If you think that something is wrong with isNetworkAvailable I tell you that this problem was before I have added it. I was hoping that it would help me to read correct but it didn't help.
logcat

UPDATE 3##

JSON:

```<code>{
  "Account" : {
    "wBOZsnGGywYIpap3cLZodPOWcpt2" : {
      "budget" : 100,
      "budgetLastMonth" : 0,
      "budgetLeft" : 100,
      "currencyType" : "USD",
      "email" : "bibishka117@gmail.com",
      "id" : "wBOZsnGGywYIpap3cLZodPOWcpt2",
      "personName" : "новый пользователь"
    }
  }
}
</code>```

答:
I found a problem. 4 hours of reading my code and stackoverflow. I don't know how, but in onPause () I had code that writes null object to a database.
So when I tested and turned on / off the Internet, I run it. So I wrote a null object that was not instantly updated on the console, and when I turned on the Internet, the object was updated to zero in the database and then read in my app. :]</p>

Body:
I have this code to read data and write the value into an object

if(SpecialFunction.isNetworkAvailable()) {
    databaseContent.loadAccountFromDatabase(account -> {
        this.account = account;
        binding.textView3.setText(account.toString());
    });
} else {
    startActivity(new Intent(this, InternetTroubleActivity.class));
}

Where databaseContent is a class which contains Firebase logic which I need.
In loadAccountFromDatabase I have next code which works with one problem.

  public void loadAccountFromDatabase(FirebaseCallbackAccount accountFirebaseCallback) {
     ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()) {
                account = snapshot.getValue(Account.class);
            } else {
                account = new Account();
                setDefaultAccount();
            }
            accountFirebaseCallback.onCallback(account);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Log.e("loadAccountFromDatabase", "Error:  " + error.toString());
        }
    };
    database.addValueEventListener(valueEventListener);
}

When I try to read data after internet reconnection or when I turn on internet after onStart() and run loadAccountFromDatabase I get null value of my snapshot.
I have a method (isNetworkAvailable()) which works well and when I don't have internet connection it returns false.
The next part of code doesn't work properly. The snapshot.exists returns true and snapshot.getValue returns null although the value is other.

if (snapshot.exists()) {
    account = snapshot.getValue(Account.class);
}

If I run an application with internet connection everything works well while I don't turn off internet and try to read again.
I also tried to use database.get().addOnCompleteListener(onCompleteListener)... but I got the same result. Everything works well while I don't try to read data after internet reconnection.

database.keepSynced(true) also doesn't help.

UPDATE##

Database init:

private final String USER_KEY = "Account", PURCHASES = "purchases";

    public void init() {
        mAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();
        database = firebaseDatabase.getReference(String.format("%s/%s", USER_KEY, mAuth.getUid()));
    }

Structure:
console

UPDATE 2##

To help you understand the problem I add screenshot of log. GREEN box: I run my app with internet connection. The data was read and wrote correct. RED box: I closed my app, destroyed activity, turned off internet. Then I run my app, but method isNetworkAvailable didn't let me run MainActivity. Then I turned on internet and clicked on button. The data was being tried to read but I got object with null variables althrough they are not null. If you think that something is wrong with isNetworkAvailable I tell you that this problem was before I have added it. I was hoping that it would help me to read correct but it didn't help.
logcat

UPDATE 3##

JSON:

{
  "Account" : {
    "wBOZsnGGywYIpap3cLZodPOWcpt2" : {
      "budget" : 100,
      "budgetLastMonth" : 0,
      "budgetLeft" : 100,
      "currencyType" : "USD",
      "email" : "bibishka117@gmail.com",
      "id" : "wBOZsnGGywYIpap3cLZodPOWcpt2",
      "personName" : "новый пользователь"
    }
  }
}


问:
TypeError: 'NoneType' object is not callable - python
I have been reading about this error and I understand that it is because I expect a function to return a result but in reality it is not, I have reviewed my code and I do not find that it could be wrong</p>
```<code>class Estudiante:
   def __init__(self):
      self.nombre = ""
      self.cedula = 0
      self.apellido = ""
      self.asignatura = ""
      self.cantidadDeNotas = 0
      self.notas = []

   @property
      def obtenerDatos(self):
         print("ingrese los datos del estudiante")
         self.cedula = int(input("Cedula del estudiante: "))
         self.nombre = input("Nombre del estudiante: ")
         self.apellido = input("Apellido del estudiante: ")
         self.asignatura = input("Asignatura: ")
         while True:
            self.cantidadDeNotas = int(input("¿cual es la cantidad de notas que desea ingresar?(más de 4): "))
            if self.cantidadDeNotas > 4:
                break
            else:
                print("ingrese una cantidad mayor a 4")

estudiante = Estudiante()
estudiante.obtenerDatos()
</code>```

答:
When you decorate a method as @property, it will automatically become a getter method for a property it is named after. It is then accessed not as object.method() but object.method (which will still call the same method underneath, and evaluate to its return value).

In your case, you are declaring obtenerDatos a property getter, but then calling estudiante.obtenerDatos(). This would be like calling estudiante.obtenerDatos()() if there were no @property tag - you call the method and then try to call its return value as a function.

Since the method does not return a value, this means your code tries to call None as a function.

Body:
I have been reading about this error and I understand that it is because I expect a function to return a result but in reality it is not, I have reviewed my code and I do not find that it could be wrong

class Estudiante:
   def __init__(self):
      self.nombre = ""
      self.cedula = 0
      self.apellido = ""
      self.asignatura = ""
      self.cantidadDeNotas = 0
      self.notas = []

   @property
      def obtenerDatos(self):
         print("ingrese los datos del estudiante")
         self.cedula = int(input("Cedula del estudiante: "))
         self.nombre = input("Nombre del estudiante: ")
         self.apellido = input("Apellido del estudiante: ")
         self.asignatura = input("Asignatura: ")
         while True:
            self.cantidadDeNotas = int(input("¿cual es la cantidad de notas que desea ingresar?(más de 4): "))
            if self.cantidadDeNotas > 4:
                break
            else:
                print("ingrese una cantidad mayor a 4")

estudiante = Estudiante()
estudiante.obtenerDatos()


问:
How to close dropdown menu when user clicks outside of it on mobile screen size
I am having alot of trouble trying to fix this issue with this HTML template Click Here . Please scroll to the 1st template Demo under Shop Pages as shown in the image below.

(Please resize your browser to a mobile screen size)

When the user opens the mobile dropdown menu on the left, he should be able to close it by clicking outside of the menu, like by clicking anywhere else on the body of the page. Currently this only closes when the user clicks on the hamburger icon.

Also, currently if the user has the menu open and then he clicks on the body of the page and then goes back to click the hamburger icon because clicking the page did not work, the page freezes up and you are unable to scroll unless you tap the screen a bunch of times because that vertical scroll bar comes in and it has the focus I guess (creating a bad experience for mobile users).

I have tried to fix this with the following code I wrote, but once the menu slides back up it never comes back down as if it was deleted from the page:

```<code><script>
$(document).on("click", function (event) {
    var $trigger = $(".mobile-menu.hamburger-icon");
    if ($trigger !== event.target && !$trigger.has(event.target).length){
        //THIS IS WHAT WORKS BUT YOU HAVE TO CLICK OUTSIDE LIKE TWICE FOR IT TO COME BACK
        $(".mobile-navigation.dl-menuwrapper").slideUp("fast");
    }
});
</script>
</code>```

I have also tried to add this piece of code to the page as well so that the menu can reappear if the user clicks on the hamburger icon again but it makes the page buggy because the menu will only come down once and then disappear again if you click on the body again while trying to close it.

```<code><script>
$(document).on("click", function (event) {
    var $trigger = $(".mobile-menu.hamburger-icon");
    if ($trigger !== event.target && !$trigger.has(event.target).length){
        //THIS IS WHAT WORKS BUT YOU HAVE TO CLICK OUTSIDE LIKE TWICE FOR IT TO COME BACK
        $(".mobile-navigation.dl-menuwrapper").slideUp("fast");
    }
});
</script>

<script>
    $(".mobile-menu.hamburger-icon").on("click", function (event) {
        $(".mobile-navigation.dl-menuwrapper").slideDown("fast");
    });
</script>
</code>```

How can I get this to work the way I need it to ?
Thank you!

答:
I was able to somewhat fix this by adding some custom classes to the div for the icon button and by writing this snippet of code which seemed to do the trick for me.</p>
```<code><script>
$(document).on("click", function (event) {
    var $BMI = $(".mobile-menu.hamburger-icon");
    var $VMM = $(".dl-menu.dl-menuopen");

    if ($BMI !== event.target && !$BMI.has(event.target).length && ($VMM.is(":hidden"))) {

        $(".mobile-navigation.dl-menuwrapper.open-mobile-menu").addClass('open-mobile-menu');

        $(".dl-menu.dl-menuopen").addClass('dl-menuopen');
    }

 </script>
</code>```

Body:
I am having alot of trouble trying to fix this issue with this HTML template Click Here . Please scroll to the 1st template Demo under Shop Pages as shown in the image below.

(Please resize your browser to a mobile screen size)

When the user opens the mobile dropdown menu on the left, he should be able to close it by clicking outside of the menu, like by clicking anywhere else on the body of the page. Currently this only closes when the user clicks on the hamburger icon.

Also, currently if the user has the menu open and then he clicks on the body of the page and then goes back to click the hamburger icon because clicking the page did not work, the page freezes up and you are unable to scroll unless you tap the screen a bunch of times because that vertical scroll bar comes in and it has the focus I guess (creating a bad experience for mobile users).

I have tried to fix this with the following code I wrote, but once the menu slides back up it never comes back down as if it was deleted from the page:

I have also tried to add this piece of code to the page as well so that the menu can reappear if the user clicks on the hamburger icon again but it makes the page buggy because the menu will only come down once and then disappear again if you click on the body again while trying to close it.

How can I get this to work the way I need it to ?
Thank you!

Body:
I was able to somewhat fix this by adding some custom classes to the div for the icon button and by writing this snippet of code which seemed to do the trick for me.

<script>
$(document).on("click", function (event) {
    var $BMI = $(".mobile-menu.hamburger-icon");
    var $VMM = $(".dl-menu.dl-menuopen");

    if ($BMI !== event.target && !$BMI.has(event.target).length && ($VMM.is(":hidden"))) {

        $(".mobile-navigation.dl-menuwrapper.open-mobile-menu").addClass('open-mobile-menu');

        $(".dl-menu.dl-menuopen").addClass('dl-menuopen');
    }

 </script>