问:
When I request a request, it returns 401 unauthorized for each request in the security section
I am making a project for Register and Login operations. I am using spring security and jwt. It always returns 401 unauthorized to any request I throw in Postman. I couldn't find the reason. Could you help? I am using spring boot new version. 3.0.0 version.

```<code>@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeHttpRequests()
            .requestMatchers("/auth/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthenticationController {

  private final AuthenticationService service;

  @PostMapping("/register")
  public ResponseEntity<AuthenticationResponse> register(
      @RequestBody RegisterRequest request
  ) {
    return ResponseEntity.ok(service.register(request));
  }
  @PostMapping("/authenticate")
  public ResponseEntity<AuthenticationResponse> authenticate(
      @RequestBody AuthenticationRequest request
  ) {
    return ResponseEntity.ok(service.authenticate(request));
  }
}

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

  private final JwtService jwtService;
  private final UserDetailsService userDetailsService;

  @Override
  protected void doFilterInternal(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull FilterChain filterChain
  ) throws ServletException, IOException {
    final String authHeader = request.getHeader("Authorization");
    final String jwt;
    final String userEmail;
    if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
      filterChain.doFilter(request, response);
      return;
    }
    jwt = authHeader.substring(7);
    userEmail = jwtService.extractUsername(jwt);
    if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
      if (jwtService.isTokenValid(jwt, userDetails)) {
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
            userDetails,
            null,
            userDetails.getAuthorities()
        );
        authToken.setDetails(
            new WebAuthenticationDetailsSource().buildDetails(request)
        );
        SecurityContextHolder.getContext().setAuthentication(authToken);
      }
    }
    filterChain.doFilter(request, response);
  }
}

@Configuration
@RequiredArgsConstructor
public class ApplicationConfig {

  private final CustomerRepository repository;

  @Bean
  public UserDetailsService userDetailsService() {
    return username -> repository.findByEmail(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found"));
  }

  @Bean
  public AuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
    return authProvider;
  }

  @Bean
  public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
  }

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

}
</code>```

I want to register and then login. I want to access some controllers based on role.

Body:
I am making a project for Register and Login operations. I am using spring security and jwt. It always returns 401 unauthorized to any request I throw in Postman. I couldn't find the reason. Could you help? I am using spring boot new version. 3.0.0 version.

@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeHttpRequests()
            .requestMatchers("/auth/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthenticationController {

  private final AuthenticationService service;

  @PostMapping("/register")
  public ResponseEntity<AuthenticationResponse> register(
      @RequestBody RegisterRequest request
  ) {
    return ResponseEntity.ok(service.register(request));
  }
  @PostMapping("/authenticate")
  public ResponseEntity<AuthenticationResponse> authenticate(
      @RequestBody AuthenticationRequest request
  ) {
    return ResponseEntity.ok(service.authenticate(request));
  }
}

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

  private final JwtService jwtService;
  private final UserDetailsService userDetailsService;

  @Override
  protected void doFilterInternal(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull FilterChain filterChain
  ) throws ServletException, IOException {
    final String authHeader = request.getHeader("Authorization");
    final String jwt;
    final String userEmail;
    if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
      filterChain.doFilter(request, response);
      return;
    }
    jwt = authHeader.substring(7);
    userEmail = jwtService.extractUsername(jwt);
    if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
      if (jwtService.isTokenValid(jwt, userDetails)) {
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
            userDetails,
            null,
            userDetails.getAuthorities()
        );
        authToken.setDetails(
            new WebAuthenticationDetailsSource().buildDetails(request)
        );
        SecurityContextHolder.getContext().setAuthentication(authToken);
      }
    }
    filterChain.doFilter(request, response);
  }
}

@Configuration
@RequiredArgsConstructor
public class ApplicationConfig {

  private final CustomerRepository repository;

  @Bean
  public UserDetailsService userDetailsService() {
    return username -> repository.findByEmail(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found"));
  }

  @Bean
  public AuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(passwordEncoder());
    return authProvider;
  }

  @Bean
  public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
  }

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

}

I want to register and then login. I want to access some controllers based on role.


来源: stackexchange

问:
Why data field in FCM Data API is empty?
There is some troubles with pushes delivery, so recently we decided to gather FCM Aggregated Delivery Data according to this post  and see insights.

1 - I followed steps described in BigQuery data export and linked project to BigQuery

2 - Then configured android project export to Enable message delivery data export

```<code>...
FirebaseApp.initializeApp(context)
FirebaseMessaging.getInstance().setDeliveryMetricsExportToBigQuery(true)
...
</code>```

Android project uses in app-module level build.gradle

```<code>implementation platform('com.google.firebase:firebase-bom:30.0.0')
implementation 'com.google.firebase:firebase-messaging-ktx'
implementation 'com.google.firebase:firebase-analytics-ktx'
</code>```

After configuring project it started to collect data in BigQuery without analytics_label. However the query to view aggregated push delivery data were returning empty data field:

```<code>{
  "androidDeliveryData": [
    ...,
    {
      "appId": "...",
      "date": {
        "year": 2022,
        "month": 12,
        "day": 25
      },
      "data": {}
    }
  ]
}
</code>```

Our backend were using legacy API to send data notifications. And we diceded to add analytics_label to sending push notification from backend, they said that this field is in new Firebase API v1. Backend team succesfully migrated to firebase-api-v1 from legacy. And BigQuery were populated with analytics labeled data. According to limitaions of API it can take yp to 5 days to be able to see aggregated data. It's been 9 days and I still getting empty data fields.

How can I achive getting aggregated pushes delivery data?

ContentLicense: CC BY-SA 4.0

Body:
There is some troubles with pushes delivery, so recently we decided to gather FCM Aggregated Delivery Data according to this post  and see insights.

1 - I followed steps described in BigQuery data export and linked project to BigQuery

2 - Then configured android project export to Enable message delivery data export

...
FirebaseApp.initializeApp(context)
FirebaseMessaging.getInstance().setDeliveryMetricsExportToBigQuery(true)
...

Android project uses in app-module level build.gradle

implementation platform('com.google.firebase:firebase-bom:30.0.0')
implementation 'com.google.firebase:firebase-messaging-ktx'
implementation 'com.google.firebase:firebase-analytics-ktx'

After configuring project it started to collect data in BigQuery without analytics_label. However the query to view aggregated push delivery data were returning empty data field:

{
  "androidDeliveryData": [
    ...,
    {
      "appId": "...",
      "date": {
        "year": 2022,
        "month": 12,
        "day": 25
      },
      "data": {}
    }
  ]
}

Our backend were using legacy API to send data notifications. And we diceded to add analytics_label to sending push notification from backend, they said that this field is in new Firebase API v1. Backend team succesfully migrated to firebase-api-v1 from legacy. And BigQuery were populated with analytics labeled data. According to limitaions of API it can take yp to 5 days to be able to see aggregated data. It's been 9 days and I still getting empty data fields.

How can I achive getting aggregated pushes delivery data?


问:
How access a prop from layout in next js pages
I have this layout component , I am trying to pass a prop from layout to its children.

```<code> const Layout = ({ children }: Props) => {
  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState(countries[0]);
  console.log("The country idsz ...........",selected.id)
  const country= selected.id

  const modifiedChildren = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
       //@ts-ignore
      return React.cloneElement(child, { testProp : country });
    }
    return child;
  });

  return (
    <>
     <LayoutContent sidebar={open} countriesWithsrc ={countriesWithsrc}  selected={selected} lected={setSelected} >
      {modifiedChildren}
     </LayoutContent>
    </>
  )
}
</code>```

export default Layout;

How can I access the modifiedChildren  in pages? An example is the following page.

```<code>    const ComingSoonCarbon = () => {
      return (
        <Layout>
        <div className="flex justify-center font-bold mt-80 text-xl text-[rgb(245,132,38,0.93)]">
          <h1>Development ongoing.Coming soon @2022</h1>
          </div>
        </Layout>
      )
    }

export default ComingSoonCarbon
</code>```

Body:
I have this layout component , I am trying to pass a prop from layout to its children.

 const Layout = ({ children }: Props) => {
  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState(countries[0]);
  console.log("The country idsz ...........",selected.id)
  const country= selected.id

  const modifiedChildren = React.Children.map(children, child => {
    if (React.isValidElement(child)) {
       //@ts-ignore
      return React.cloneElement(child, { testProp : country });
    }
    return child;
  });

  return (
    <>
     <LayoutContent sidebar={open} countriesWithsrc ={countriesWithsrc}  selected={selected} lected={setSelected} >
      {modifiedChildren}
     </LayoutContent>
    </>
  )
}

export default Layout;

How can I access the modifiedChildren  in pages? An example is the following page.

    const ComingSoonCarbon = () => {
      return (
        <Layout>

Development ongoing.Coming soon @2022

        </Layout>
      )
    }

export default ComingSoonCarbon


问:
How to host Flutter Webapp on a subfolder?
I'm trying to host a webApp inside a subfolder of my host. I uploaded all the contents of the build/web folder, but in the console I get the error:

how can i set url of my subfolder?

```<code>{
"name": "pagamento",
"short_name": "pagamento",
"start_url": "./pagamenti",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
    {
        "src": "icons/Icon-192.png",
        "sizes": "192x192",
        "type": "image/png"
    },
    {
        "src": "icons/Icon-512.png",
        "sizes": "512x512",
        "type": "image/png"
    },
    {
        "src": "icons/Icon-maskable-192.png",
        "sizes": "192x192",
        "type": "image/png",
        "purpose": "maskable"
    },
    {
        "src": "icons/Icon-maskable-512.png",
        "sizes": "512x512",
        "type": "image/png",
        "purpose": "maskable"
    }
]
</code>```

}

but it did not work

thank you and happy 2023 to all.

Body:
I'm trying to host a webApp inside a subfolder of my host. I uploaded all the contents of the build/web folder, but in the console I get the error:

how can i set url of my subfolder?

{
"name": "pagamento",
"short_name": "pagamento",
"start_url": "./pagamenti",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
    {
        "src": "icons/Icon-192.png",
        "sizes": "192x192",
        "type": "image/png"
    },
    {
        "src": "icons/Icon-512.png",
        "sizes": "512x512",
        "type": "image/png"
    },
    {
        "src": "icons/Icon-maskable-192.png",
        "sizes": "192x192",
        "type": "image/png",
        "purpose": "maskable"
    },
    {
        "src": "icons/Icon-maskable-512.png",
        "sizes": "512x512",
        "type": "image/png",
        "purpose": "maskable"
    }
]

}

but it did not work

thank you and happy 2023 to all.


问:
Node.js is stuck after "npm run dev"
I installed the latest react and next.js versions.
after building a new project with npx create-next-app,
the first thing that I do inside the vs code is "npm run dev"
and I get the warning: warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload

Now I didn't write a single line of code and the terminal is stuck.
I tried re-installing react,next.js, I tried to re-build the package and I do not understand what is the problem.

Will be helpful if you guys can help.
Thanks.

edit:

the full console output after me running npm run dev:

```<code>ready - started server on 0.0.0.0:3000, url: http://localhost:3000

event - compiled client and server successfully in 498 ms (166 modules)

wait  - compiling /_error (client and server)...

event - compiled client and server successfully in 85 ms (167 modules)

warn  - Fast Refresh had to perform a full reload. Read more:
https://nextjs.org/docs/messages/fast-refresh-reload

wait  - compiling / (client and server)...

event - compiled client and server successfully in 140 ms (170 modules)

warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload
</code>```

And then it stucks so I do ctrl+c to terminate the process.

I am using react version: 18.2.0
and next.js version: 13.1.1

Title: Node.js is stuck after "npm run dev"

Body:
I installed the latest react and next.js versions.
after building a new project with npx create-next-app,
the first thing that I do inside the vs code is "npm run dev"
and I get the warning: warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload

Now I didn't write a single line of code and the terminal is stuck.
I tried re-installing react,next.js, I tried to re-build the package and I do not understand what is the problem.

Will be helpful if you guys can help.
Thanks.

edit:

the full console output after me running npm run dev:

ready - started server on 0.0.0.0:3000, url: http://localhost:3000

event - compiled client and server successfully in 498 ms (166 modules)

wait  - compiling /_error (client and server)...

event - compiled client and server successfully in 85 ms (167 modules)

warn  - Fast Refresh had to perform a full reload. Read more:
https://nextjs.org/docs/messages/fast-refresh-reload

wait  - compiling / (client and server)...

event - compiled client and server successfully in 140 ms (170 modules)

warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload

And then it stucks so I do ctrl+c to terminate the process.

I am using react version: 18.2.0
and next.js version: 13.1.1


问:
How to convert a distance matrix to a pairwise comparison in Python?
I have a distance matrix and want to convert it to a pairwise comparison.

The distance matrix:

Distance matrix
AWGS13092760-1_S21.ffn
AWGS13092803-1_S22.ffn
AWGS13093729-1_S5.ffn

AWGS13092760-1_S21.ffn
0
196
188

AWGS13092803-1_S22.ffn
196
0
131

AWGS13093729-1_S5.ffn
188
131
0

AWGS13094209-2_S10.ffn
1377
1359
1330

I expect my output to be like this:

FIELD1
query
reference
cgMLST_chewBBACCA_Difference

0
AWGS13092803-1_S22
AWGS13092803-1_S22
196

1
AWGS13093729-1_S5
AWGS13092803-1_S22
188

2
AWGS13094209-2_S10
AWGS13092803-1_S22
1377

Now, I managed to get my desired result, but I was wondering if there is a better way to do it instead of using nested for loops?

The code I used:

```<code># read input and add query, reference and distances
    df = pd.read_excel(file)
    list_dist = []
    list_query = []
    list_ref = []
    col = df.columns

    for x in range(1, (len(col))):  # iterate every column, column index = x
        d = df[df.columns[x]][x:]
        com = df[df.columns[0]][x:]
        for item in com:  # appends all query sample IDs to a list
            list_query.append(item)
        for it in d:  # appends all distances to a list
            list_dist.append(it)
        for f in range(x, (len(col) - 1)):  # appends all reference sample IDs to a list
            reference = df.columns[x]
            list_ref.append(reference)

    df_pws_comp = pd.DataFrame()
    df_pws_comp["query"] = list_query  # list with query IDs
    df_pws_comp["reference"] = list_ref  # list with reference IDs
    df_pws_comp["cgMLST_chewBBACA_Difference"] = list_dist
</code>```

Thank you in advance!

Body:
I have a distance matrix and want to convert it to a pairwise comparison.

The distance matrix:

Distance matrix
AWGS13092760-1_S21.ffn
AWGS13092803-1_S22.ffn
AWGS13093729-1_S5.ffn

AWGS13092760-1_S21.ffn
0
196
188

AWGS13092803-1_S22.ffn
196
0
131

AWGS13093729-1_S5.ffn
188
131
0

AWGS13094209-2_S10.ffn
1377
1359
1330

I expect my output to be like this:

FIELD1
query
reference
cgMLST_chewBBACCA_Difference

0
AWGS13092803-1_S22
AWGS13092803-1_S22
196

1
AWGS13093729-1_S5
AWGS13092803-1_S22
188

2
AWGS13094209-2_S10
AWGS13092803-1_S22
1377

Now, I managed to get my desired result, but I was wondering if there is a better way to do it instead of using nested for loops?

The code I used:

# read input and add query, reference and distances
    df = pd.read_excel(file)
    list_dist = []
    list_query = []
    list_ref = []
    col = df.columns

    for x in range(1, (len(col))):  # iterate every column, column index = x
        d = df[df.columns[x]][x:]
        com = df[df.columns[0]][x:]
        for item in com:  # appends all query sample IDs to a list
            list_query.append(item)
        for it in d:  # appends all distances to a list
            list_dist.append(it)
        for f in range(x, (len(col) - 1)):  # appends all reference sample IDs to a list
            reference = df.columns[x]
            list_ref.append(reference)

    df_pws_comp = pd.DataFrame()
    df_pws_comp["query"] = list_query  # list with query IDs
    df_pws_comp["reference"] = list_ref  # list with reference IDs
    df_pws_comp["cgMLST_chewBBACA_Difference"] = list_dist

Thank you in advance!


问:
Can we skip the pop operation for stack-navigation in react-navigation
I'm having an issue in case of preforming pop operation. Actually I wanted to perform the flow that when I navigates to a page and then can't be able to navigate back to the previous one.

I tried to pop the previous page but as it is a stack it's default behaviour is to pop the first element and then the next one, so is there any functionality that react-navigation provides to skip the pop operation for a particular page


问:
Sprockets::FileNotFound: couldn't find file 'tipso/src/tipso' with type 'application/javascript'
I am trying to deploy my app to Heroku and I keep getting stuck on this Sprockets error that a file cannot be found.  I don't understand why this is occurring.

```<code># assets.rb
Rails.application.config.assets.paths << Rails.root.join('node_modules')

# application.js.erb
//= require rails-ujs
//= require jquery3
//= require jquery_ujs
//#= require dataTables/jquery.dataTables
//#= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require popper
//= require bootstrap
//= require activestorage
//= require turbolinks
//= require plyr
//= require lodash
//= require jquery-readyselector
//= require toastr
//= require tipso    <-- throws error
</code>```

I don't understand the error because it's clearly in my node_modules folder.

I will say that Sprockets is searching a temporary build folder so maybe the package isn't ending up there?:

```<code>remote:        Sprockets::FileNotFound: couldn't find file 'tipso' with type 'application/javascript'
remote:        Checked in these paths:
remote:          /tmp/build_38841618/app/assets/config
remote:          /tmp/build_38841618/app/assets/fonts
remote:          /tmp/build_38841618/app/assets/images
remote:          /tmp/build_38841618/app/assets/javascripts
remote:          /tmp/build_38841618/app/assets/stylesheets
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/ahoy_matey-4.0.3/vendor/assets/javascripts
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/jquery_mask_rails-0.1.0/vendor/assets/javascripts
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/bootstrap-tour-rails-0.4.0/vendor/assets/javascripts
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/bootstrap-tour-rails-0.4.0/vendor/assets/stylesheets
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/jquery-ui-rails-6.0.1/app/assets/images
...
</code>```

What else can I do to get Sprockets to recognize this package?

Body:
I am trying to deploy my app to Heroku and I keep getting stuck on this Sprockets error that a file cannot be found.  I don't understand why this is occurring.

# assets.rb
Rails.application.config.assets.paths << Rails.root.join('node_modules')

# application.js.erb
//= require rails-ujs
//= require jquery3
//= require jquery_ujs
//#= require dataTables/jquery.dataTables
//#= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require popper
//= require bootstrap
//= require activestorage
//= require turbolinks
//= require plyr
//= require lodash
//= require jquery-readyselector
//= require toastr
//= require tipso    <-- throws error

I don't understand the error because it's clearly in my node_modules folder.

I will say that Sprockets is searching a temporary build folder so maybe the package isn't ending up there?:

remote:        Sprockets::FileNotFound: couldn't find file 'tipso' with type 'application/javascript'
remote:        Checked in these paths:
remote:          /tmp/build_38841618/app/assets/config
remote:          /tmp/build_38841618/app/assets/fonts
remote:          /tmp/build_38841618/app/assets/images
remote:          /tmp/build_38841618/app/assets/javascripts
remote:          /tmp/build_38841618/app/assets/stylesheets
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/ahoy_matey-4.0.3/vendor/assets/javascripts
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/jquery_mask_rails-0.1.0/vendor/assets/javascripts
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/bootstrap-tour-rails-0.4.0/vendor/assets/javascripts
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/bootstrap-tour-rails-0.4.0/vendor/assets/stylesheets
remote:          /tmp/build_38841618/vendor/bundle/ruby/3.1.0/gems/jquery-ui-rails-6.0.1/app/assets/images
...

What else can I do to get Sprockets to recognize this package?


问:
convertapi gives issue while converting docx to pdf in IOS device
I am trying to convert docx file to pdf using convertapi. The language i am using is Python and also i am doing some jinja2 templating in docx file. Everything works well with Android and web app. But it give 500 Internal server error while using in IOS device.

```<code>convert_api_result = convertapi.convert('pdf',
                                                {'File': demo_file.name},
                                                from_format='docx')
</code>```

Error:
raise ReadTimeout(e, request=request)\nrequests.exceptions.ReadTimeout: HTTPSConnectionPool(host='v2.convertapi.com')

I don't know why is this happening. Any help would be appreciated.

Body:
I am trying to convert docx file to pdf using convertapi. The language i am using is Python and also i am doing some jinja2 templating in docx file. Everything works well with Android and web app. But it give 500 Internal server error while using in IOS device.

convert_api_result = convertapi.convert('pdf',
                                                {'File': demo_file.name},
                                                from_format='docx')

Error:
raise ReadTimeout(e, request=request)\nrequests.exceptions.ReadTimeout: HTTPSConnectionPool(host='v2.convertapi.com')

I don't know why is this happening. Any help would be appreciated.


问:
Getting error 400 on OpenAI image edit API
I have been testing OpenAI's Image Edit API for my project and keep getting the following error in console,

```<code>POST https://api.openai.com/v1/images/edits 400
(anonymous) @ script.js:8
</code>```

Here is my JS file code,

```<code>const form = new FormData();
form.append('image',  'maira.png');
form.append('mask', 'maira2.png');
form.append('prompt', 'A sunlit indoor lounge area with a pool containing a flamingo');
form.append('n', '1');
form.append('size', '1024x1024');

fetch('https://api.openai.com/v1/images/edits', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer *myAPIKey*'
    },
    body: form
});
</code>```

I am expecting a JSON object in response but getting the error instead.

Body:
I have been testing OpenAI's Image Edit API for my project and keep getting the following error in console,

POST https://api.openai.com/v1/images/edits 400
(anonymous) @ script.js:8

Here is my JS file code,

const form = new FormData();
form.append('image',  'maira.png');
form.append('mask', 'maira2.png');
form.append('prompt', 'A sunlit indoor lounge area with a pool containing a flamingo');
form.append('n', '1');
form.append('size', '1024x1024');

fetch('https://api.openai.com/v1/images/edits', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer *myAPIKey*'
    },
    body: form
});

I am expecting a JSON object in response but getting the error instead.


问:
java error connecting two devices with socket (public ip)
i'm almost a new java programmer (started at 5 month ago) and i want to connect two program over internet but i get some error that's i can't fix.

i've tried alot. i told to my friend to ping my public ip in cmd and he did and it worked fine. with that the java client did'nt work either.

after that, I looked for another answer on stackoverflow, then i found a comment that said you have to do port forwarding . i did port forwarding and it still gives an error.

Client

```<code>import java.io.*;
import java.net.*;

public class Client{
    public static void main(String[] args) throws IOException{

        Socket s = new Socket("151.245.38.21",113);

          while (true){

          }
        }
    }
</code>```

SERVER

```<code>import java.io.*;
import java.net.*;

public class SERVER{
    public static void main(String[] args) throws IOException{

        ServerSocket ss = new ServerSocket(113); //the port that i used in port forwarding

        Socket s = ss.accept();

        System.out.println("Connected!");

    System.out.println(s);
    System.out.println(ss);

        while (true){

        }
    }
}
</code>```

error

```<code>Exception in thread "main" java.net.ConnectException: Connection timed out: connect
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:579)
    at java.base/sun.nio.ch.Net.connect(Net.java:568)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:585)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
    at java.base/java.net.Socket.connect(Socket.java:633)
    at java.base/java.net.Socket.connect(Socket.java:583)
    at java.base/java.net.Socket.<init>(Socket.java:507)
    at java.base/java.net.Socket.<init>(Socket.java:287)
    at Client.main(Client.java:7)
</code>```

Body:
i'm almost a new java programmer (started at 5 month ago) and i want to connect two program over internet but i get some error that's i can't fix.

i've tried alot. i told to my friend to ping my public ip in cmd and he did and it worked fine. with that the java client did'nt work either.

after that, I looked for another answer on stackoverflow, then i found a comment that said you have to do port forwarding . i did port forwarding and it still gives an error.

Client

import java.io.*;
import java.net.*;

public class Client{
    public static void main(String[] args) throws IOException{

        Socket s = new Socket("151.245.38.21",113);

          while (true){

          }
        }
    }

SERVER

import java.io.*;
import java.net.*;

public class SERVER{
    public static void main(String[] args) throws IOException{

        ServerSocket ss = new ServerSocket(113); //the port that i used in port forwarding

        Socket s = ss.accept();

        System.out.println("Connected!");

    System.out.println(s);
    System.out.println(ss);

        while (true){

        }
    }
}

error

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:579)
    at java.base/sun.nio.ch.Net.connect(Net.java:568)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:585)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
    at java.base/java.net.Socket.connect(Socket.java:633)
    at java.base/java.net.Socket.connect(Socket.java:583)
    at java.base/java.net.Socket.<init>(Socket.java:507)
    at java.base/java.net.Socket.<init>(Socket.java:287)
    at Client.main(Client.java:7)


问:
Problem with softPageBreaks when reading a odf file with lxml to create a LaTeX file
I have a Google Doc that I want to convert into a LaTeX file while stripping out some content of the Google Doc. Specifically I want to remove all headlines in the Google Doc. I also currently have four-line paragraphs in the Google Doc where each line ends with a newline character. This means that in Google Doc they aren't seen as one paragraph but four and I want those to be one in my LaTeX file.

First I extracted an XML file and parsed it:

```<code>if not os.path.exists(tempFolder):
    os.makedirs(tempFolder)

# Extract the contents of the ODF file to the "temp" folder
with zipfile.ZipFile(fileName, "r") as zip:
    zip.extractall(path=tempFolder)

# Open the "content.xml" file inside the "temp" folder and parse it into an XML tree
doc = etree.parse(contentXml)
removeHeadlines(doc)
</code>```

I remove the headlines via:

```<code>def removeHeadlines(doc):

    p2 = doc.findall('.//text:p[@text:style-name="P2"]', namespaces=doc.getroot().nsmap)

    for p in ( p2 ):
        p.getparent().remove(p)
</code>```

Then I create the LaTeX file via:

```<code>elementList = oldDoc.findall(
    './/text:p[@text:style-name="Standard"]',
    namespaces=oldDoc.getroot().nsmap)
textList = [element.text for element in elementList]

latexDoc = pylatex.Document()

section = pylatex.section.Section(fileName)
latexDoc.append(section)

paragraph = pylatex.section.Paragraph('')
paragraphIsNew = True

for string in textList:
    if string:
        # If the string is not empty, add it to the paragraph
        paragraph.append(string + "\n")
        paragraphIsNew = False
    else:
        if not paragraphIsNew:
            latexDoc.append(paragraph)
            paragraph = pylatex.section.Paragraph('')
            paragraphIsNew = True

latexDoc.append(paragraph)

latexDoc.generate_pdf(newFileName)
</code>```

Unfortunately, some lines don't make it into the LaTeX pdf. Those look like:

```<code><text:p text:style-name="Standard"><text:soft-page-break/>Sad line that doesn't make it,</text:p>
</code>```

I tried unsuccessfully tried to remove the softPageBreak elements by doing:

```<code>softPageBreaks = doc.findall('.//text:soft-page-break', namespaces=doc.getroot().nsmap)

# Remove the element, but keep its parent and the text content
for element in softPageBreaks:
    parent = element.getparent()
    text = element.tail
    parent.remove(element)
    parent.text = text
</code>```

Body:
I have a Google Doc that I want to convert into a LaTeX file while stripping out some content of the Google Doc. Specifically I want to remove all headlines in the Google Doc. I also currently have four-line paragraphs in the Google Doc where each line ends with a newline character. This means that in Google Doc they aren't seen as one paragraph but four and I want those to be one in my LaTeX file.

First I extracted an XML file and parsed it:

if not os.path.exists(tempFolder):
    os.makedirs(tempFolder)

# Extract the contents of the ODF file to the "temp" folder
with zipfile.ZipFile(fileName, "r") as zip:
    zip.extractall(path=tempFolder)

# Open the "content.xml" file inside the "temp" folder and parse it into an XML tree
doc = etree.parse(contentXml)
removeHeadlines(doc)

I remove the headlines via:

def removeHeadlines(doc):

    p2 = doc.findall('.//text:p[@text:style-name="P2"]', namespaces=doc.getroot().nsmap)

    for p in ( p2 ):
        p.getparent().remove(p)

Then I create the LaTeX file via:

elementList = oldDoc.findall(
    './/text:p[@text:style-name="Standard"]',
    namespaces=oldDoc.getroot().nsmap)
textList = [element.text for element in elementList]

latexDoc = pylatex.Document()

section = pylatex.section.Section(fileName)
latexDoc.append(section)

paragraph = pylatex.section.Paragraph('')
paragraphIsNew = True

for string in textList:
    if string:
        # If the string is not empty, add it to the paragraph
        paragraph.append(string + "\n")
        paragraphIsNew = False
    else:
        if not paragraphIsNew:
            latexDoc.append(paragraph)
            paragraph = pylatex.section.Paragraph('')
            paragraphIsNew = True

latexDoc.append(paragraph)

latexDoc.generate_pdf(newFileName)

Unfortunately, some lines don't make it into the LaTeX pdf. Those look like:

<text:p text:style-name="Standard"><text:soft-page-break/>Sad line that doesn't make it,</text:p>

I tried unsuccessfully tried to remove the softPageBreak elements by doing:

softPageBreaks = doc.findall('.//text:soft-page-break', namespaces=doc.getroot().nsmap)

# Remove the element, but keep its parent and the text content
for element in softPageBreaks:
    parent = element.getparent()
    text = element.tail
    parent.remove(element)
    parent.text = text


问:
NEXTJS 13: router options props
In the old router (page router) there was the option as that was used to mask the url, in the new app router this option is not present. I need that and I'm stuck in there.
Anyone have found a solution or I need to switch back to the page folder?

I've a post list that when you click it open a modal in the current url, but I need to change the url so that if you refresh the page you go to the post page.

Example:

if you go to this url and you click on a post a modal will be opened but the url also change and if you refresh you will go to the post page.

Title: NEXTJS 13: router options props


问:
ERROR : Cannot find module './TransactionCard' or its corresponding type declarations
```<code>export { default } from "./TransactionCard";
</code>```

while exporting from a tsx file getting this error.

I was trying to export a component as default from index.tsx file.

Body:
export { default } from "./TransactionCard";

while exporting from a tsx file getting this error.

I was trying to export a component as default from index.tsx file.


问:
How to avoid the MinAreaRec plot for the whole canvas of window?
So, I am trying to measure the line (check the attached code and result), the problem is when creating the boxplot points to measure the line it also creating boxplot points of the whole canvas of window no matter the image or thresholding value is. I also tried to limit in contourarea(c) command but couldn't limit it (don't know why). Kindly improvise the code or explain where I can counter this problem of mine in layman language as I am a newbee.
Thankyou!

```<code>import cv2
import numpy as np
import imutils
import imutils.perspective as persp
import scipy.spatial.distance as dist

print("PRESSED MODE 1 CONTOUR")
# cv2.destroyAllWindows()
img = cv2.imread('opencv_frame_3.png')
# img2 = cv2.imread('shapes.jpg')
# rgb_img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
rgb_img = cv2.cvtColor(gray, cv2.COLOR_BGR2RGB)

# thresh, thresh_img = cv2.threshold(gray,90,255,cv2.THRESH_BINARY)
# thresh_img = cv2.erode(thresh_img, None, iterations=5)
# thresh_img = cv2.dilate(thresh_img, None, iterations=1)
# rgb_img_thresh = cv2.cvtColor(thresh_img, cv2.COLOR_BGR2RGB)

thresh_img = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,17,5)
# thresh_img = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,175,15)
# thr = cv2.cvtColor(thr, cv2.COLOR_BGR2RGB)

conts = cv2.findContours(thresh_img, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

conts = imutils.grab_contours(conts)
# print(len(conts))

cont_img = np.zeros(img.shape)
cont_img = cv2.drawContours(cont_img,conts, -1 , (0,255,0),1)
cont_img2 = np.copy(img)
cont_img2 = cv2.drawContours(cont_img2,conts, -1 , (0,255,0),1)

# cv2.imshow('black',cont_img)

def midPoint (ptA, ptB):
    return ((ptA[0]+ptB[0])/2 , (ptA[1]+ptB[1])/2)

for c in conts:
    box =  cv2.minAreaRect(c)
    # print(box)
    box = cv2.boxPoints(box)
    box = np.array(box, dtype='int')
    area = cv2.contourArea(c)
    # print(area)

    if cv2.contourArea(c) < 50000:
        continue
    area = cv2.contourArea(c)
    print(area/96)
    print("________")
    cv2.drawContours(cont_img,[c],-1,(0,0,255),2)
    cv2.drawContours(cont_img, [box], -1, (255, 0, 0), 2)
    cv2.drawContours(cont_img2,[c],-1,(0,0,255),2)
    cv2.drawContours(cont_img2, [box], -1, (255, 0, 0), 2)

    for (x,y)  in box:
         cv2.circle(cont_img,(x,y),2,(255,255,255),20)
         cv2.circle(cont_img2, (x, y), 2, (255, 255, 255), 20)
         (tl,tr,br,bl) = box

         (trX,tlX) = midPoint(tr,tl)
         (brX, blX) = midPoint(br, bl)

         cv2.circle(cont_img, (int(trX), int(tlX)),1, (0, 255, 255), 20)
         cv2.circle(cont_img, (int(brX), int(blX)),1, (0, 255, 255), 20)
         cv2.line(cont_img, (int(trX), int(tlX)), (int(brX), int(blX)), (255,0,255), 2)

         cv2.circle(cont_img2, (int(trX), int(tlX)), 1, (0, 255, 255), 20)
         cv2.circle(cont_img2, (int(brX), int(blX)), 1, (0, 255, 255), 20)
         cv2.line(cont_img2, (int(trX), int(tlX)), (int(brX), int(blX)), (255, 0, 255), 2)

         dA = dist.euclidean((int(trX), int(tlX)), (int(brX), int(blX)))
         cv2.putText(cont_img,"{:.2f} px".format(dA/300), (int(trX+20), int(blX-20)),
                     cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,255),2)

         cv2.putText(cont_img2,"{:.2f} px".format(dA/300), (int(trX+20), int(blX-20)),
                     cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,255),2)

         (tlX, blX) = midPoint(tl, bl)
         (trX, brX) = midPoint(tr, br)

         cv2.circle(cont_img, (int(tlX), int(blX)),1, (0, 255, 0), 20)
         cv2.circle(cont_img, (int(trX), int(brX)),1, (0, 255, 0), 20)
         cv2.line(cont_img, (int(tlX), int(blX)), (int(trX), int(brX)), (255,0,255), 2)

         cv2.circle(cont_img2, (int(tlX), int(blX)),1, (0, 255, 0), 20)
         cv2.circle(cont_img2, (int(trX), int(brX)),1, (0, 255, 0), 20)
         cv2.line(cont_img2, (int(tlX), int(blX)), (int(trX), int(brX)), (255,0,255), 2)

         dB = dist.euclidean((int(tlX), int(blX)), (int(trX), int(brX)))
         cv2.putText(cont_img,"{:.2f} in".format(dB/300), (int(trX-120), int(blX-320)),
                     cv2.FONT_HERSHEY_SIMPLEX,0.7,(0, 255, 255),2)
         cv2.putText(cont_img2, "{:.2f} in".format(dB/300), (int(trX-120), int(blX -320)),
                cv2.FONT_HERSHEY_SIMPLEX,0.7, (0, 255, 255),2)

    print("Line A", "{:.2f} in".format(dA/96))
    print("Line B", "{:.2f} in".format(dB/96))
    print("**************")
# cont_img = cv2.resize(cont_img,(0,0),fx=0.5,fy=0.5)
cv2.imshow('area',cont_img)
# cont_img2 = cv2.resize(cont_img2,(0,0),fx=0.5,fy=0.5)
# cv2.imshow('ORG',cont_img2)
# thresh_img = cv2.resize(thresh_img,(0,0),fx=0.5,fy=0.5)
cv2.imshow("thresh", thresh_img)

# imgStack = stackImages(0.4,([img,rgb_img],
#                             [rgb_img_thresh,cont_img]))
#
# cv2.imshow('imgthresh',imgStack)

cv2.waitKey(0)

cv2.destroyAllWindows()
</code>```

Check the image of output the whole window size is getting measured
I tried to either limit the measurement or area of contourarea(c) or c itself but it doesn't work for me

Body:
So, I am trying to measure the line (check the attached code and result), the problem is when creating the boxplot points to measure the line it also creating boxplot points of the whole canvas of window no matter the image or thresholding value is. I also tried to limit in contourarea(c) command but couldn't limit it (don't know why). Kindly improvise the code or explain where I can counter this problem of mine in layman language as I am a newbee.
Thankyou!

import cv2
import numpy as np
import imutils
import imutils.perspective as persp
import scipy.spatial.distance as dist

print("PRESSED MODE 1 CONTOUR")
# cv2.destroyAllWindows()
img = cv2.imread('opencv_frame_3.png')
# img2 = cv2.imread('shapes.jpg')
# rgb_img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
rgb_img = cv2.cvtColor(gray, cv2.COLOR_BGR2RGB)

# thresh, thresh_img = cv2.threshold(gray,90,255,cv2.THRESH_BINARY)
# thresh_img = cv2.erode(thresh_img, None, iterations=5)
# thresh_img = cv2.dilate(thresh_img, None, iterations=1)
# rgb_img_thresh = cv2.cvtColor(thresh_img, cv2.COLOR_BGR2RGB)

thresh_img = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,17,5)
# thresh_img = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,175,15)
# thr = cv2.cvtColor(thr, cv2.COLOR_BGR2RGB)

conts = cv2.findContours(thresh_img, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

conts = imutils.grab_contours(conts)
# print(len(conts))

cont_img = np.zeros(img.shape)
cont_img = cv2.drawContours(cont_img,conts, -1 , (0,255,0),1)
cont_img2 = np.copy(img)
cont_img2 = cv2.drawContours(cont_img2,conts, -1 , (0,255,0),1)

# cv2.imshow('black',cont_img)

def midPoint (ptA, ptB):
    return ((ptA[0]+ptB[0])/2 , (ptA[1]+ptB[1])/2)

for c in conts:
    box =  cv2.minAreaRect(c)
    # print(box)
    box = cv2.boxPoints(box)
    box = np.array(box, dtype='int')
    area = cv2.contourArea(c)
    # print(area)

    if cv2.contourArea(c) < 50000:
        continue
    area = cv2.contourArea(c)
    print(area/96)
    print("________")
    cv2.drawContours(cont_img,[c],-1,(0,0,255),2)
    cv2.drawContours(cont_img, [box], -1, (255, 0, 0), 2)
    cv2.drawContours(cont_img2,[c],-1,(0,0,255),2)
    cv2.drawContours(cont_img2, [box], -1, (255, 0, 0), 2)

    for (x,y)  in box:
         cv2.circle(cont_img,(x,y),2,(255,255,255),20)
         cv2.circle(cont_img2, (x, y), 2, (255, 255, 255), 20)
         (tl,tr,br,bl) = box

         (trX,tlX) = midPoint(tr,tl)
         (brX, blX) = midPoint(br, bl)

         cv2.circle(cont_img, (int(trX), int(tlX)),1, (0, 255, 255), 20)
         cv2.circle(cont_img, (int(brX), int(blX)),1, (0, 255, 255), 20)
         cv2.line(cont_img, (int(trX), int(tlX)), (int(brX), int(blX)), (255,0,255), 2)

         cv2.circle(cont_img2, (int(trX), int(tlX)), 1, (0, 255, 255), 20)
         cv2.circle(cont_img2, (int(brX), int(blX)), 1, (0, 255, 255), 20)
         cv2.line(cont_img2, (int(trX), int(tlX)), (int(brX), int(blX)), (255, 0, 255), 2)

         dA = dist.euclidean((int(trX), int(tlX)), (int(brX), int(blX)))
         cv2.putText(cont_img,"{:.2f} px".format(dA/300), (int(trX+20), int(blX-20)),
                     cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,255),2)

         cv2.putText(cont_img2,"{:.2f} px".format(dA/300), (int(trX+20), int(blX-20)),
                     cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,255,255),2)

         (tlX, blX) = midPoint(tl, bl)
         (trX, brX) = midPoint(tr, br)

         cv2.circle(cont_img, (int(tlX), int(blX)),1, (0, 255, 0), 20)
         cv2.circle(cont_img, (int(trX), int(brX)),1, (0, 255, 0), 20)
         cv2.line(cont_img, (int(tlX), int(blX)), (int(trX), int(brX)), (255,0,255), 2)

         cv2.circle(cont_img2, (int(tlX), int(blX)),1, (0, 255, 0), 20)
         cv2.circle(cont_img2, (int(trX), int(brX)),1, (0, 255, 0), 20)
         cv2.line(cont_img2, (int(tlX), int(blX)), (int(trX), int(brX)), (255,0,255), 2)

         dB = dist.euclidean((int(tlX), int(blX)), (int(trX), int(brX)))
         cv2.putText(cont_img,"{:.2f} in".format(dB/300), (int(trX-120), int(blX-320)),
                     cv2.FONT_HERSHEY_SIMPLEX,0.7,(0, 255, 255),2)
         cv2.putText(cont_img2, "{:.2f} in".format(dB/300), (int(trX-120), int(blX -320)),
                cv2.FONT_HERSHEY_SIMPLEX,0.7, (0, 255, 255),2)

    print("Line A", "{:.2f} in".format(dA/96))
    print("Line B", "{:.2f} in".format(dB/96))
    print("**************")
# cont_img = cv2.resize(cont_img,(0,0),fx=0.5,fy=0.5)
cv2.imshow('area',cont_img)
# cont_img2 = cv2.resize(cont_img2,(0,0),fx=0.5,fy=0.5)
# cv2.imshow('ORG',cont_img2)
# thresh_img = cv2.resize(thresh_img,(0,0),fx=0.5,fy=0.5)
cv2.imshow("thresh", thresh_img)

# imgStack = stackImages(0.4,([img,rgb_img],
#                             [rgb_img_thresh,cont_img]))
#
# cv2.imshow('imgthresh',imgStack)

cv2.waitKey(0)

cv2.destroyAllWindows()

Check the image of output the whole window size is getting measured
I tried to either limit the measurement or area of contourarea(c) or c itself but it doesn't work for me


问:
How to remove a word using CSS only
I'm trying to remove the word "Per Ticket" using CSS only.
I'm a bit of a novice when it comes to CSS but have managed to do quite a bit and the last hurdle is removing this word.
TIA
What I need removing

I've tried

.postid-65599 .woocommerce-price-amount per ticket {display:none;}

Title: How to remove a word using CSS only


问:
Pylab saved image, not as expected
I am trying to save plots from pyplot as .png using the following code:

```<code>import numpy as np
import os
from matplotlib import pyplot as pl

os.chdir("/WORKING/DIRECTORY")

array1 = np.random.rand(10, 3)
array2 = np.random.rand(50, 3)
array3 = np.random.rand(400, 3)

arrays = (array1, array2, array3)
dpi = 300
count = 1

for n in arrays:
    pl.imshow(n, cmap='Accent')
    pl.axis('off')
    pl.savefig(str(count) + ".png", bbox_inches='tight', pad_inches=0, dpi=dpi)
    count +=1
</code>```

Depending on the array size the results are not as expected. Array1 renders fine. Array2 renders ok, but the last column of values is cut off (a few pixel less wide than the first two columns). Array3 is completely distorted.

Increasing the resolution fixes the problem. I don't want to do that globally as most of my files don't require it. How can I detect the files that are rendered wrong? Pyplot does not return an error eg for array2 or array3. Attached image files for reference.

Any idea how to pick this up as an error or bin the files into a separate folder? Array 1, Array 2, Array3

Title: Pylab saved image, not as expected

Body:
I am trying to save plots from pyplot as .png using the following code:

import numpy as np
import os
from matplotlib import pyplot as pl

os.chdir("/WORKING/DIRECTORY")

array1 = np.random.rand(10, 3)
array2 = np.random.rand(50, 3)
array3 = np.random.rand(400, 3)

arrays = (array1, array2, array3)
dpi = 300
count = 1

for n in arrays:
    pl.imshow(n, cmap='Accent')
    pl.axis('off')
    pl.savefig(str(count) + ".png", bbox_inches='tight', pad_inches=0, dpi=dpi)
    count +=1

Depending on the array size the results are not as expected. Array1 renders fine. Array2 renders ok, but the last column of values is cut off (a few pixel less wide than the first two columns). Array3 is completely distorted.

Increasing the resolution fixes the problem. I don't want to do that globally as most of my files don't require it. How can I detect the files that are rendered wrong? Pyplot does not return an error eg for array2 or array3. Attached image files for reference.

Any idea how to pick this up as an error or bin the files into a separate folder? Array 1, Array 2, Array3


问:
Is there any disadvantage of inflating custom attribute classes?
I have some classes which inherit from the Attribute class. These Attributes (like [Table] and [Column] are used to mark classes and properties as database tables or database columns and let me generate a database schema at runtime. Right now they are not only used as "markers", they represent the schema itself. For example the Table class does not only inherit from Attribute but also contains a property where a list of columns of the table are stored.

```<code>public class Schema : Attribute
{
    public List<Table> Tables { get; set; } = new List<Table>();
}

public class Table : Attribute
{
    public string Name { get; set; }
    public List<Column> Columns { get; set; } = new List<Column>();
}

public class Column : Attribute
{
    public string Name { get; set; }
}

[Schema] public class Example
{
    [Table] public class Person
    {
        [Column] public static string Name { get; set; } => "name";
        [Column] public static string Adress { get; set; } => "adress";
    }
}

 public class Test
 {
    public static Schema GenerateSchema<T>()
    {
        var schemaAttribute = (typeof T).GetCustomAttribute<Schema>();

        if (schema == null)
        {
            return null;
        }

        foreach (var type in typeof(T).GetNestedTypes())
        {
            if (Attribute.IsDefined(type, typeof(Table)))
            {
                var tableAttribute = type.GetCustomAttribute<Table>();

                var properties = type.GetProperties();

                var columnAttributes = new List<Column>();

                foreach (var property in properties)
                {
                    var columnAttribute = property.GetCustomAttribute<Column>();

                    if (columnAttribute != null)
                    {
                        columnAttribute.Name = property.GetValue(null) as string;
                        columnAttributes.Add(columnAttribute);
                    }
                }

                tableAttribute.Columns = columnAttributes;

                schemaAttribute.tables.Add(tableAttribute);
            }

            return schemaAttribute;
        }
    }
}
</code>```

Is there any drawback in using the attribute classes to not only mark the classes and properties but also hold the informations like shown above? Or might it be a "better" idea to use seperate classes for the schema, tables and columns and only use the attribute classes as "markers"?

Body:
I have some classes which inherit from the Attribute class. These Attributes (like [Table] and [Column] are used to mark classes and properties as database tables or database columns and let me generate a database schema at runtime. Right now they are not only used as "markers", they represent the schema itself. For example the Table class does not only inherit from Attribute but also contains a property where a list of columns of the table are stored.

public class Schema : Attribute
{
    public List
 Tables { get; set; } = new List
();
}

public class Table : Attribute
{
    public string Name { get; set; }
    public List<Column> Columns { get; set; } = new List<Column>();
}

public class Column : Attribute
{
    public string Name { get; set; }
}

[Schema] public class Example
{
    [Table] public class Person
    {
        [Column] public static string Name { get; set; } => "name";
        [Column] public static string Adress { get; set; } => "adress";
    }
}

 public class Test
 {
    public static Schema GenerateSchema<T>()
    {
        var schemaAttribute = (typeof T).GetCustomAttribute<Schema>();

        if (schema == null)
        {
            return null;
        }

        foreach (var type in typeof(T).GetNestedTypes())
        {
            if (Attribute.IsDefined(type, typeof(Table)))
            {
                var tableAttribute = type.GetCustomAttribute
();

                var properties = type.GetProperties();

                var columnAttributes = new List<Column>();

                foreach (var property in properties)
                {
                    var columnAttribute = property.GetCustomAttribute<Column>();

                    if (columnAttribute != null)
                    {
                        columnAttribute.Name = property.GetValue(null) as string;
                        columnAttributes.Add(columnAttribute);
                    }
                }

                tableAttribute.Columns = columnAttributes;

                schemaAttribute.tables.Add(tableAttribute);
            }

            return schemaAttribute;
        }
    }
}

Is there any drawback in using the attribute classes to not only mark the classes and properties but also hold the informations like shown above? Or might it be a "better" idea to use seperate classes for the schema, tables and columns and only use the attribute classes as "markers"?


问:
Why can't I find AD security group using the AD User and Computers tool?
I created a security group in AD. Using the AD Users and Computers tool, I can see it when I browse for it at the OU path, but I cannot see it using the "Find" function. Why is that?

Result when I browse for the group.

Result when I do a "Find" for the group.


问:
How to use translate service in html of angular(prime ng library used)

I am having problem in traslating items selected in ([selectedItemsLabel]="'{0} items selected'") in html in angular

{{'home.A1'| translate}}" tried this [selectedItemsLabel]="'{0} {{'home.A1'| translate}}'" but not working


问:
Why do I get this error when hitting play?
the error is

NullReferenceException: Object reference not set to an instance of an object
MainScript.Start () (at Assets/Scripts/MainScript.cs:31)

The code causing that error is:

void Start()
    {
/*31*/  A1.text = Raspunsuri.instance.Q1[1];
    }
```
<p>and</p>
<pre class="lang-cs prettyprint-override"><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Raspunsuri : MonoBehaviour
{
    public static Raspunsuri instance;

    public List<string> Q1 = new List<string>() { "Am rugat o sută de români să completeze fraza: Sâmbătă mergem în vizită la cuscrii și știi că ei se bucură dacă le aducem și o sticlă de...", "Vin$36", "Șampanie$30", "Lichior$10", "Țuică$9", "Pălincă$6", "Coniac$5", "Ulei$2", "Suc$2" };
    public List<string> Q2 = new List<string>() { "Pe postul RA TV din Regatul Animalelor, ce vietate prezintă, in fiecare duminică „Viața Junglei”?", "Leul$27", "Maimuța$13", "Girafa$13", "Tigrul$8", "Zebra$7", "Elefantul$6", "Vulpe$6", "Ursul$6" };
    public List<string> Q3 = new List<string>() { "La ce eveniment te duci cu telefonul încărcat la maxim pentru că știi că o să faci multe poze?", "Nuntă$39", "Botez$20", "Petrecere$11", "Concert$9", "Aniversare$8", "Balul Bobocilior$5", "Serbare$5", "Revelion$3" };
    public List<string> Q4 = new List<string>() { "Ai o găleată cu mere. Ce faci cu ele?", "Compot$31", "Plăcintă$26", "Gem$14", "Suc$11", "Țuică$5", "Cidru$5", "Prăjitură$4", "Dulceață$4" };
    public List<string> Q5 = new List<string>() { "Pe lângă plopii fără soț, ce mai vezi în parc?", "Bancă$24", "Tei$11", "Stejar$10", "Brad$10", "Castan$10", "Flori$9", "Salcâm$6", "Iarbă$5" };
    public List<string> Q6 = new List<string>() { "Ce se împrăștie foarte ușor dar îți ia o grămadă să aduni la loc?", "Orez$22", "Zahăr$18", "Mărgelele$14", "Făină$13", "Sare$11", "Semințe$9", "Fasole$7", "Piper$6" };

    // Start is called before the first frame update

    private void Awake()
    {
        instance = this;
    }
    void Start()
    {
        Debug.Log(Q1[1]);

    }

    // Update is called once per frame
    void Update()
    {

    }
}
</code>```

When trying to Debug.Log Q1[1], nothing shows up in Unity, so the problem is probably there. Can anyone tell me how to fix it?

Body:
the error is

NullReferenceException: Object reference not set to an instance of an object
MainScript.Start () (at Assets/Scripts/MainScript.cs:31)

The code causing that error is:

void Start()
    {
/*31*/  A1.text = Raspunsuri.instance.Q1[1];
    }

and

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Raspunsuri : MonoBehaviour
{
    public static Raspunsuri instance;

    public List<string> Q1 = new List<string>() { "Am rugat o sută de români să completeze fraza: Sâmbătă mergem în vizită la cuscrii și știi că ei se bucură dacă le aducem și o sticlă de...", "Vin$36", "Șampanie$30", "Lichior$10", "Țuică$9", "Pălincă$6", "Coniac$5", "Ulei$2", "Suc$2" };
    public List<string> Q2 = new List<string>() { "Pe postul RA TV din Regatul Animalelor, ce vietate prezintă, in fiecare duminică „Viața Junglei”?", "Leul$27", "Maimuța$13", "Girafa$13", "Tigrul$8", "Zebra$7", "Elefantul$6", "Vulpe$6", "Ursul$6" };
    public List<string> Q3 = new List<string>() { "La ce eveniment te duci cu telefonul încărcat la maxim pentru că știi că o să faci multe poze?", "Nuntă$39", "Botez$20", "Petrecere$11", "Concert$9", "Aniversare$8", "Balul Bobocilior$5", "Serbare$5", "Revelion$3" };
    public List<string> Q4 = new List<string>() { "Ai o găleată cu mere. Ce faci cu ele?", "Compot$31", "Plăcintă$26", "Gem$14", "Suc$11", "Țuică$5", "Cidru$5", "Prăjitură$4", "Dulceață$4" };
    public List<string> Q5 = new List<string>() { "Pe lângă plopii fără soț, ce mai vezi în parc?", "Bancă$24", "Tei$11", "Stejar$10", "Brad$10", "Castan$10", "Flori$9", "Salcâm$6", "Iarbă$5" };
    public List<string> Q6 = new List<string>() { "Ce se împrăștie foarte ușor dar îți ia o grămadă să aduni la loc?", "Orez$22", "Zahăr$18", "Mărgelele$14", "Făină$13", "Sare$11", "Semințe$9", "Fasole$7", "Piper$6" };

    // Start is called before the first frame update

    private void Awake()
    {
        instance = this;
    }
    void Start()
    {
        Debug.Log(Q1[1]);

    }

    // Update is called once per frame
    void Update()
    {

    }
}

When trying to Debug.Log Q1[1], nothing shows up in Unity, so the problem is probably there. Can anyone tell me how to fix it?


问:
Getting type error from require function of module.exports in nodejs firebase cloud functions
I have a function that I am exporting and importing inside another file. Now this export function is used in a lot of place inside the application and it's working fine everywhere else but for some reason it's becoming undefined inside the cloud function

```<code>const functions = require("firebase-functions");
const admin = require("firebase-admin");
const db = admin.firestore();
const {
  checkAndGetApplicationMode,
} = require("../Utils/application-setup-functions");

exports.createCause = functions.https.onCall(async (data, context) => {
  console.log("applicationMode check", checkAndGetApplicationMode); // Undefined
  console.log("applicationMode check", checkAndGetApplicationMode()); // TypeError: checkAndGetApplicationMode is not a function
});
</code>```

Although If I hover over it in my vs code it does give me reference to the actual function.

Here is the file structure for more information. I am using this checkAndGetApplicationMode function in many other files and it's working fine there. Also if I try require inside the function then works but if i require it outside the file then it gives undefined

File Stucture

Body:
I have a function that I am exporting and importing inside another file. Now this export function is used in a lot of place inside the application and it's working fine everywhere else but for some reason it's becoming undefined inside the cloud function

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const db = admin.firestore();
const {
  checkAndGetApplicationMode,
} = require("../Utils/application-setup-functions");

exports.createCause = functions.https.onCall(async (data, context) => {
  console.log("applicationMode check", checkAndGetApplicationMode); // Undefined
  console.log("applicationMode check", checkAndGetApplicationMode()); // TypeError: checkAndGetApplicationMode is not a function
});

Although If I hover over it in my vs code it does give me reference to the actual function.

Here is the file structure for more information. I am using this checkAndGetApplicationMode function in many other files and it's working fine there. Also if I try require inside the function then works but if i require it outside the file then it gives undefined

File Stucture


问:
How to Import a Project on ESP-IDF using VS Code
I have a project I have written, I was already able to compile at work. Now I am trying to compile the same project on my personal comoputer. It gives me a lot of include path errors. I know I have to change some things in the CMake file however I dont know what to change exactly. I have had problems importing projects from Git as well.

The Question is: How can I import and compile an existing ESP IDF project on VS Code?


问:
How to write Jest test cases for Navbar in react?
I have created a NavBar in react and now I want to write jest test cases for it but not getting how to do it.
Attaching my NavBar code for reference:-</p>
```<code>import Container from "react-bootstrap/Container";
import Nav from "react-bootstrap/Nav";
import Navbar from "react-bootstrap/Navbar";
import { Link } from "react-router-dom";
import { SignOutButton } from "../../pages/SignOutButton";
import Mode from "../Switch/Mode";

function NavBar() {
  return (
    <>
      <Navbar bg="dark" variant="dark">
        <Container>
          <Navbar.Brand as={Link} to="./">
            <img
              alt=""
              src="./images/logo.png"
              width="30"
              height="30"
              className="d-inline-block align-top"
            />
          </Navbar.Brand>
          <Nav className="me-auto">
            <Nav.Link as={Link} to="./Home">Home</Nav.Link>
            <Nav.Link as={Link} to="./About">About</Nav.Link>
            <Nav.Link as={Link} to="./Contact">Contact</Nav.Link>
            <Nav.Link as={Link} to="./History">History</Nav.Link>
          </Nav>
        </Container>
        <Mode />
        <SignOutButton />
      </Navbar>
    </>
  );
}

export default NavBar;
</code>```

Body:
I have created a NavBar in react and now I want to write jest test cases for it but not getting how to do it.
Attaching my NavBar code for reference:-

import Container from "react-bootstrap/Container";
import Nav from "react-bootstrap/Nav";
import Navbar from "react-bootstrap/Navbar";
import { Link } from "react-router-dom";
import { SignOutButton } from "../../pages/SignOutButton";
import Mode from "../Switch/Mode";

function NavBar() {
  return (
    <>
      <Navbar bg="dark" variant="dark">
        <Container>
          <Navbar.Brand as={Link} to="./">

          </Navbar.Brand>

            Home
            About
            Contact
            History

        </Container>
        <Mode />
        <SignOutButton />
      </Navbar>
    </>
  );
}

export default NavBar;


问:
Flutter Image.network test fails because of exception
I use Image.network to display images of items:

```<code>Image.network(
  pictureUri,
  errorBuilder: (context, error, stackTrace) => Image.asset(
    noPictureAssetUri,
  ),
);
</code>```

when given item has an image, then the server returns that image, if the item has no image, then the server returns error 404.

It works fine in release mode - if there is image, it is displayed, and if server sends 404, then it uses the asset.

However when I'm running integration tests (flutter test integration_test), they show:

══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 404,

and then it fails:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following message was thrown:
Multiple exceptions (5) were detected during the running of the current test, and at least one was
unexpected.

The tests fails despite everything working as intended.

How can I make my tests pass? I need either:

a way to catch these internal exceptions

make flutter test ignore
these exceptions.

I want to add that this is an end to end test, running on real (development) server, so I can't just mock http Client as it was suggested. I need a way to handle 404 error, when the real server returns it in debug mode.

My flutter doctor, in case you need it:

Doctor summary (to see all details, run flutter doctor -v):

[√] Flutter (Channel stable, 3.3.10, on Microsoft Windows [Version 10.0.22621.963], locale en-150)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)

[√] Chrome - develop for the web

[√] Android Studio (version 2021.2)

[√] VS Code (version 1.74.2)

[√] Connected device (4 available)

[√] HTTP Host Availability

Body:
I use Image.network to display images of items:

Image.network(
  pictureUri,
  errorBuilder: (context, error, stackTrace) => Image.asset(
    noPictureAssetUri,
  ),
);

when given item has an image, then the server returns that image, if the item has no image, then the server returns error 404.

It works fine in release mode - if there is image, it is displayed, and if server sends 404, then it uses the asset.

However when I'm running integration tests (flutter test integration_test), they show:

══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 404,

and then it fails:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following message was thrown:
Multiple exceptions (5) were detected during the running of the current test, and at least one was
unexpected.

The tests fails despite everything working as intended.

How can I make my tests pass? I need either:

a way to catch these internal exceptions

make flutter test ignore
these exceptions.

I want to add that this is an end to end test, running on real (development) server, so I can't just mock http Client as it was suggested. I need a way to handle 404 error, when the real server returns it in debug mode.

My flutter doctor, in case you need it:

Doctor summary (to see all details, run flutter doctor -v):

[√] Flutter (Channel stable, 3.3.10, on Microsoft Windows [Version 10.0.22621.963], locale en-150)

[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)

[√] Chrome - develop for the web

[√] Android Studio (version 2021.2)

[√] VS Code (version 1.74.2)

[√] Connected device (4 available)

[√] HTTP Host Availability


问:
problem in set cookie and use proxy in vite react app
In Vite ReactJS Ts APP when try to set cookie and use proxy it's not working properly in production nut in the localhost it's working fine

that's my code at vite.config.ts

```<code>
const defaultConfig = {
  plugins: [
    react({ include: "**/*.tsx", }),
  ],
  server: {
    proxy: {
      '/api': {
        target: 'https://tame-lime-rooster-tie.cyclic.app',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            if (!req.headers.cookie) {
              return;
            }
            console.log('req.headers.cookie', req.headers.cookie)
            proxyReq.setHeader('cookie', req.headers.cookie);
          });
        },
        secure: false
      }
    }
  }
}

export default defineConfig(({ command, mode }) => {
  if (command === 'serve') {
    const isDev = mode === 'development';
    return {
      ...defaultConfig,
      server: {
        proxy: {
          '/api': {
            target: isDev ? 'http://localhost:5000' : 'https://tame-lime-rooster-tie.cyclic.app',
            changeOrigin: true,
            configure: (proxy, options) => {
              proxy.on('proxyReq', (proxyReq, req, res) => {
                if (!req.headers.cookie) {
                  return;
                }
                console.log('req.headers.cookie', req.headers.cookie)
                proxyReq.setHeader('cookie', req.headers.cookie);
              });
            },
            secure: false
          }
        }
      }
    }
  } else {
    return defaultConfig;
  }
});
</code>```

but it's working good only on localhost when i deploy the app it's not working good

Body:
In Vite ReactJS Ts APP when try to set cookie and use proxy it's not working properly in production nut in the localhost it's working fine

that's my code at vite.config.ts

const defaultConfig = {
  plugins: [
    react({ include: "**/*.tsx", }),
  ],
  server: {
    proxy: {
      '/api': {
        target: 'https://tame-lime-rooster-tie.cyclic.app',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            if (!req.headers.cookie) {
              return;
            }
            console.log('req.headers.cookie', req.headers.cookie)
            proxyReq.setHeader('cookie', req.headers.cookie);
          });
        },
        secure: false
      }
    }
  }
}

export default defineConfig(({ command, mode }) => {
  if (command === 'serve') {
    const isDev = mode === 'development';
    return {
      ...defaultConfig,
      server: {
        proxy: {
          '/api': {
            target: isDev ? 'http://localhost:5000' : 'https://tame-lime-rooster-tie.cyclic.app',
            changeOrigin: true,
            configure: (proxy, options) => {
              proxy.on('proxyReq', (proxyReq, req, res) => {
                if (!req.headers.cookie) {
                  return;
                }
                console.log('req.headers.cookie', req.headers.cookie)
                proxyReq.setHeader('cookie', req.headers.cookie);
              });
            },
            secure: false
          }
        }
      }
    }
  } else {
    return defaultConfig;
  }
});

but it's working good only on localhost when i deploy the app it's not working good


问:
Execution failed for task ':app:mergeReleaseResources' (When running eas build -p android --profile production)
I'm getting the following error when building the react-native apk app for android via expo build command for production.

Below is the package.json, eas.json and error

package.json ((https://i.stack.imgur.com/3pgm5.png)

eas.json (https://i.stack.imgur.com/tY3YS.png)

ERROR ON EXPO BUILD:

[stderr] Execution failed for task ':app:mergeReleaseResources'.
[stderr] > A failure occurred while executing com.android.build.gradle.internal.res.Aapt2CompileRunnable
[stderr]    > Android resource compilation failed
[stderr]      ERROR:/home/expo/workingdir/build/mobile-app-paywise/android/app/build/generated/res/react/release/drawable-mdpi/assets_images_registration.png: AAPT: error: file failed to compile.
[stderr]

[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] 2: Task failed with an exception.
[stderr] -----------
[stderr] * What went wrong:
[stderr] java.lang.StackOverflowError (no error message)
[stderr] * Try:
[stderr] > Run with --stacktrace option to get the stack trace.
[stderr] > Run with --info or --debug option to get more log output.
[stderr] > Run with --scan to get full insights.
[stderr] ==============================================================================
[stderr] * Get more help at https://help.gradle.org
[stderr] BUILD FAILED in 5m 13s
Error: Gradle build failed with unknown error. See logs for the "Run gradlew" phase for more information.

Tried npx expo prebuild, and deleted the drawable* files, but still facing same issues.
Appreciate if anyone could help :(


问:
Can I give a specific style to a tag of a html markup textfield in Jaspersoft Studio?
I am having problems with lists in jaspersoft studio.
My problem is described in this question: Indentation in generated PDF using JasperReports

I tried this and it worked, but not as the way I intended. Since I don't have only Ordered Lists in the HTML that comes from my database, the whole textfield is having these styles applied. I am trying to find a way to only apply this style to the
 tags in the html.

Is there a way to do it? I tried with  a
Lorem ipsum for testing what is happening. The text is starting on the wrong place in the second line. Why? Lorem ipsum for testing what is happening. The text is starting on the wrong place in the second line. Why? Lorem ipsum for testing what is happening. The text is starting on the wrong place in the second line. Why?

test

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nisl dui, imperdiet nec maximus vitae, feugiat quis ligula. Sed ac ornare metus, posuere sagittis lectus. Vestibulum varius dui ut erat congue dapibus. Nunc malesuada eros et condimentum cursus. Sed semper efficitur massa. Phasellus sed odio tempus, semper neque quis, ullamcorper eros. Vestibulum luctus viverra justo, eget pellentesque nulla cursus nec. Integer tortor velit, auctor at lectus ac, fermentum accumsan dolor. Phasellus tincidunt odio sed sagittis vestibulum. Vestibulum ac enim vel ante ornare iaculis. Proin dapibus hendrerit elementum.

JUST A TEST

test

test
"]]></textFieldExpression>
            </textField>
```

Thanks.

Body:
I am having problems with lists in jaspersoft studio.
My problem is described in this question: Indentation in generated PDF using JasperReports

I tried this and it worked, but not as the way I intended. Since I don't have only Ordered Lists in the HTML that comes from my database, the whole textfield is having these styles applied. I am trying to find a way to only apply this style to the
 tags in the html.

Is there a way to do it? I tried with  a
Lorem ipsum for testing what is happening. The text is starting on the wrong place in the second line. Why? Lorem ipsum for testing what is happening. The text is starting on the wrong place in the second line. Why? Lorem ipsum for testing what is happening. The text is starting on the wrong place in the second line. Why?

test

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nisl dui, imperdiet nec maximus vitae, feugiat quis ligula. Sed ac ornare metus, posuere sagittis lectus. Vestibulum varius dui ut erat congue dapibus. Nunc malesuada eros et condimentum cursus. Sed semper efficitur massa. Phasellus sed odio tempus, semper neque quis, ullamcorper eros. Vestibulum luctus viverra justo, eget pellentesque nulla cursus nec. Integer tortor velit, auctor at lectus ac, fermentum accumsan dolor. Phasellus tincidunt odio sed sagittis vestibulum. Vestibulum ac enim vel ante ornare iaculis. Proin dapibus hendrerit elementum.

JUST A TEST

test

test
"]]></textFieldExpression>
            </textField>

Thanks.


问:
How to change subtitles of video during Airplay on web
I have a native video player (VideoElement) with custom controls that supports AirPlay.

The videoElement has textTracks (subtitles) that work fine when playing in the video and they work fine in AirPlay when changing subtitles using the Apple TV Remote.

However, when I start AirPlay I want to be able to change the subtitles (turn them off / on / change language) from my video player controls (without using the Remote).

But this doesn't seem to work? When I try to change the textTracks the update does not reflect on the video during AirPlay.

E.g. This sets the textTrack.mode correctly and I can console log it correctly afterwards, but it does not update the current AirPlay session to reflect the change.

const textTrack = videoElement.textTracks[0]
textTrack.mode = 'hidden' // this should hide the subtitles
```

(in the above simplified example I only have 1 textTrack for testing "English" that's either on or off)

Is it not possible to change subtitles from web during an AirPlay session?

Body:
I have a native video player (VideoElement) with custom controls that supports AirPlay.

The videoElement has textTracks (subtitles) that work fine when playing in the video and they work fine in AirPlay when changing subtitles using the Apple TV Remote.

However, when I start AirPlay I want to be able to change the subtitles (turn them off / on / change language) from my video player controls (without using the Remote).

But this doesn't seem to work? When I try to change the textTracks the update does not reflect on the video during AirPlay.

E.g. This sets the textTrack.mode correctly and I can console log it correctly afterwards, but it does not update the current AirPlay session to reflect the change.

const textTrack = videoElement.textTracks[0]
textTrack.mode = 'hidden' // this should hide the subtitles

(in the above simplified example I only have 1 textTrack for testing "English" that's either on or off)

Is it not possible to change subtitles from web during an AirPlay session?


问:
Encountering Migration Issue When Altering ApplicationUser Table on New DotNet 6 React Project
Started a small dot net / react project for picture uploading, I'm familiar with both react and dot net but have never had them working together.
Wanted to use React for a better front end experience but enjoy the MC aspect of dot net, so, best of both worlds.

I'm able to subvert the issue by commenting out some of a migration but wanted to double check this won't bite me down the line.

Here's the command line for the scaffolding I used:

```<code>dotnet new react -o my-picture-project -f net6.0 -uld true -au Individual
</code>```

Once I had it running I wanted to put an Organization and ApplicationUser rights (ApplicationUsers will belong to a main Organization who will have certain admin rights over them).

These are the models and the only changes I made before building the migration and attempting to update the DB

Application Organization

```<code>using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace my_picture_project.Models
{
    public class ApplicationOrganization
    {
        public int ApplicationOrganizationID { get; set; }

        [Display(Name = "Organization Name")]
        [MaxLength(50)]
        public string Name { get; set; }

        // Navigation property
        [JsonIgnore]
        public virtual List<ApplicationUser> ApplicationUserList { get; set; }
    }
}
</code>```

Application User

```<code>using Microsoft.AspNetCore.Identity;

namespace my_picture_project.Models;

    public class ApplicationUser : IdentityUser
    {
        public virtual ApplicationOrganization ApplicationOrganization { get; set; }
        public int OrganizationID { get; set; }
    }
</code>```

(With the auth scaffolding on this project - there was already an ApplicationUser model, I just altered it)
The error I get on attempting to update the DB is:

```<code>The operation failed because an index or statistics with name 'IX_PersistedGrants_ConsumedTime' already exists on table 'PersistedGrants'.
</code>```

And the reason for this is as it states - it already exists.

Like I said, commenting it out alleviates it and allows it to run, so my guess is there is a hiccup with the original CreateIdentitySchema migration colliding with my tweaks to ApplicationUser.

I just wanted to see if anyone could give me a second opinion before I dove too deep.

Body:
Started a small dot net / react project for picture uploading, I'm familiar with both react and dot net but have never had them working together.
Wanted to use React for a better front end experience but enjoy the MC aspect of dot net, so, best of both worlds.

I'm able to subvert the issue by commenting out some of a migration but wanted to double check this won't bite me down the line.

Here's the command line for the scaffolding I used:

dotnet new react -o my-picture-project -f net6.0 -uld true -au Individual

Once I had it running I wanted to put an Organization and ApplicationUser rights (ApplicationUsers will belong to a main Organization who will have certain admin rights over them).

These are the models and the only changes I made before building the migration and attempting to update the DB

Application Organization

using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace my_picture_project.Models
{
    public class ApplicationOrganization
    {
        public int ApplicationOrganizationID { get; set; }

        [Display(Name = "Organization Name")]
        [MaxLength(50)]
        public string Name { get; set; }

        // Navigation property
        [JsonIgnore]
        public virtual List<ApplicationUser> ApplicationUserList { get; set; }
    }
}

Application User

using Microsoft.AspNetCore.Identity;

namespace my_picture_project.Models;

    public class ApplicationUser : IdentityUser
    {
        public virtual ApplicationOrganization ApplicationOrganization { get; set; }
        public int OrganizationID { get; set; }
    }

(With the auth scaffolding on this project - there was already an ApplicationUser model, I just altered it)
The error I get on attempting to update the DB is:

The operation failed because an index or statistics with name 'IX_PersistedGrants_ConsumedTime' already exists on table 'PersistedGrants'.

And the reason for this is as it states - it already exists.

Like I said, commenting it out alleviates it and allows it to run, so my guess is there is a hiccup with the original CreateIdentitySchema migration colliding with my tweaks to ApplicationUser.

I just wanted to see if anyone could give me a second opinion before I dove too deep.


问:
Spark PickleException: expected zero arguments for construction of ClassDict (for numpy.dtype)
I'm trying to return a double type from a udf in spark, but it gives me this error.

The udf is:

```<code>def new_pagerank(links, current_pr, counters):
  n_pr = 0;
  #for each incoming link to the page calculate the pagerank
  #zip the links and counters to get them both in the loop
  for l, c in zip(links, counters):

    #get current_pr of the link l
    current_link_pr=current_pr.loc[current_pr['id'] == l].PR

    n_pr += current_link_pr/c
  new_pr = 0.85/N+0.15*n_pr
  return new_pr
</code>```

the udf caller is:

```<code>new_pagerank_udf = udf(lambda x,y: new_pagerank(x,pageRankPDF,y), DoubleType())

NewPageRankDF=ReverseDF.select(ReverseDF["id"],new_pagerank_udf(ReverseDF["links"],ReverseDF["counters"]).alias("PR"))
pagerankPDF=NewPageRankDF.toPandas()
</code>```

ReverseDF:

```<code>root
 |-- id: long (nullable = false)
 |-- Links: array (nullable = false)
 |    |-- element: integer (containsNull = false)
 |-- counters: array (nullable = false)
 |    |-- element: integer (containsNull = false)
</code>```

pageRankPDF:

```<code> #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   id      5319 non-null   int64
 1   PR      5319 non-null   float64
</code>```

the problem is that current_link_pr returns a series and not a float type but i cannot cast to it using .iloc[0]

```<code>current_link_pr=current_pr.loc[current_pr['id'] == l].PR.iloc[0]
</code>```

because it gives 'IndexError: single positional indexer is out-of-bounds'

So is there a way to cast it to a float without using loc()?

Body:
I'm trying to return a double type from a udf in spark, but it gives me this error.

The udf is:

def new_pagerank(links, current_pr, counters):
  n_pr = 0;
  #for each incoming link to the page calculate the pagerank
  #zip the links and counters to get them both in the loop
  for l, c in zip(links, counters):

    #get current_pr of the link l
    current_link_pr=current_pr.loc[current_pr['id'] == l].PR

    n_pr += current_link_pr/c
  new_pr = 0.85/N+0.15*n_pr
  return new_pr

the udf caller is:

new_pagerank_udf = udf(lambda x,y: new_pagerank(x,pageRankPDF,y), DoubleType())

NewPageRankDF=ReverseDF.select(ReverseDF["id"],new_pagerank_udf(ReverseDF["links"],ReverseDF["counters"]).alias("PR"))
pagerankPDF=NewPageRankDF.toPandas()

ReverseDF:

root
 |-- id: long (nullable = false)
 |-- Links: array (nullable = false)
 |    |-- element: integer (containsNull = false)
 |-- counters: array (nullable = false)
 |    |-- element: integer (containsNull = false)

pageRankPDF:

 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   id      5319 non-null   int64
 1   PR      5319 non-null   float64

the problem is that current_link_pr returns a series and not a float type but i cannot cast to it using .iloc[0]

current_link_pr=current_pr.loc[current_pr['id'] == l].PR.iloc[0]

because it gives 'IndexError: single positional indexer is out-of-bounds'

So is there a way to cast it to a float without using loc()?


问:
How can I fix the HTTP request timed out error when clicking on a Print button?

So what I am trying to do it to test if by pressing the "Print" button, the print window will be displayed. For this, I am testing on this site https://testguild.com/SeleniumTestPage.html. I want to do this by writing an automated test in C# using nUnit and Selenium. The problem is that after I press the print button, the flow stops and after some time I get an HTTP request timed out error. As a mention, I get this error even if I add the argument --no-sandbox to the driver options and this is the only case for which I get this error.

The code of the test is presented below (In the Page class I instantiate the WebDriver and I think it's not relevant):

public void print(){           Page.GetDriver().Navigate().GoToUrl("https://www.joecolantonio.com/SeleniumTestPage.html");

Page.GetWait().Until(ExpectedConditions.ElementIsVisible(By.Id("printButton")));

Page.GetDriver().FindElement(By.Id("printButton")).Click();

}

And the error I am getting is this:

```<code>Message:
OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:59603/session/4c2ec74541511e5b587cdb608432f98c/element/cd52f5b9-aa09-4cc4-b795-7acd83a72ad2/click timed out after 60 seconds.
  ----> System.Threading.Tasks.TaskCanceledException : The operation was canceled.
  ----> System.IO.IOException : Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request..
  ----> System.Net.Sockets.SocketException : The I/O operation has been aborted because of either a thread exit or an application request.```
```

Body:
So what I am trying to do it to test if by pressing the "Print" button, the print window will be displayed. For this, I am testing on this site https://testguild.com/SeleniumTestPage.html. I want to do this by writing an automated test in C# using nUnit and Selenium. The problem is that after I press the print button, the flow stops and after some time I get an HTTP request timed out error. As a mention, I get this error even if I add the argument --no-sandbox to the driver options and this is the only case for which I get this error.

The code of the test is presented below (In the Page class I instantiate the WebDriver and I think it's not relevant):

public void print(){           Page.GetDriver().Navigate().GoToUrl("https://www.joecolantonio.com/SeleniumTestPage.html");

Page.GetWait().Until(ExpectedConditions.ElementIsVisible(By.Id("printButton")));

Page.GetDriver().FindElement(By.Id("printButton")).Click();

}

And the error I am getting is this:

Message:
OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL http://localhost:59603/session/4c2ec74541511e5b587cdb608432f98c/element/cd52f5b9-aa09-4cc4-b795-7acd83a72ad2/click timed out after 60 seconds.
  ----> System.Threading.Tasks.TaskCanceledException : The operation was canceled.
  ----> System.IO.IOException : Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request..
  ----> System.Net.Sockets.SocketException : The I/O operation has been aborted because of either a thread exit or an application request.```


问:
Active Directory and External Email Accounts
In my place of work we have an Active Directory with 'staff' accounts. Each of these AD accounts has an associated company email, e.g. john@example.com

Within the same AD we also have 'external' user accounts, e.g. suppliers, contractors etc. This allows the external users to login and access some of our systems using their AD credentials (user number and password). None of these external users have an email address associated with their AD account.

The only users with an AD email address are 'staff'. There are various reasons why we would like 'external' users to have an email address, e.g. Currently they cannot use the 'send to email' feature of our printers, as they have no associated email.

I have a few questions (I am not an AD administrator or security expert, and I'm not familiar with the email or AD infrastructure.)

is it technically possible to associate an external domain email address to our internal AD user accounts (e.g. john@gmail.com)

will doing this pose any security risks / why would AD admins be reluctant to do this

is there a better / safer alternative


问:
Generate random vertex of regular polygon
I need help with programming random vertices of regular polygon. I want to get a function, where for n regular polygon get vertices of random coordinates. I tried like this but I have to have coordinates of poly. Any help?</p>
```<code>import random

def polygon_random_points (poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds
    points = []
    while len(points) < num_points:
        random_point = Point([random.uniform(min_x, max_x), random.uniform(min_y, max_y)])
        if (random_point.within(poly)):
            points.append(random_point)
    return points
</code>```

Body:
I need help with programming random vertices of regular polygon. I want to get a function, where for n regular polygon get vertices of random coordinates. I tried like this but I have to have coordinates of poly. Any help?

import random

def polygon_random_points (poly, num_points):
    min_x, min_y, max_x, max_y = poly.bounds
    points = []
    while len(points) < num_points:
        random_point = Point([random.uniform(min_x, max_x), random.uniform(min_y, max_y)])
        if (random_point.within(poly)):
            points.append(random_point)
    return points


问:
Sort Array in IBM EGL
I have in (ibm) EGL an arry of following record:

```<code>record FreelanceOrderRec
    orderNr                     int;
    date                        date;
    installerNr                 int;
    partOfDay                   string;
    ....
end
</code>```

orderNr is the key of the order,

installeNr also (personel files),

date is the date our freelancer will install the order

PartOfday is during what hours the installer will go to the client,
it can have following  values:

```<code>"1 (08:00-13:00)";
"2 (11:00-15:00)";
"3 (13:00-17:00)";
"Not Known.";
</code>```

This array is scrambled and I want to order it like this:

date desc, installeNr desc, PartOfday desc

how can I order an array like that in egl?

```<code>(freelanceOrderRecs FreelanceOrderRec[])
</code>```

Title: Sort Array in IBM EGL

Body:
I have in (ibm) EGL an arry of following record:

record FreelanceOrderRec
    orderNr                     int;
    date                        date;
    installerNr                 int;
    partOfDay                   string;
    ....
end

orderNr is the key of the order,

installeNr also (personel files),

date is the date our freelancer will install the order

PartOfday is during what hours the installer will go to the client,
it can have following  values:

"1 (08:00-13:00)";
"2 (11:00-15:00)";
"3 (13:00-17:00)";
"Not Known.";

This array is scrambled and I want to order it like this:

date desc, installeNr desc, PartOfday desc

how can I order an array like that in egl?

(freelanceOrderRecs FreelanceOrderRec[])


问:
Angular 15.x ngSrc and ngSrcset issue
In my Angular 15.x project I'm using NgOptimizedImage with ngSrc and ngSrcset but getting incorrect result according to the documentation.

When I enter:

Documentation says I should get:

Instead I get:

So the same image is returned....

Title: Angular 15.x ngSrc and ngSrcset issue


问:
How to get the updated activities in getstream io when a reaction is added
Im implementing getstream io in my app.when a new comment is added thought the screen is getting rebuilt,i =m not getting new reaction in the activities
How do i get to see my latest comment soon when its added


问:
Im trying to build a dashboard that checks if a sit is up or not
So basically im trying to create a webapp that checks weather a website is up or not based on https statuscodes.
When i test the node code using a url that doesn't exist my app.js crashes.

i tried logging the http response code in a var and using that var to change the content of the webpage

here is the code i tried

Node:

```<code>
const express = require("express");
const jsdom = require('jsdom');
const { appendFile } = require('fs');
const app = express();
var https = require('https')

app.set('view engine', 'ejs');

var request = https.get("https://www.dutchen.com/", function (res) {
    var statusCode = (res.statusCode);
    console.log(statusCode);
    request.on("error", function (error) {
        console.error(error.status);
    });

app.get('/', function(req, res) {
    res.render('pages/index.ejs', {
        statusCode: statusCode
    });
    });
});

app.listen(3000, function() {
    console.log(`Example app listening on port 3000`);
  });
</code>```

EJS:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <%- include('../partials/head'); %>
</head>
<body class="container">
  <h1>FCIT Website status checker</h1>
  <p>Check the FCIT website status</p>
<main>
  <div class="container text-center">
    <div class="row">
      <div class="col">
        <h2>Dutchen.com</h2>
        <% if(statusCode < 400){ %>
          <h1>Online</h1>
        <% } else{ %>
          <h1>Offline</h1>
       <% } %>
      </div>
      <div class="col">

      </div>
      <div class="col">

      </div>
    </div>
  </div>
</main>

<footer>
  <%- include('../partials/footer'); %>
</footer>

</body>
</html>
</code>```

Body:
So basically im trying to create a webapp that checks weather a website is up or not based on https statuscodes.
When i test the node code using a url that doesn't exist my app.js crashes.

i tried logging the http response code in a var and using that var to change the content of the webpage

here is the code i tried

Node:

const express = require("express");
const jsdom = require('jsdom');
const { appendFile } = require('fs');
const app = express();
var https = require('https')

app.set('view engine', 'ejs');

var request = https.get("https://www.dutchen.com/", function (res) {
    var statusCode = (res.statusCode);
    console.log(statusCode);
    request.on("error", function (error) {
        console.error(error.status);
    });

app.get('/', function(req, res) {
    res.render('pages/index.ejs', {
        statusCode: statusCode
    });
    });
});

app.listen(3000, function() {
    console.log(`Example app listening on port 3000`);
  });

EJS:

<!DOCTYPE html>

  <%- include('../partials/head'); %>

FCIT Website status checker

Check the FCIT website status

Dutchen.com

        <% if(statusCode < 400){ %>

Online

        <% } else{ %>

Offline

       <% } %>

  <%- include('../partials/footer'); %>