问:
How to make multiple API http requests with Angular 14
I am currently doing a project for work that requires me to pass in two APIs within two different input tags. I been following along a stackblitz demo, and was wondering how could I implement this to my project

HTML

```<code><form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
        {{option.name}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>
</code>```

TS

```<code>@Injectable({
  providedIn: 'root'
})
export class Service {
  constructor(private http: HttpClient) { }

  opts = [];

  getData() {
    return this.opts.length ?
      of(this.opts) :
      this.http.get<any>('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
  }
}

/**
 * @title Simple autocomplete
 */
@Component({
  selector: 'autocomplete-simple-example',
  templateUrl: 'autocomplete-simple-example.html',
  styleUrls: ['autocomplete-simple-example.css'],
})
export class AutocompleteSimpleExample {
  myControl = new FormControl();
  options = [];
  filteredOptions: Observable<any[]>;

  constructor(private service: Service) {
     this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      debounceTime(400),
      distinctUntilChanged(),
      switchMap(val => {
            return this.filter(val || '')
       })
    )
   }

  ngOnInit() {

  }

  filter(val: string): Observable<any[]> {
    // call the service which makes the http-request
    return this.service.getData()
     .pipe(
       map(response => response.filter(option => {
         return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
       }))
     )
   }
}
</code>```

I looked up the subscribe method but wasn't sure on where to implement it.

Body:
I am currently doing a project for work that requires me to pass in two APIs within two different input tags. I been following along a stackblitz demo, and was wondering how could I implement this to my project

HTML

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
        {{option.name}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

TS

@Injectable({
  providedIn: 'root'
})
export class Service {
  constructor(private http: HttpClient) { }

  opts = [];

  getData() {
    return this.opts.length ?
      of(this.opts) :
      this.http.get<any>('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
  }
}

/**
 * @title Simple autocomplete
 */
@Component({
  selector: 'autocomplete-simple-example',
  templateUrl: 'autocomplete-simple-example.html',
  styleUrls: ['autocomplete-simple-example.css'],
})
export class AutocompleteSimpleExample {
  myControl = new FormControl();
  options = [];
  filteredOptions: Observable<any[]>;

  constructor(private service: Service) {
     this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      debounceTime(400),
      distinctUntilChanged(),
      switchMap(val => {
            return this.filter(val || '')
       })
    )
   }

  ngOnInit() {

  }

  filter(val: string): Observable<any[]> {
    // call the service which makes the http-request
    return this.service.getData()
     .pipe(
       map(response => response.filter(option => {
         return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
       }))
     )
   }
}

I looked up the subscribe method but wasn't sure on where to implement it.


来源: stackexchange

问:
EntryPointNotFoundException thrown when reading from Header collection in HttpRequest
I have an Azure Function with a HTTP Trigger to handle a webhook.  It's all working fine (function being triggered, reading the POST body) until I try to check for a value in the http request Headers collection.

The request is a Microsoft.AspNetCore.Http.HttpRequest, which appears to be an Abstract base class, being instantiated behind the scenes toDefaultHttpRequest.

The offending lines of code are

```<code>var requestBody = await (new StreamReader(req.Body)).ReadToEndAsync();  // works fine
if (req.Headers.ContainsKey("X-Payload-Digest"))  // crashes out, can't read from Headers
{
    req.Headers.TryGetValue("X-Payload-Digest", out var secretKey);
}
</code>```

The code throws an exception when trying to retrieve or check anything from the Headers collection property of the HttpRequest req variable.

The funny thing is, whilst debugging I can pause execution and run req.Headers.ContainsKey("X-Payload-Digest") just fine in the VS 2022 immediate window.  Yet it fails when stepping through the code.  Even in debug, pausing on breakpoints.

The debugger links out to Microsoft.Azure.WebJobs.Host.Executors TaskMethodInvoker -> FunctionInvoker, which returns Result = "{Not yet computed}"

And the eventual Exception thrown is EntryPointNotFoundException

One theory was that it's down to async / await, with it trying to read from req.Headers too soon before it's hydrated, but I don't think that's it.  Another hypothesis is that maybe it's referencing an incorrect Assembly or dll, where the Headers collection itself isn't available as a property or it's available methods are different, which seems more likely but I can't figure out how or why.  Or if it's even the case!

All thoughts welcome on this, I'm stumpted!

ContentLicense: CC BY-SA 4.0

Body:
I have an Azure Function with a HTTP Trigger to handle a webhook.  It's all working fine (function being triggered, reading the POST body) until I try to check for a value in the http request Headers collection.

The request is a Microsoft.AspNetCore.Http.HttpRequest, which appears to be an Abstract base class, being instantiated behind the scenes toDefaultHttpRequest.

The offending lines of code are

var requestBody = await (new StreamReader(req.Body)).ReadToEndAsync();  // works fine
if (req.Headers.ContainsKey("X-Payload-Digest"))  // crashes out, can't read from Headers
{
    req.Headers.TryGetValue("X-Payload-Digest", out var secretKey);
}

The code throws an exception when trying to retrieve or check anything from the Headers collection property of the HttpRequest req variable.

The funny thing is, whilst debugging I can pause execution and run req.Headers.ContainsKey("X-Payload-Digest") just fine in the VS 2022 immediate window.  Yet it fails when stepping through the code.  Even in debug, pausing on breakpoints.

The debugger links out to Microsoft.Azure.WebJobs.Host.Executors TaskMethodInvoker -> FunctionInvoker, which returns Result = "{Not yet computed}"

And the eventual Exception thrown is EntryPointNotFoundException

One theory was that it's down to async / await, with it trying to read from req.Headers too soon before it's hydrated, but I don't think that's it.  Another hypothesis is that maybe it's referencing an incorrect Assembly or dll, where the Headers collection itself isn't available as a property or it's available methods are different, which seems more likely but I can't figure out how or why.  Or if it's even the case!

All thoughts welcome on this, I'm stumpted!


问:
Can Subquery Scalar Values Be Evaluated Before The Query Condition Is Evaluated In PostgreSQL?

Overview

I'm trying to filter on one of two columns depending on the result of a subquery. However, on analysing the queries it shows that the subquery values are evaulated too late - leading to less efficient index or full table scans.

Examples

The query needs to perform a computation once (in this case I'm using common table expressions). Then based on the result of that computation one of two columns should be used in the condition.

I've attempted to illustrate this below in the following toy examples.

What I Want To Work

```<code>WITH "polygon" AS (SELECT ST_SetSRID(ST_GeomFromGeoJSON('{"type":"Polygon","coordinates":[[[-0.004,0.004],[0.004,0.004],[0.004,-0.004],[-0.004,-0.004],[-0.004,0.004]]]}'), 4326) AS "polygon"),
     "geometry" AS (SELECT ST_Transform("polygon", 900913) AS "geometry", ST_Area("polygon"::GEOGRAPHY) AS "area" FROM "polygon"),
     "parameters" AS (
         SELECT "area" > 1000000 AS "use_geom_alt"
         FROM "geometry"
     )
SELECT r.*
      FROM "record_record" "r"
      WHERE ("record_date" >= '2000-01-01' AND "record_date" <= '2019-12-31')
        AND (
              --
              (NOT (SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom))
              OR ((SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom_alt))
          );
</code>```

In the above example I'm attempting to short circuit the condition based on the value of use_geom_alt. The value of use_geom_alt is FALSE so ST_Intersects((SELECT geometry FROM geometry), r.geom) would be evaluated - and preferably using it's index.

```<code>              (NOT (SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom))
              OR ((SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom_alt))

</code>```

However, as can be seen in the query plan below the subquery is evaluated too late to be of use and a less efficient (record_date) index scan is used.

```<code>QUERY PLAN
Gather  (cost=1000.54..31522732.07 rows=142 width=4734) (actual time=0.702..897.763 rows=18100 loops=1)
    Workers Planned: 2
    "Params Evaluated: $2, $3, $4, $5"
    Workers Launched: 2
    CTE geometry
        ->  Result  (cost=0.00..0.01 rows=1 width=40) (actual time=0.001..0.002 rows=1 loops=1)
    CTE parameters
        ->  CTE Scan on geometry  (cost=0.00..0.02 rows=1 width=1) (actual time=0.004..0.005 rows=1 loops=1)
    InitPlan 3 (returns $2)
        ->  CTE Scan on parameters  (cost=0.00..0.02 rows=1 width=1) (actual time=0.005..0.006 rows=1 loops=1)
    InitPlan 4 (returns $3)
        ->  CTE Scan on geometry geometry_1  (cost=0.00..0.02 rows=1 width=32) (actual time=0.000..0.001 rows=1 loops=1)
    InitPlan 5 (returns $4)
        ->  CTE Scan on parameters parameters_1  (cost=0.00..0.02 rows=1 width=1) (actual time=0.000..0.000 rows=1 loops=1)
    InitPlan 6 (returns $5)
        ->  CTE Scan on geometry geometry_2  (cost=0.00..0.02 rows=1 width=32) (actual time=0.000..0.001 rows=1 loops=1)
    ->  Parallel Index Scan using record_record_record_date_idx on record_record r  (cost=0.43..31521717.75 rows=59 width=4734) (actual time=0.103..857.236 rows=6033 loops=3)
        Index Cond: ((record_date >= '2000-01-01'::date) AND (record_date <= '2019-12-31'::date))
        "Filter: (((NOT $2) AND st_intersects($3, geom)) OR ($4 AND st_intersects($5, geom_alt)))"
        Rows Removed by Filter: 470543
Planning Time: 0.427 ms
Execution Time: 898.936 ms
</code>```

How I Wanted It To Work

The following query is the same as above except the use of the (SELECT use_geom_alt FROM parameters) subquery has been replaced with boolean literals to explicitly short circuit the condition.

```<code>WITH "polygon" AS (SELECT ST_SetSRID(ST_GeomFromGeoJSON('{"type":"Polygon","coordinates":[[[-0.004,0.004],[0.004,0.004],[0.004,-0.004],[-0.004,-0.004],[-0.004,0.004]]]}'), 4326) AS "polygon"),
     "geometry" AS (SELECT ST_Transform("polygon", 900913) AS "geometry", ST_Area("polygon"::GEOGRAPHY) AS "area" FROM "polygon"),
     "parameters" AS (
         SELECT "area" > 1000000 AS "use_geom_alt"
         FROM "geometry"
     )
SELECT r.*
      FROM "record_record" "r"
      WHERE ("record_date" >= '2000-01-01' AND "record_date" <= '2019-12-31')
        AND (
              (TRUE AND ST_Intersects((SELECT geometry FROM geometry), r.geom))
              OR (FALSE AND ST_Intersects((SELECT geometry FROM geometry), r.geom_alt))
          );
</code>```

This results in the desired query plan.

```<code>QUERY PLAN
Index Scan using record_record_geom_idx on record_record r  (cost=0.44..5754.90 rows=142 width=4734) (actual time=0.076..53.885 rows=18100 loops=1)
    Index Cond: (geom && $1)
    "Filter: ((record_date >= '2000-01-01'::date) AND (record_date <= '2019-12-31'::date) AND st_intersects($1, geom))"
    Rows Removed by Filter: 6620
    CTE geometry
        ->  Result  (cost=0.00..0.01 rows=1 width=40) (actual time=0.001..0.001 rows=1 loops=1)
    InitPlan 2 (returns $1)
        ->  CTE Scan on geometry  (cost=0.00..0.02 rows=1 width=32) (actual time=0.003..0.004 rows=1 loops=1)
Planning Time: 0.370 ms
Execution Time: 54.783 ms
</code>```

In Conclusion

I would like know to if what I want to achieve is at all possible?

Alternatively, I realise I may be asking the wrong question and I would be interested in hearing about alternative approaches.

Body:
Overview

I'm trying to filter on one of two columns depending on the result of a subquery. However, on analysing the queries it shows that the subquery values are evaulated too late - leading to less efficient index or full table scans.

Examples

The query needs to perform a computation once (in this case I'm using common table expressions). Then based on the result of that computation one of two columns should be used in the condition.

I've attempted to illustrate this below in the following toy examples.

What I Want To Work

WITH "polygon" AS (SELECT ST_SetSRID(ST_GeomFromGeoJSON('{"type":"Polygon","coordinates":[[[-0.004,0.004],[0.004,0.004],[0.004,-0.004],[-0.004,-0.004],[-0.004,0.004]]]}'), 4326) AS "polygon"),
     "geometry" AS (SELECT ST_Transform("polygon", 900913) AS "geometry", ST_Area("polygon"::GEOGRAPHY) AS "area" FROM "polygon"),
     "parameters" AS (
         SELECT "area" > 1000000 AS "use_geom_alt"
         FROM "geometry"
     )
SELECT r.*
      FROM "record_record" "r"
      WHERE ("record_date" >= '2000-01-01' AND "record_date" <= '2019-12-31')
        AND (
              --
              (NOT (SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom))
              OR ((SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom_alt))
          );

In the above example I'm attempting to short circuit the condition based on the value of use_geom_alt. The value of use_geom_alt is FALSE so ST_Intersects((SELECT geometry FROM geometry), r.geom) would be evaluated - and preferably using it's index.

              (NOT (SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom))
              OR ((SELECT use_geom_alt FROM parameters) AND ST_Intersects((SELECT geometry FROM geometry), r.geom_alt))

However, as can be seen in the query plan below the subquery is evaluated too late to be of use and a less efficient (record_date) index scan is used.

QUERY PLAN
Gather  (cost=1000.54..31522732.07 rows=142 width=4734) (actual time=0.702..897.763 rows=18100 loops=1)
    Workers Planned: 2
    "Params Evaluated: $2, $3, $4, $5"
    Workers Launched: 2
    CTE geometry
        ->  Result  (cost=0.00..0.01 rows=1 width=40) (actual time=0.001..0.002 rows=1 loops=1)
    CTE parameters
        ->  CTE Scan on geometry  (cost=0.00..0.02 rows=1 width=1) (actual time=0.004..0.005 rows=1 loops=1)
    InitPlan 3 (returns $2)
        ->  CTE Scan on parameters  (cost=0.00..0.02 rows=1 width=1) (actual time=0.005..0.006 rows=1 loops=1)
    InitPlan 4 (returns $3)
        ->  CTE Scan on geometry geometry_1  (cost=0.00..0.02 rows=1 width=32) (actual time=0.000..0.001 rows=1 loops=1)
    InitPlan 5 (returns $4)
        ->  CTE Scan on parameters parameters_1  (cost=0.00..0.02 rows=1 width=1) (actual time=0.000..0.000 rows=1 loops=1)
    InitPlan 6 (returns $5)
        ->  CTE Scan on geometry geometry_2  (cost=0.00..0.02 rows=1 width=32) (actual time=0.000..0.001 rows=1 loops=1)
    ->  Parallel Index Scan using record_record_record_date_idx on record_record r  (cost=0.43..31521717.75 rows=59 width=4734) (actual time=0.103..857.236 rows=6033 loops=3)
        Index Cond: ((record_date >= '2000-01-01'::date) AND (record_date <= '2019-12-31'::date))
        "Filter: (((NOT $2) AND st_intersects($3, geom)) OR ($4 AND st_intersects($5, geom_alt)))"
        Rows Removed by Filter: 470543
Planning Time: 0.427 ms
Execution Time: 898.936 ms

How I Wanted It To Work

The following query is the same as above except the use of the (SELECT use_geom_alt FROM parameters) subquery has been replaced with boolean literals to explicitly short circuit the condition.

WITH "polygon" AS (SELECT ST_SetSRID(ST_GeomFromGeoJSON('{"type":"Polygon","coordinates":[[[-0.004,0.004],[0.004,0.004],[0.004,-0.004],[-0.004,-0.004],[-0.004,0.004]]]}'), 4326) AS "polygon"),
     "geometry" AS (SELECT ST_Transform("polygon", 900913) AS "geometry", ST_Area("polygon"::GEOGRAPHY) AS "area" FROM "polygon"),
     "parameters" AS (
         SELECT "area" > 1000000 AS "use_geom_alt"
         FROM "geometry"
     )
SELECT r.*
      FROM "record_record" "r"
      WHERE ("record_date" >= '2000-01-01' AND "record_date" <= '2019-12-31')
        AND (
              (TRUE AND ST_Intersects((SELECT geometry FROM geometry), r.geom))
              OR (FALSE AND ST_Intersects((SELECT geometry FROM geometry), r.geom_alt))
          );

This results in the desired query plan.

QUERY PLAN
Index Scan using record_record_geom_idx on record_record r  (cost=0.44..5754.90 rows=142 width=4734) (actual time=0.076..53.885 rows=18100 loops=1)
    Index Cond: (geom && $1)
    "Filter: ((record_date >= '2000-01-01'::date) AND (record_date <= '2019-12-31'::date) AND st_intersects($1, geom))"
    Rows Removed by Filter: 6620
    CTE geometry
        ->  Result  (cost=0.00..0.01 rows=1 width=40) (actual time=0.001..0.001 rows=1 loops=1)
    InitPlan 2 (returns $1)
        ->  CTE Scan on geometry  (cost=0.00..0.02 rows=1 width=32) (actual time=0.003..0.004 rows=1 loops=1)
Planning Time: 0.370 ms
Execution Time: 54.783 ms

In Conclusion

I would like know to if what I want to achieve is at all possible?

Alternatively, I realise I may be asking the wrong question and I would be interested in hearing about alternative approaches.


问:
Does MSVC ASan Support x64 builds?
I'm trying to run my program through ASan on MSVC (fsantitize=address) and I keep getting runtime errors from the ASan dlls. Has anyone been able to get ASan working with runtime set to MDd and platform set to x64?

Windows 11
MSVC 2019 - 16.11.2

Title: Does MSVC ASan Support x64 builds?


问:
import React, { useState } from 'react'; ^^^^^^ SyntaxError: Cannot use import statement outside a module
I want to import my react component in my node but it throwing an error. It imports react component after that it show error in react component when there is import a file using common type.
following is my node js code.
`

```<code>import { createRequire } from "module";
const require = createRequire(
    import.meta.url);

const http= require ("http");
const express= require("express");
const cors= require("cors");
const socketIO=require("socket.io");
const { user } = require("../src/component/Join/Join.js");
const app=express();
const port=4500 || process.env.PORT;

const users=[{}];

app.use(cors());

app.get("/",(req,res)=>{
    res.send("Hello detective its working now");
})

const server=http.createServer(app);
const io=socketIO(server);

io.on("connection",(socket)=>{
    console.log("New Connection");
    socket.on("Joined",({user})=>{ //  on means data receive--user destructring and receiving
        users[socket.id]=user;                           //data from chat user
        console.log(`${user} has joined`);
        socket.broadcast.emit("userJoined",{user:"Admin",message:`${user[socket.id]} has joined`})    // broadcast means khud ko  chhod ke dusre users ko
        socket.emit("welcome",{user:"Admin",message:`Welcome to the chat,${user[socket.id]}`})
    })

    socket.on("message",({message,id})=>{
        io.emit("sendMessage",{user:user[id],message,id})
    })

socket.on("disconnect",()=>{
    socket.broadcast.emit("leave",{user:"Admin",message:`${user[socket.id]} has left`})
    console.log("User left");
});

});
server.listen(port,()=>{
    console.log(`server is running on  http://localhost:${port}`);
})
</code>```

`

and I am trying to connect with react following code
`

```<code>import React, { useState } from 'react';
import "./Join.css";
import logo from "../../Images/logo.png";
import { Link } from 'react-router-dom';

let user;
const SendUser=()=>{
    user=document.getElementById("Joininput").value;
    document.getElementById("Joininput").value ="";
}

const Join = () => {
    const [name, setname] = useState("");
  return (
    <div className='Joincontainer'>
        <div className="Joinpage">
            <img src={logo} alt="logo" />
            <h1>Mongo Chat</h1>
            <input onChange={(e)=>setname(e.target.value)} type="text" id="Joininput" placeholder='Enter Your Name'/>
            <Link onClick={(e)=>!name ? e.preventDefault():null} to="/chat"> <button onClick={SendUser} className='Joinbtn'>Join In</button></Link>
        </div>
    </div>
  )
}

export {Join}
export {user}
</code>```

`

but it throws following error in node.

`

```<code>import React, { useState } from 'react';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at file:///D:/Lakshman/Js%20Code/Chat_App/cchat/server/index.js:10:18
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
</code>```

`

I want to it use module and common export in same file.

Body:
I want to import my react component in my node but it throwing an error. It imports react component after that it show error in react component when there is import a file using common type.
following is my node js code.
`

import { createRequire } from "module";
const require = createRequire(
    import.meta.url);

const http= require ("http");
const express= require("express");
const cors= require("cors");
const socketIO=require("socket.io");
const { user } = require("../src/component/Join/Join.js");
const app=express();
const port=4500 || process.env.PORT;

const users=[{}];

app.use(cors());

app.get("/",(req,res)=>{
    res.send("Hello detective its working now");
})

const server=http.createServer(app);
const io=socketIO(server);

io.on("connection",(socket)=>{
    console.log("New Connection");
    socket.on("Joined",({user})=>{ //  on means data receive--user destructring and receiving
        users[socket.id]=user;                           //data from chat user
        console.log(`${user} has joined`);
        socket.broadcast.emit("userJoined",{user:"Admin",message:`${user[socket.id]} has joined`})    // broadcast means khud ko  chhod ke dusre users ko
        socket.emit("welcome",{user:"Admin",message:`Welcome to the chat,${user[socket.id]}`})
    })

    socket.on("message",({message,id})=>{
        io.emit("sendMessage",{user:user[id],message,id})
    })

socket.on("disconnect",()=>{
    socket.broadcast.emit("leave",{user:"Admin",message:`${user[socket.id]} has left`})
    console.log("User left");
});

});
server.listen(port,()=>{
    console.log(`server is running on  http://localhost:${port}`);
})

`

and I am trying to connect with react following code
`

import React, { useState } from 'react';
import "./Join.css";
import logo from "../../Images/logo.png";
import { Link } from 'react-router-dom';

let user;
const SendUser=()=>{
    user=document.getElementById("Joininput").value;
    document.getElementById("Joininput").value ="";
}

const Join = () => {
    const [name, setname] = useState("");
  return (

Mongo Chat

            <input onChange={(e)=>setname(e.target.value)} type="text" id="Joininput" placeholder='Enter Your Name'/>
            <Link onClick={(e)=>!name ? e.preventDefault():null} to="/chat"> <button onClick={SendUser} className='Joinbtn'>Join In</button></Link>

  )
}

export {Join}
export {user}

`

but it throws following error in node.

`

import React, { useState } from 'react';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at file:///D:/Lakshman/Js%20Code/Chat_App/cchat/server/index.js:10:18
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)

`

I want to it use module and common export in same file.


问:
How to add multiple different events on single button in react js. But when onMouseDown function runs onClick should not work like below code

function Demo() {
  function onClick() {
    console.log("I am from onClick")
  }

  function onMouseDown() {
    console.log("I am from onMouseDown")
  }

  function onMouseUp() {
    console.log("I am from onMouseUp")
  }
  return (<>
     <button onCLick={onClick} onMouseDown={onMouseDown} onMouseUp={onMouseUp}>Click Me</button>   </>
  )
}
```

When I mouse down it should give me "I am from onMouseUp" but should not give me "I am from onClick".

Also, when I mouseup it should give me "I am from onMouseDown".

Body:
function Demo() {
  function onClick() {
    console.log("I am from onClick")
  }

  function onMouseDown() {
    console.log("I am from onMouseDown")
  }

  function onMouseUp() {
    console.log("I am from onMouseUp")
  }
  return (<>
     <button onCLick={onClick} onMouseDown={onMouseDown} onMouseUp={onMouseUp}>Click Me</button>   </>
  )
}

When I mouse down it should give me "I am from onMouseUp" but should not give me "I am from onClick".

Also, when I mouseup it should give me "I am from onMouseDown".


问:
I wanted to know why it showing error like this or is that goint to make any problem for me after deployment
```<code>warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works
Error: Aborted because ./pages/login.js is not accepted
Update propagation: ./pages/login.js -> ./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?absolutePagePath=D%3A%5CJimmy%5Cwork%5Cclient%5Cpages%5Clogin.js&page=%2Flogin!
    at applyHandler (http://localhost:3000/_next/static/chunks/webpack.js?ts=1670508348862:881:31)
    at http://localhost:3000/_next/static/chunks/webpack.js?ts=1670508348862:564:21
    at Array.map (<anonymous>)
</code>```

I wantes to know more about this error and how i can solve this error

Body:
warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works
Error: Aborted because ./pages/login.js is not accepted
Update propagation: ./pages/login.js -> ./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?absolutePagePath=D%3A%5CJimmy%5Cwork%5Cclient%5Cpages%5Clogin.js&page=%2Flogin!
    at applyHandler (http://localhost:3000/_next/static/chunks/webpack.js?ts=1670508348862:881:31)
    at http://localhost:3000/_next/static/chunks/webpack.js?ts=1670508348862:564:21
    at Array.map (<anonymous>)

I wantes to know more about this error and how i can solve this error


问:
Flutter FireStore - initialize instance after clearing persistence
I am calling await FirebaseFirestore.instance.clearPersistence(); in-order to clear the cached data after a user signed out.

Per the documentation, you only call it after terminating the firestore session.

But after trying to retrieve the data again after login, I am getting an error:

"The client has already been terminated"

EDIT: THIS HAPPENS ONLY ON FLUTTER WEB. On flutter mobile (Tested on Android) it is working fine.

So how can I initialize the instance after terminating it?

```<code>await FirebaseFirestore.instance.terminate();
await FirebaseFirestore.instance.clearPersistence();
</code>```

Body:
I am calling await FirebaseFirestore.instance.clearPersistence(); in-order to clear the cached data after a user signed out.

Per the documentation, you only call it after terminating the firestore session.

But after trying to retrieve the data again after login, I am getting an error:

"The client has already been terminated"

EDIT: THIS HAPPENS ONLY ON FLUTTER WEB. On flutter mobile (Tested on Android) it is working fine.

So how can I initialize the instance after terminating it?

await FirebaseFirestore.instance.terminate();
await FirebaseFirestore.instance.clearPersistence();


问:
gitlab-runner: docker-in-docker use local cache as well as gitlab registry
I'm using Gitlab CI with a gitlab-runner installed on our server. We can then assume that each jobs will be executed on the same machine.

build: build image image and push as image:git_commit

test: pull image:git_commit and test

tag: pull image:git_commit, tag it to latest and push to image:latest

For performance I set cache_from: image:latest in my docker-compose configuration. However, it seems that each jobs is executed in a separate gitlab-runner docker instance so it does not actually keep images. In practice, this makes the runner to download image each time even though it was previously built on this very machine.

My question is:

how can I setup my host to keep image:latest cached (and up-to-date) and share it with my runner instances?

Thanks

Edit: I set pull_policy = "if-not-present" in my /etc/gitlab-runner/config.toml, the fullpath image is present in my host e.g. registry.gitlab.com/user/project/image:latest is listed in docker images


问:
creation of tab menu on drupal 7
I tried to create a tab menu ,  but the call back is empty , the respond of var_dump is

array(4) { ["admin/config/cb/tabs"]=> array(3) { ["title"]=> string(15) "Create Menu Tab" ["page callback"]=> string(13) "testpage_tab1" ["access callback"]=> bool(true) } ["admin/config/cb/tabs/first"]=> array(4) { ["title"]=> string(9) "First Tab" ["type"]=> int(140) ["page callback"]=> string(13) "testpage_tab1" ["access callback"]=> bool(true) } ["admin/config/cb/tabs/second"]=> array(4) { ["title"]=> string(10) "Second Tab" ["type"]=> int(132) ["page callback"]=> string(13) "testpage_tab2" ["access callback"]=> bool(true) } ["admin/config/cb/tabs/third"]=> array(4) { ["title"]=> string(9) "Third Tab" ["type"]=> int(132) ["page callback"]=> string(13) "testpage_tab3" ["access callback"]=> bool(true) } }
; my functions was

```<code>function phponwebsites_menu() {

    $items['admin/config/cb/tabs'] = array(
      'title' => t('Create Menu Tab'),
      'page callback' => 'testpage_tab1',
      'access callback' => TRUE,
    );

    $items['admin/config/cb/tabs/first'] = array(
      'title' => t('First Tab'),
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'page callback' => 'testpage_tab1',
      'access callback' => TRUE,
    );

    $items['admin/config/cb/tabs/second'] = array(
      'title' => t('Second Tab'),
      'type' => MENU_LOCAL_TASK,
      'page callback' => 'testpage_tab2',
      'access callback' => TRUE,
    );

    $items['admin/config/cb/tabs/third'] = array(
      'title' => t('Third Tab'),
      'type' => MENU_LOCAL_TASK,
      'page callback' => 'testpage_tab3',
      'access callback' => TRUE,
    );

    return $items;
  }

  /**
   * Implement testpage_tab1()
   */
  function testpage_tab1() {
    $str = t('Hi this is first tab');
    return $str;
  }

  /**
   * Implement testpage_tab2()
   */
  function testpage_tab2() {
    $str = t('Hi this is second tab');
    return $str;
  }

  /**
   * Implement testpage_tab3()
   */
  function testpage_tab3() {
    $str = t('Hi this is third tab');
    return $str;
  }

/**
 * Implements hook_block_info().
 */
function cab_order_block_info()
{
    $blocks['cab_order'] = [
        'info' => t('Order form')
    ];
    return $blocks;
}
</code>```

I think the error is in the links I put in $items[]

```<code>$items['admin/config/cabformation/tabs/third']
</code>```

Title: creation of tab menu on drupal 7

Body:
I tried to create a tab menu ,  but the call back is empty , the respond of var_dump is

array(4) { ["admin/config/cb/tabs"]=> array(3) { ["title"]=> string(15) "Create Menu Tab" ["page callback"]=> string(13) "testpage_tab1" ["access callback"]=> bool(true) } ["admin/config/cb/tabs/first"]=> array(4) { ["title"]=> string(9) "First Tab" ["type"]=> int(140) ["page callback"]=> string(13) "testpage_tab1" ["access callback"]=> bool(true) } ["admin/config/cb/tabs/second"]=> array(4) { ["title"]=> string(10) "Second Tab" ["type"]=> int(132) ["page callback"]=> string(13) "testpage_tab2" ["access callback"]=> bool(true) } ["admin/config/cb/tabs/third"]=> array(4) { ["title"]=> string(9) "Third Tab" ["type"]=> int(132) ["page callback"]=> string(13) "testpage_tab3" ["access callback"]=> bool(true) } }
; my functions was

function phponwebsites_menu() {

    $items['admin/config/cb/tabs'] = array(
      'title' => t('Create Menu Tab'),
      'page callback' => 'testpage_tab1',
      'access callback' => TRUE,
    );

    $items['admin/config/cb/tabs/first'] = array(
      'title' => t('First Tab'),
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'page callback' => 'testpage_tab1',
      'access callback' => TRUE,
    );

    $items['admin/config/cb/tabs/second'] = array(
      'title' => t('Second Tab'),
      'type' => MENU_LOCAL_TASK,
      'page callback' => 'testpage_tab2',
      'access callback' => TRUE,
    );

    $items['admin/config/cb/tabs/third'] = array(
      'title' => t('Third Tab'),
      'type' => MENU_LOCAL_TASK,
      'page callback' => 'testpage_tab3',
      'access callback' => TRUE,
    );

    return $items;
  }

  /**
   * Implement testpage_tab1()
   */
  function testpage_tab1() {
    $str = t('Hi this is first tab');
    return $str;
  }

  /**
   * Implement testpage_tab2()
   */
  function testpage_tab2() {
    $str = t('Hi this is second tab');
    return $str;
  }

  /**
   * Implement testpage_tab3()
   */
  function testpage_tab3() {
    $str = t('Hi this is third tab');
    return $str;
  }

/**
 * Implements hook_block_info().
 */
function cab_order_block_info()
{
    $blocks['cab_order'] = [
        'info' => t('Order form')
    ];
    return $blocks;
}

I think the error is in the links I put in $items[]

$items['admin/config/cabformation/tabs/third']


问:
VB code to create slides based on number of audio files, and insert random background images
I am trying to create a VB Code that will create number of slides based on the audio files in the folder.
Then, I want to insert random background images from the folder.
I have written this code but it doesn't work.

```<code>    Sub CreatePowerPointSlides()

    'Declare variables
    Dim pptApp As Object
    Dim pptPres As Object
    Dim pptSlide As Object
    Dim audioFiles As String
    Dim audioFile As String
    Dim imageFiles As String
    Dim imageFile As String

    'Create a new instance of PowerPoint and open the presentation
    Set pptApp = CreateObject("PowerPoint.Application")
    pptApp.Visible = True
    Set pptPres = pptApp.Presentations.Add

    'Get a list of all audio files in the folder
    audioFiles = Dir("C:\Users\audio\*.mp3")

    'Iterate through each audio file in the folder
    Do While audioFiles <> ""
        audioFile = audioFiles

        'Create a new slide in PowerPoint and add the audio file
        Set pptSlide = pptPres.Slides.Add(pptPres.Slides.Count + 1, 11, ppViewSlide)
        pptSlide.Shapes.AddMediaObject2 FileName:=audioFile, LinkToFile:=msoFalse,
        SaveWithDocument:=msoTrue

        'Get a list of all image files in the folder
        imageFiles = Dir("C:\Users\user1\Pictures\ImageBackground\Nature\*.jpg")

        'Choose a random image file from the folder
        Randomize
        imageFile = "C:\Users\user1\Pictures\ImageBackground\Nature\" &
        Split(imageFiles, vbNewLine)(Int(Rnd() *
        UBound(Split(imageFiles, vbNewLine))))

        'Add the image file as the background of the slide
        pptSlide.FollowMasterBackground = msoFalse
        pptSlide.Background.Fill.UserPicture PictureFile:=imageFile

        'Get the next audio file in the folder
        audioFiles = Dir()
    Loop

    pptApp.ActiveWindow.View.Type = ppViewSlide

    End Sub

</code>```

It doesn't even create one slide.

Body:
I am trying to create a VB Code that will create number of slides based on the audio files in the folder.
Then, I want to insert random background images from the folder.
I have written this code but it doesn't work.

    Sub CreatePowerPointSlides()

    'Declare variables
    Dim pptApp As Object
    Dim pptPres As Object
    Dim pptSlide As Object
    Dim audioFiles As String
    Dim audioFile As String
    Dim imageFiles As String
    Dim imageFile As String

    'Create a new instance of PowerPoint and open the presentation
    Set pptApp = CreateObject("PowerPoint.Application")
    pptApp.Visible = True
    Set pptPres = pptApp.Presentations.Add

    'Get a list of all audio files in the folder
    audioFiles = Dir("C:\Users\audio\*.mp3")

    'Iterate through each audio file in the folder
    Do While audioFiles <> ""
        audioFile = audioFiles

        'Create a new slide in PowerPoint and add the audio file
        Set pptSlide = pptPres.Slides.Add(pptPres.Slides.Count + 1, 11, ppViewSlide)
        pptSlide.Shapes.AddMediaObject2 FileName:=audioFile, LinkToFile:=msoFalse,
        SaveWithDocument:=msoTrue

        'Get a list of all image files in the folder
        imageFiles = Dir("C:\Users\user1\Pictures\ImageBackground\Nature\*.jpg")

        'Choose a random image file from the folder
        Randomize
        imageFile = "C:\Users\user1\Pictures\ImageBackground\Nature\" &
        Split(imageFiles, vbNewLine)(Int(Rnd() *
        UBound(Split(imageFiles, vbNewLine))))

        'Add the image file as the background of the slide
        pptSlide.FollowMasterBackground = msoFalse
        pptSlide.Background.Fill.UserPicture PictureFile:=imageFile

        'Get the next audio file in the folder
        audioFiles = Dir()
    Loop

    pptApp.ActiveWindow.View.Type = ppViewSlide

    End Sub

It doesn't even create one slide.


问:
cron.schedule doesn't send the function sendApod()
So i'm having this problem, i'm trying to make a discord.js bot sent the NASA Astronomy picture of the day every day at 2PM to a specific channel, and it worked with setIntervenal, but once i switched to cron it simply refuses to work.

Here's the code snippet:

```<code>
async function sendApod() {
    try {
        const response = await axios.get(
            `https://api.nasa.gov/planetary/apod?api_key=${api.NASA_API_KEY}`
        );

        // Create a Discord message embed with the APOD data
        const embed = new Discord.MessageEmbed()
            .setTitle(response.data.title)
            .setImage(response.data.url)
            .setDescription(response.data.explanation)
            .setColor('2f31363136');

        // Send the message to the desired Discord channel
        const channel = client.channels.cache.get(DISCORD_CHANNEL_ID);
        channel.send({ embeds: [embed] });
    } catch (error) {
        console.error(error);
    }
}

// Create a cron job that will run the sendApod function at 2 PM every day
cron.schedule('0 14 * * *', sendApod);
</code>```

Can someone help me figure it out? cheers!

I thought it could be a one off error, so i tried changing the minutes etc. but still nothing happened.

Body:
So i'm having this problem, i'm trying to make a discord.js bot sent the NASA Astronomy picture of the day every day at 2PM to a specific channel, and it worked with setIntervenal, but once i switched to cron it simply refuses to work.

Here's the code snippet:

async function sendApod() {
    try {
        const response = await axios.get(
            `https://api.nasa.gov/planetary/apod?api_key=${api.NASA_API_KEY}`
        );

        // Create a Discord message embed with the APOD data
        const embed = new Discord.MessageEmbed()
            .setTitle(response.data.title)
            .setImage(response.data.url)
            .setDescription(response.data.explanation)
            .setColor('2f31363136');

        // Send the message to the desired Discord channel
        const channel = client.channels.cache.get(DISCORD_CHANNEL_ID);
        channel.send({ embeds: [embed] });
    } catch (error) {
        console.error(error);
    }
}

// Create a cron job that will run the sendApod function at 2 PM every day
cron.schedule('0 14 * * *', sendApod);

Can someone help me figure it out? cheers!

I thought it could be a one off error, so i tried changing the minutes etc. but still nothing happened.


问:
How to group an array by its parent_id? (php / laravel)
I'm currently assigned to task in which I will need to group raw array data. The data is very simple and it has root_id to determine the parent of the element. The task is to group it dynamically based from DB data.

Now, I already tried constructing draft flowchart but I always end up problematic for nested child. I would kindly ask of your help, how to make this possible in PHP or Laravel in a good performance way.

Below in the left, is the raw data array and the right side is the expected grouped array-object.

$data = [
    {
        id: 1
        root: null
    },
    {
        id: 2
        root: null
    },
    {
        id: 3
        root: 1
    },
    {
        id: 4
        root: 2
    },
    {
        id: 5
        root: 3
    },
    {
        id: 6
        root: 5
    },
];

$expectedGroupResult = [
    {
        id: 1
        root: null
        child: [
            {
                id: 3,
                root: 1
                child: [
                    {
                        id: 5,
                        root: 3,
                        child: [
                            {
                                id: 6,
                                root: 5,
                                child: [],
                            },
                        ]
                    },
                ],
            },
        ]
    },
    {
        id: 2,
        root: null,
        child: [
            {
                id: 4,
                root: 2,
                child: []
            },
        ],
    }
];```


问:
Get the text locking algorithm from the result
I want to understand the algorithm of this locking using the normal and locked text of the same text

Example:
My Text : Hello World
My Encrypted Text : DWC$%3v6tvegT54gt3

Is it possible that I can get the algorithm of this encryption

For example, instead of using (Hello World), I should use (Goodbye World).
and get the locked text with the same algorithm

Example:
My Text : Hello World
My Encrypted Text : DWC$%3v6tvegT54gt3

Example:
My Text : GoodBy World
My Encrypted Text : CR$F%#FRTCERt546456456nmth

I searched many sites and videos but could not find anything

I can't even get my point across properly to the Google search engine


问:
Copying the y-lim of a plot and use this on other plot
I am trying to make a combined plot with the same y-limits. In here there are two facetwrapped boxplots. I would normally set the y-limits manually at the same level, but this messed up the medians and thus the direction of the line in the left plot (see image). Therefore the scales in this plot are set scale = "free_y"

My question: Is there a way to copy the y-axis from a plot, and use this exact scale on another plot? / What are the alternatives to find the exact y-limits a boxplot uses?

For now I have tried obtain the y-limits of the left facetwrapped plot (see image), and use this information to manually set the same y-limit on the right facetwrapped plot(see image) (This plot I am able to set y-limits manually without messing up the plot).

The combined plot with needed simular y-axis (name left plot = AbundancePlotVH , name rightplot = boxplotVHAbundance. I would like to make the y-axis on the rightplot the same as the one of the leftplot

To obtain the exact Y-limits I have tried:

par("usr") but this gave me 0 1 0 1 values

Find the min and max value of the data from the leftplot (see image) through the code below

```<code>Range <- range(c(totalVH$MeanAbundance))
Range
</code>```

This helped, but did not make the axis exactly the same.
I've been searching for alternative solutions, but cant seem to find one that works for me..

Here the code I use for my plot. It combines 2 individual facetwrapped boxplots (AbundancePlotVH & boxplotVHAbundance)

```<code>prow<- plot_grid(AbundancePlotVH + theme(legend.position="none"), boxplotVHAbundance +  theme(legend.position="none", axis.text.y = element_blank(), axis.ticks.y = element_blank(),
VH<- plot_grid(title, prow, legend, ncol =  1, rel_heights = c(1, 10), axis = "l", align = "v")
VH
</code>```

Body:
I am trying to make a combined plot with the same y-limits. In here there are two facetwrapped boxplots. I would normally set the y-limits manually at the same level, but this messed up the medians and thus the direction of the line in the left plot (see image). Therefore the scales in this plot are set scale = "free_y"

My question: Is there a way to copy the y-axis from a plot, and use this exact scale on another plot? / What are the alternatives to find the exact y-limits a boxplot uses?

For now I have tried obtain the y-limits of the left facetwrapped plot (see image), and use this information to manually set the same y-limit on the right facetwrapped plot(see image) (This plot I am able to set y-limits manually without messing up the plot).

The combined plot with needed simular y-axis (name left plot = AbundancePlotVH , name rightplot = boxplotVHAbundance. I would like to make the y-axis on the rightplot the same as the one of the leftplot

To obtain the exact Y-limits I have tried:

par("usr") but this gave me 0 1 0 1 values

Find the min and max value of the data from the leftplot (see image) through the code below

Range <- range(c(totalVH$MeanAbundance))
Range

This helped, but did not make the axis exactly the same.
I've been searching for alternative solutions, but cant seem to find one that works for me..

Here the code I use for my plot. It combines 2 individual facetwrapped boxplots (AbundancePlotVH & boxplotVHAbundance)

prow<- plot_grid(AbundancePlotVH + theme(legend.position="none"), boxplotVHAbundance +  theme(legend.position="none", axis.text.y = element_blank(), axis.ticks.y = element_blank(),
VH<- plot_grid(title, prow, legend, ncol =  1, rel_heights = c(1, 10), axis = "l", align = "v")
VH


问:
Great expectations: why does profiler throws error up to 0.15.18 but not later?
This dataframe:

```<code>df = pd.DataFrame(
    [
        {"name": "Ross", "dob": pd.Timestamp("1967-10-18")},
        {"name": "Rachel", "dob": pd.Timestamp("1968-05-05")},
        {"name": "Phoebe", "dob": None},
    ]
)
</code>```

Would cause the UserConfigurableProfiler to fail when using great_expectations <= 0.15.18. For example, for the above dataframe, the error is the following:

```<code>File ~/.local/lib/python3.9/site-packages/great_expectations/execution_engine/execution_engine.py:397, in ExecutionEngine.resolve_metrics(self, metrics_to_resolve, metrics, runtime_configuration)
    393         resolved_metrics[metric_to_resolve.id] = metric_fn(
    394             **metric_provider_kwargs
    395         )
    396     except Exception as e:
--> 397         raise ge_exceptions.MetricResolutionError(
    398             message=str(e), failed_metrics=(metric_to_resolve,)
    399         )
    401 if len(metric_fn_bundle) > 0:
    402     try:
    403         # an engine-specific way of computing metrics together
    404         # NOTE: DH 20220328: This is where we can introduce the Batch Metrics Store (BMS)

MetricResolutionError: Column values, min_value, and max_value must either be None or of the same type.
</code>```

But when using great_expectations >= 0.15.19, the profiler does not throw an error anymore. I don't know if it is silently swallowing the exception somehow. I went through the source code but I couldn't find anything different between 0.15.18 and 0.15.19 for example.

Steps to reproduce:

pip install great_expectations==0.15.18

```<code>import great_expectations
from great_expectations.core.batch import RuntimeBatchRequest
from great_expectations.checkpoint.checkpoint import SimpleCheckpoint
from great_expectations.data_context import BaseDataContext
from great_expectations.data_context.types.base import (
    DataContextConfig,
    FilesystemStoreBackendDefaults,
)
from great_expectations.profile.user_configurable_profiler  import UserConfigurableProfiler, ExpectationConfiguration
import os
import pandas as pd
</code>```
```<code>data_context_config = DataContextConfig( store_backend_defaults=FilesystemStoreBackendDefaults(root_directory=f'{os.getcwd()}/ge_gen_dir_2/') )
context = BaseDataContext(project_config = data_context_config)
</code>```
```<code>expectation_suite_name = 'expectation_suite_yellow_tripdata_02'

suite = context.create_expectation_suite(
    expectation_suite_name = expectation_suite_name,
    overwrite_existing=True
)
</code>```
```<code>df = pd.DataFrame(
    [
        {"name": "Ross", "dob": pd.Timestamp("1967-10-18")},
        {"name": "Rachel", "dob": pd.Timestamp("1968-05-05")},
        {"name": "Phoebe", "dob": None},
    ]
)
batch_request = RuntimeBatchRequest(
    datasource_name= 'dummy_datasource',
    data_connector_name= "runtime_connector",
    data_asset_name='yellow_tripdata_01',
    batch_identifiers={
        "run_id": 'yellow_tripdata_01',
    },
    runtime_parameters={"batch_data": df}
)
</code>```
```<code>datasource_config = {
    'name': f'dummy_datasource',
    'class_name': 'Datasource',
    'module_name': 'great_expectations.datasource',
    'execution_engine': {
        'module_name': 'great_expectations.execution_engine',
        'class_name': 'PandasExecutionEngine',
    },
    'data_connectors': {
        'runtime_connector': {
            'class_name': 'RuntimeDataConnector',
            'batch_identifiers': ['run_id'],
        },
    },
}

context.add_datasource(**datasource_config)
</code>```
```<code>validator = context.get_validator(batch_request=batch_request, expectation_suite_name=expectation_suite_name)
</code>```
```<code>profiler = UserConfigurableProfiler(
    profile_dataset=validator,
    not_null_only=False,
    # when set to True, no expectations at column level will be generated
    table_expectations_only=False,
    ignored_columns=[],
    # Here you can provide a list of expectations to exclude from the profiler
    excluded_expectations=[],
)
</code>```
```<code>profiler.build_suite()
</code>```

If you want to test the same for the lib version that does not throw an error, just install the later version, for example:

pip install great_expectations==0.15.21

Please help!

Body:
This dataframe:

df = pd.DataFrame(
    [
        {"name": "Ross", "dob": pd.Timestamp("1967-10-18")},
        {"name": "Rachel", "dob": pd.Timestamp("1968-05-05")},
        {"name": "Phoebe", "dob": None},
    ]
)

Would cause the UserConfigurableProfiler to fail when using great_expectations <= 0.15.18. For example, for the above dataframe, the error is the following:

File ~/.local/lib/python3.9/site-packages/great_expectations/execution_engine/execution_engine.py:397, in ExecutionEngine.resolve_metrics(self, metrics_to_resolve, metrics, runtime_configuration)
    393         resolved_metrics[metric_to_resolve.id] = metric_fn(
    394             **metric_provider_kwargs
    395         )
    396     except Exception as e:
--> 397         raise ge_exceptions.MetricResolutionError(
    398             message=str(e), failed_metrics=(metric_to_resolve,)
    399         )
    401 if len(metric_fn_bundle) > 0:
    402     try:
    403         # an engine-specific way of computing metrics together
    404         # NOTE: DH 20220328: This is where we can introduce the Batch Metrics Store (BMS)

MetricResolutionError: Column values, min_value, and max_value must either be None or of the same type.

But when using great_expectations >= 0.15.19, the profiler does not throw an error anymore. I don't know if it is silently swallowing the exception somehow. I went through the source code but I couldn't find anything different between 0.15.18 and 0.15.19 for example.

Steps to reproduce:

pip install great_expectations==0.15.18

import great_expectations
from great_expectations.core.batch import RuntimeBatchRequest
from great_expectations.checkpoint.checkpoint import SimpleCheckpoint
from great_expectations.data_context import BaseDataContext
from great_expectations.data_context.types.base import (
    DataContextConfig,
    FilesystemStoreBackendDefaults,
)
from great_expectations.profile.user_configurable_profiler  import UserConfigurableProfiler, ExpectationConfiguration
import os
import pandas as pd

data_context_config = DataContextConfig( store_backend_defaults=FilesystemStoreBackendDefaults(root_directory=f'{os.getcwd()}/ge_gen_dir_2/') )
context = BaseDataContext(project_config = data_context_config)

expectation_suite_name = 'expectation_suite_yellow_tripdata_02'

suite = context.create_expectation_suite(
    expectation_suite_name = expectation_suite_name,
    overwrite_existing=True
)

df = pd.DataFrame(
    [
        {"name": "Ross", "dob": pd.Timestamp("1967-10-18")},
        {"name": "Rachel", "dob": pd.Timestamp("1968-05-05")},
        {"name": "Phoebe", "dob": None},
    ]
)
batch_request = RuntimeBatchRequest(
    datasource_name= 'dummy_datasource',
    data_connector_name= "runtime_connector",
    data_asset_name='yellow_tripdata_01',
    batch_identifiers={
        "run_id": 'yellow_tripdata_01',
    },
    runtime_parameters={"batch_data": df}
)

datasource_config = {
    'name': f'dummy_datasource',
    'class_name': 'Datasource',
    'module_name': 'great_expectations.datasource',
    'execution_engine': {
        'module_name': 'great_expectations.execution_engine',
        'class_name': 'PandasExecutionEngine',
    },
    'data_connectors': {
        'runtime_connector': {
            'class_name': 'RuntimeDataConnector',
            'batch_identifiers': ['run_id'],
        },
    },
}

context.add_datasource(**datasource_config)

validator = context.get_validator(batch_request=batch_request, expectation_suite_name=expectation_suite_name)

profiler = UserConfigurableProfiler(
    profile_dataset=validator,
    not_null_only=False,
    # when set to True, no expectations at column level will be generated
    table_expectations_only=False,
    ignored_columns=[],
    # Here you can provide a list of expectations to exclude from the profiler
    excluded_expectations=[],
)

profiler.build_suite()

If you want to test the same for the lib version that does not throw an error, just install the later version, for example:

pip install great_expectations==0.15.21

Please help!


问:
Serverless set cookie for AWS Api Gateway
It's my first question on Stackoverflow, normally I always found a solution here before Asking but not this time

I use integration lambda mode, not the proxy mode.

I am able to set a cookie from serverless but I don't want to have the cookie in the body of my response.

I do this in the serverless.yml to set the cookie:

  login:
    handler: functions/auth/login.handler
    events:
      - http:
          path: login
          method: post
          cors: true
          integration: lambda
          response:
            headers:
              Set-Cookie: integration.response.body.body
            statusCodes:
              200:
                pattern: '' # Default response method
              400:
                pattern: '.*"statusCode": 400,.*'
                template: $input.path("$.errorMessage")
              401:
                pattern: '.*"statusCode": 401,.*'
                template: $input.path("$.errorMessage")
              500:
                pattern: '.*"statusCode": 500,.*'
                template: $input.path("$.errorMessage")
```
<p>here is the code of my lambda function:</p>
<pre class="lang-js prettyprint-override"><code>/* login and return the jwt token infos and set the auth cookie */

import { ok, internalServerError, unAuthorized } from '../../lib/response.js';
import { login } from '../../lib/token.js';
import { logger } from '../../lib/logger.js';
import { authLambda } from '../../constants/constant.js';

export const handler = async (event) => {
  logger.info('START', authLambda.login);

  let responseObject;
  let date = new Date();
  date.setTime(+ date + (86400000)); // 24h

  try {
    const token = await login(event.body);

    if (token) {
      let cookie = 'auth='+token
      responseObject = ok(cookie);
    } else {
      responseObject = unAuthorized();
    }

    logger.info('END => ', authLambda.login, responseObject);

    return responseObject;
  } catch (e) {
    logger.error('ERROR', authLambda.login, e);
    return new Error(internalServerError(e));
  }
};

</code>```

So, I have this as the response of the request:

{
    "message": "Ok",
    "statusCode": 200,
    "body": "auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImJpbmN6YWttYXJ0aW40QGdtYWlsLmNvbSIsImlkIjoiOTUwNzI1YjAtODJlMy00Nzc0LWIwZDEtMWMxMTcyM2UzMTY3Iiwicm9sZSI6IkVuZ2luZWVyIiwiaWF0IjoxNjcwNDk0NjYzLCJleHAiOjE2NzA1ODEwNjN9.Y7X4AiVV84rCFLvuGTHbcyKMfZhpZuq3iWERzkHRZS0"
}
```
<p>But I only want to have this:</p>
<pre class="lang-json prettyprint-override"><code>{
    "message": "Ok",
    "statusCode": 200
}
</code>```

Thanks

Body:
It's my first question on Stackoverflow, normally I always found a solution here before Asking but not this time

I use integration lambda mode, not the proxy mode.

I am able to set a cookie from serverless but I don't want to have the cookie in the body of my response.

I do this in the serverless.yml to set the cookie:

  login:
    handler: functions/auth/login.handler
    events:
      - http:
          path: login
          method: post
          cors: true
          integration: lambda
          response:
            headers:
              Set-Cookie: integration.response.body.body
            statusCodes:
              200:
                pattern: '' # Default response method
              400:
                pattern: '.*"statusCode": 400,.*'
                template: $input.path("$.errorMessage")
              401:
                pattern: '.*"statusCode": 401,.*'
                template: $input.path("$.errorMessage")
              500:
                pattern: '.*"statusCode": 500,.*'
                template: $input.path("$.errorMessage")

here is the code of my lambda function:

/* login and return the jwt token infos and set the auth cookie */

import { ok, internalServerError, unAuthorized } from '../../lib/response.js';
import { login } from '../../lib/token.js';
import { logger } from '../../lib/logger.js';
import { authLambda } from '../../constants/constant.js';

export const handler = async (event) => {
  logger.info('START', authLambda.login);

  let responseObject;
  let date = new Date();
  date.setTime(+ date + (86400000)); // 24h

  try {
    const token = await login(event.body);

    if (token) {
      let cookie = 'auth='+token
      responseObject = ok(cookie);
    } else {
      responseObject = unAuthorized();
    }

    logger.info('END => ', authLambda.login, responseObject);

    return responseObject;
  } catch (e) {
    logger.error('ERROR', authLambda.login, e);
    return new Error(internalServerError(e));
  }
};

So, I have this as the response of the request:

{
    "message": "Ok",
    "statusCode": 200,
    "body": "auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImJpbmN6YWttYXJ0aW40QGdtYWlsLmNvbSIsImlkIjoiOTUwNzI1YjAtODJlMy00Nzc0LWIwZDEtMWMxMTcyM2UzMTY3Iiwicm9sZSI6IkVuZ2luZWVyIiwiaWF0IjoxNjcwNDk0NjYzLCJleHAiOjE2NzA1ODEwNjN9.Y7X4AiVV84rCFLvuGTHbcyKMfZhpZuq3iWERzkHRZS0"
}

But I only want to have this:

{
    "message": "Ok",
    "statusCode": 200
}

Thanks


问:
Python 3.9 SFTP connection
I'm trying to connect to SFTP server that is hosted locally (that's a POC ...). I'm using python 3.9 and the library paramiko.

The code I use is the following :

```<code>import paramiko
import sys

def main() -> None:
    hostkeys = paramiko.hostkeys.HostKeys("known_hosts.txt")

    ip = "127.0.0.1"
    username = "my_username"
    password = "my_password"

    # As per the paramiko doc. The host fingerprint is stored using the ed25519 algorithm
    hostFingerprint = hostkeys.lookup(ip)["ssh-ed25519"]

    try:
        tp = paramiko.Transport(ip, 22)
        tp.connect(username=username, password=password, hostkey=hostFingerprint)
        # Upload operations happening here...
        tp.close()
    except Exception as e:
        print(e)
    finally:
        return None

</code>```

The file known_hsts.txt has been generated via Powershell cmd : ssh-keyscan 127.0.0.1 > C:\Users\my_username\PycharmProjects\POC\known_hosts.txt.

When i run the script i don't understand why hostkeys.keys() == []

When i look at the file known_hosts.txt I see the different keys : ssh-rsa, ssh-ed25519, etc.

Title: Python 3.9 SFTP connection

Body:
I'm trying to connect to SFTP server that is hosted locally (that's a POC ...). I'm using python 3.9 and the library paramiko.

The code I use is the following :

import paramiko
import sys

def main() -> None:
    hostkeys = paramiko.hostkeys.HostKeys("known_hosts.txt")

    ip = "127.0.0.1"
    username = "my_username"
    password = "my_password"

    # As per the paramiko doc. The host fingerprint is stored using the ed25519 algorithm
    hostFingerprint = hostkeys.lookup(ip)["ssh-ed25519"]

    try:
        tp = paramiko.Transport(ip, 22)
        tp.connect(username=username, password=password, hostkey=hostFingerprint)
        # Upload operations happening here...
        tp.close()
    except Exception as e:
        print(e)
    finally:
        return None

The file known_hsts.txt has been generated via Powershell cmd : ssh-keyscan 127.0.0.1 > C:\Users\my_username\PycharmProjects\POC\known_hosts.txt.

When i run the script i don't understand why hostkeys.keys() == []

When i look at the file known_hosts.txt I see the different keys : ssh-rsa, ssh-ed25519, etc.


问:
Cannot update page-break-before when range contains paragraphs in a table
```<code>UpdateParagraphStyleRequest paragraphStyle = new UpdateParagraphStyleRequest()
        {
            Fields = "*",
            ParagraphStyle = new ParagraphStyle()
            {
                SpaceAbove = new Dimension() {
                    Magnitude = 0,
                    Unit = "PT" // https://developers.google.com/docs/api/reference/rest/v1/documents#unit
                },
                PageBreakBefore = null,
                NamedStyleType = "NORMAL_TEXT" // https://developers.google.com/docs/api/reference/rest/v1/documents#namedstyletype
            },
            Range = new Range() { StartIndex = 1, EndIndex = 398 }
        };
</code>```

The intention of the above code is, to do what can be done in the UI with the function "Remove space before paragraph". As you can see "Add page break before" is greyed out. The reason why it's greyed out, is because I am in this context inside a table. And inside a table this feature is apparently not available.

That's why the property "PageBreakBefore" is set to null, to indicate, that I don't want to update it. Because the range given in my code is also that table.

Nevertheless I am getting this error: "Cannot update page-break-before when the range contains paragraphs in a table".

Body:
UpdateParagraphStyleRequest paragraphStyle = new UpdateParagraphStyleRequest()
        {
            Fields = "*",
            ParagraphStyle = new ParagraphStyle()
            {
                SpaceAbove = new Dimension() {
                    Magnitude = 0,
                    Unit = "PT" // https://developers.google.com/docs/api/reference/rest/v1/documents#unit
                },
                PageBreakBefore = null,
                NamedStyleType = "NORMAL_TEXT" // https://developers.google.com/docs/api/reference/rest/v1/documents#namedstyletype
            },
            Range = new Range() { StartIndex = 1, EndIndex = 398 }
        };

The intention of the above code is, to do what can be done in the UI with the function "Remove space before paragraph". As you can see "Add page break before" is greyed out. The reason why it's greyed out, is because I am in this context inside a table. And inside a table this feature is apparently not available.

That's why the property "PageBreakBefore" is set to null, to indicate, that I don't want to update it. Because the range given in my code is also that table.

Nevertheless I am getting this error: "Cannot update page-break-before when the range contains paragraphs in a table".


问:
Sharepoint external data keeps on refreshing
We have a problem with our SharePoint external data. When I try to access the external data in my system it kept on searching, I cannot see any data. But when I tried the same from the server, I can access the data. I checked the log but I am not able to find anything. Does someone experience the same issue? Or Can you point me in the right direction? Thanks for your help in advance.
I checked the log and I checked in the admin center. But nothing was fishy.
image here</p>


问:
SSIS works on second run only
I have a computer I use to run several SSIS jobs from a vb.net desktop app.  All the jobs worked the second time I ran them which was annoying and so I migrated it to a new computer. That didn't fix it, that is, the jobs still only worked the second time I ran them.  See the code below.

```<code>Dim messages As New List(Of String)
        Dim x As OperationMessageCollection

 Try
        x = ssisCatalog.Executions(executionIdentifier).Messages

    Catch ex As Exception
        wait(5)
    End Try

    Try
        For Each message As OperationMessage In ssisCatalog.Executions(executionIdentifier).Messages
            messages.Add(message.MessageType & ": " + message.Message)
        Next
    Catch ex As Exception
        messages.Add("sync error.  The data might be in the db but the ssis process took too long to tell me")
    End Try
    Return messages
</code>```

I noticed that ssis required two runs before it gave messages, The first try blocked addressed that by adding five seconds and giving SQL more time to produce messages.

I've been using the same code to run these jobs for several years.  The packages are in ssisdb project folder on SQL Server 15.0.2095.3 and the destination DB is the same version.  The SSIS service is running prior to execution.  They are simple packages, moving some tab delimited text from my local system into a production SQL DB.

After running I check the execution messages for the word 'fail', but that word isn't in there and so, historically, that meant the package ran without failure.

Title: SSIS works on second run only

Body:
I have a computer I use to run several SSIS jobs from a vb.net desktop app.  All the jobs worked the second time I ran them which was annoying and so I migrated it to a new computer. That didn't fix it, that is, the jobs still only worked the second time I ran them.  See the code below.

Dim messages As New List(Of String)
        Dim x As OperationMessageCollection

 Try
        x = ssisCatalog.Executions(executionIdentifier).Messages

    Catch ex As Exception
        wait(5)
    End Try

    Try
        For Each message As OperationMessage In ssisCatalog.Executions(executionIdentifier).Messages
            messages.Add(message.MessageType & ": " + message.Message)
        Next
    Catch ex As Exception
        messages.Add("sync error.  The data might be in the db but the ssis process took too long to tell me")
    End Try
    Return messages

I noticed that ssis required two runs before it gave messages, The first try blocked addressed that by adding five seconds and giving SQL more time to produce messages.

I've been using the same code to run these jobs for several years.  The packages are in ssisdb project folder on SQL Server 15.0.2095.3 and the destination DB is the same version.  The SSIS service is running prior to execution.  They are simple packages, moving some tab delimited text from my local system into a production SQL DB.

After running I check the execution messages for the word 'fail', but that word isn't in there and so, historically, that meant the package ran without failure.


问:
Testing a react-native component with jest
I'm working on a react-native project and I want to do some testing on it using the testing-library for react-native and jest. The issue is that I cannot render components that contain the Pressable component from react-native. Here is the component that im trying to render:

```<code>import React from 'react'
import { View, Text, Pressable } from 'react-native'
export default function FilteringOptions() {

    return (
        <View style={{ flexDirection: 'row' }}>
            <Pressable>
                <Text style={{ fontSize: 24, paddingLeft: 10 }}>{'\u29BF'} All </Text>
            </Pressable>
            <Pressable>
                <Text style={{ fontSize: 24, paddingLeft: 10 }}>{'\u29BF'} Finance  </Text>
            </Pressable>
            <Pressable>
                <Text style={{ fontSize: 24, paddingLeft: 10 }}>{'\u29BF'} Health</Text>
            </Pressable>
        </View>
    );
}

</code>```

Here is the test case in jest:

```<code>test('Testing if FilteringOptions renders', () => {
    render(<FilteringOptions />);
    expect(screen.toJSON()).toMatchSnapshot();
});
</code>```

And here is the error im getting:

```<code>
  console.error
    Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
</code>```

Besides this jest also tells me that this error occurs in the  component and the test fails cause there is a:

```<code>TypeError: Cannot read properties of null (reading 'useRef')
</code>```

The app works without any issues and components that do not contain the  component render and pass the test without any issues.

I couldn't find any specific fix to this issue. The only thing I have tried is updating my repoes.

Body:
I'm working on a react-native project and I want to do some testing on it using the testing-library for react-native and jest. The issue is that I cannot render components that contain the Pressable component from react-native. Here is the component that im trying to render:

import React from 'react'
import { View, Text, Pressable } from 'react-native'
export default function FilteringOptions() {

    return (
        <View style={{ flexDirection: 'row' }}>
            <Pressable>
                <Text style={{ fontSize: 24, paddingLeft: 10 }}>{'\u29BF'} All </Text>
            </Pressable>
            <Pressable>
                <Text style={{ fontSize: 24, paddingLeft: 10 }}>{'\u29BF'} Finance  </Text>
            </Pressable>
            <Pressable>
                <Text style={{ fontSize: 24, paddingLeft: 10 }}>{'\u29BF'} Health</Text>
            </Pressable>
        </View>
    );
}

Here is the test case in jest:

test('Testing if FilteringOptions renders', () => {
    render(<FilteringOptions />);
    expect(screen.toJSON()).toMatchSnapshot();
});

And here is the error im getting:

  console.error
    Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Besides this jest also tells me that this error occurs in the  component and the test fails cause there is a:

TypeError: Cannot read properties of null (reading 'useRef')

The app works without any issues and components that do not contain the  component render and pass the test without any issues.

I couldn't find any specific fix to this issue. The only thing I have tried is updating my repoes.


问:
Lab Streaming Layer inlet using data pulled from MATLAB function?
I'm streaming force and 3D kinematic data from Qualisys motion capture software (QTM) using a function in MATLAB. I need to use Lab Streaming Layer (LSL) to time-sync the force & 3D data with another stream of data from eye-tracking glasses. The force data will need to be sent from MATLAB to PsychoPy to drive a visual stimulus.

I need help figuring out how to call the data being streamed into MATLAB into inlets in LSL so I can time sync them and pipe them into the Python-based program via an LSL outlet. The only documentation from QTM + LSL is based in Python, but I'm using MATLAB-based LSL.

Here is the inlet code:

```<code>% resolve a stream...
disp('Resolving QTM stream...');
result = {};
while isempty(result)
    result = lsl_resolve_byprop(lib,'type','force'); end

% create a new inlet
disp('Opening an inlet...');
inlet = lsl_inlet(result{1});

disp('Now receiving data...');
while true
    % get data from the inlet
    [vec,ts] = inlet.pull_sample();
    % and display it
    fprintf('%.2f\t',vec);
    fprintf('%.5f\n',ts);
end
</code>```

I don't know if I need 2 inlets, one for 3D data and one for force. I also don't know if I can replace 'force' (in the code above) with the name of the function (@QCMdemo) since the function pulls both 3D and force data streams simultaneously. It hasn't worked for me so far.

Body:
I'm streaming force and 3D kinematic data from Qualisys motion capture software (QTM) using a function in MATLAB. I need to use Lab Streaming Layer (LSL) to time-sync the force & 3D data with another stream of data from eye-tracking glasses. The force data will need to be sent from MATLAB to PsychoPy to drive a visual stimulus.

I need help figuring out how to call the data being streamed into MATLAB into inlets in LSL so I can time sync them and pipe them into the Python-based program via an LSL outlet. The only documentation from QTM + LSL is based in Python, but I'm using MATLAB-based LSL.

Here is the inlet code:

% resolve a stream...
disp('Resolving QTM stream...');
result = {};
while isempty(result)
    result = lsl_resolve_byprop(lib,'type','force'); end

% create a new inlet
disp('Opening an inlet...');
inlet = lsl_inlet(result{1});

disp('Now receiving data...');
while true
    % get data from the inlet
    [vec,ts] = inlet.pull_sample();
    % and display it
    fprintf('%.2f\t',vec);
    fprintf('%.5f\n',ts);
end

I don't know if I need 2 inlets, one for 3D data and one for force. I also don't know if I can replace 'force' (in the code above) with the name of the function (@QCMdemo) since the function pulls both 3D and force data streams simultaneously. It hasn't worked for me so far.


问:
Spring Boot SSO Azure AD Redirection causing 404 Error after successful authorization
In my Java 11, Spring Boot 2.7.4, Maven application, I am using Spring Security, specifically AadWebSecurityConfigurerAdapter, in order to secure the app against Azure AD. To do this, the first step was to include the following dependencies in my pom.xml file:

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>com.azure.spring</groupId>
        <artifactId>spring-cloud-azure-starter-active-directory</artifactId>
    </dependency>
</code>```

Next, in the Java code, we are overriding AadWebSecurityConfigurerAdapter as follows. Note the security exceptions.

```<code>import com.azure.spring.cloud.autoconfigure.aad.AadWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AadOAuth2LoginSecurityConfig extends AadWebSecurityConfigurerAdapter implements Ordered {

    @Value("${sso.azure.ad.auth.provider.order:2}")
    private int order;

    /**
     * Add configuration logic as needed.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/home", "/login**", "/callback/", "/webjars/**", "/error**", "/oauth2/authorization/**", "login/oauth2/code", "/login/oauth2/code**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    @Override
    public int getOrder() {
        return order;
    }

}
</code>```

This all works fine in a test deployment, where the service is running directly on a personal laptop and the Azure AD is a test account that I setup myself. The redirect URI points to localhost:

http://localhost:11120/login/oauth2/code/

However, in my production environment, the code is containerised using Docker containers, which are deployed to a set of AWS EC2 instances sitting behind a Load Balancer and the Azure AD instance is an official production one, registered specifically for and administered by my organisation. The redirect URI references the load balancer (note also the lack of a trailing forward slash):

https://my-load-balancer:11120/login/oauth2/code

In the production deployment, the users are first redirected to the Microsoft login screen where they are successfully able to authenticate themselves. I can see in the logs that the application then successfully obtains a token from Azure AD. All good up to this point. But then an attempt is made to redirect to the Redirect URL, which is where we see an error in the logs and the user sees a 404 Exception in the browser window. I have included this as a screen shot below, with developer tools open on the right.

Below I have pasted a filtered, sanitized section of my server log file with the authorization tokens replaced with 0.ARXXXXX for brevity. I have labelled the initial request plus the authorization, redirect and error.

```<code>Original request:
2022-12-08 11:02:50,838 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Securing GET /content/documents/myapp?test_no=I1111115432BBBBBBB&entry_number=415895J

2022-12-08 11:02:50,838 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor [https-jsse-nio-11120-exec-4] Failed to authorize filter invocation [GET /content/documents/myapp?test_no=I1111115432BBBBBBB&entry_number=415895J] with attributes [authenticated]

2022-12-08 11:02:50,839 DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache [https-jsse-nio-11120-exec-4] Saved request https://my-load-balancer:11120/content/documents/myapp?test_no=I1111115432BBBBBBB&entry_number=415895J to session

Authorization:
2022-12-08 11:02:50,840 DEBUG org.springframework.security.web.DefaultRedirectStrategy [https-jsse-nio-11120-exec-4] Redirecting to https://my-load-balancer:11120/oauth2/authorization/azure

2022-12-08 11:02:50,902 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-1] Securing GET /oauth2/authorization/azure

2022-12-08 11:02:50,903 DEBUG org.springframework.security.web.DefaultRedirectStrategy [https-jsse-nio-11120-exec-1] Redirecting to https://login.microsoftonline.com/ac52f73c-fd1a-4a9a-8e7a-4a248f31
39e1/oauth2/v2.0/authorize?response_type=code&client_id=f2e26228-25f2-48e7-8131-240533efa2b7&scope=openid%20profile%20offline_access&state=XvM6aRea1X-OkDd8Lm_WFQ2-5j9CvAkFeiTnHxylQ_Y%3D&redirect_uri
=https:/my-load-balancer:11120/login/oauth2/code&nonce=-2I3k_L7dWxC3eBGHcEFz4iRXK8b5XL_qMJN2cQ6m8s

Attempt to redirect to Redirect URL:
2022-12-08 11:02:51,385 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Securing GET /login/oauth2/code?code=0.ARXXXXX

2022-12-08 11:02:51,386 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor [https-jsse-nio-11120-exec-4] Authorized filter invocation [GET /login/oauth2/code?code=0.ARXXXXX] with attributes [permitAll]

2022-12-08 11:02:51,386 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Secured GET /login/oauth2/code?code=0.ARXXXXX

2022-12-08 11:02:51,386 DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter [https-jsse-nio-11120-exec-4] Before request [GET /login/oauth2/code?code=0.ARXXXXX]

2022-12-08 11:02:51,395 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository [https-jsse-nio-11120-exec-4] Did not store anonymous SecurityContext

2022-12-08 11:02:51,395 DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter [https-jsse-nio-11120-exec-4] REQUEST DATA : GET /login/oauth2/code?code=0.ARXXXXX]

2022-12-08 11:02:51,395 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository [https-jsse-nio-11120-exec-4] Did not store anonymous SecurityContext

2022-12-08 11:02:51,395 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter [https-jsse-nio-11120-exec-4] Cleared SecurityContextHolder to complete request

Error:
2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Securing GET /error?code=0.ARXXXXX

2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter [https-jsse-nio-11120-exec-4] Set SecurityContextHolder to empty SecurityContext

2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter [https-jsse-nio-11120-exec-4] Set SecurityContextHolder to anonymous SecurityContext

2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Secured GET /error?code=0.ARXXXXX
</code>```

It is strange that redirection to /login/oauth2/code is causing a 404 error in production but not in test. This is not an endpoint that we as developers code. I believe that it comes 'out of the box' with the Spring Security Authentication Provider.

As I am working in a tied down, production environment with no direct access myself, any changes will take a while to action, hence I am here trying to get the best advice possible before I request any changes. I would be extremely grateful for any guidance, suggestions or advice!

My own thoughts so far are that the issue may well be due to the fact that the production redirect URI points to a load balancer rather than localhost as it does in the test. Perhaps we should try using localhost rather than the load balancer, so that the redirect comes straight back to the server from which it originated without the need for extra 'jumps' to and from the load balancer?

I also think that a trailing slash should be added to the redirect URI in production - it seems like a small detail, but the importance of including this has been highlighted in several articles that I have read. Other than that, I can't see what could be causing the error.

Many thanks for reading! Please note that this post is a continuation from SO question 74707044, which was the previous hurdle we faced, which is now hopefully dealt with!

Body:
In my Java 11, Spring Boot 2.7.4, Maven application, I am using Spring Security, specifically AadWebSecurityConfigurerAdapter, in order to secure the app against Azure AD. To do this, the first step was to include the following dependencies in my pom.xml file:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    <dependency>
        <groupId>com.azure.spring</groupId>
        <artifactId>spring-cloud-azure-starter-active-directory</artifactId>
    </dependency>

Next, in the Java code, we are overriding AadWebSecurityConfigurerAdapter as follows. Note the security exceptions.

import com.azure.spring.cloud.autoconfigure.aad.AadWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AadOAuth2LoginSecurityConfig extends AadWebSecurityConfigurerAdapter implements Ordered {

    @Value("${sso.azure.ad.auth.provider.order:2}")
    private int order;

    /**
     * Add configuration logic as needed.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/", "/home", "/login**", "/callback/", "/webjars/**", "/error**", "/oauth2/authorization/**", "login/oauth2/code", "/login/oauth2/code**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    @Override
    public int getOrder() {
        return order;
    }

}

This all works fine in a test deployment, where the service is running directly on a personal laptop and the Azure AD is a test account that I setup myself. The redirect URI points to localhost:

http://localhost:11120/login/oauth2/code/

However, in my production environment, the code is containerised using Docker containers, which are deployed to a set of AWS EC2 instances sitting behind a Load Balancer and the Azure AD instance is an official production one, registered specifically for and administered by my organisation. The redirect URI references the load balancer (note also the lack of a trailing forward slash):

https://my-load-balancer:11120/login/oauth2/code

In the production deployment, the users are first redirected to the Microsoft login screen where they are successfully able to authenticate themselves. I can see in the logs that the application then successfully obtains a token from Azure AD. All good up to this point. But then an attempt is made to redirect to the Redirect URL, which is where we see an error in the logs and the user sees a 404 Exception in the browser window. I have included this as a screen shot below, with developer tools open on the right.

Below I have pasted a filtered, sanitized section of my server log file with the authorization tokens replaced with 0.ARXXXXX for brevity. I have labelled the initial request plus the authorization, redirect and error.

Original request:
2022-12-08 11:02:50,838 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Securing GET /content/documents/myapp?test_no=I1111115432BBBBBBB&entry_number=415895J

2022-12-08 11:02:50,838 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor [https-jsse-nio-11120-exec-4] Failed to authorize filter invocation [GET /content/documents/myapp?test_no=I1111115432BBBBBBB&entry_number=415895J] with attributes [authenticated]

2022-12-08 11:02:50,839 DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache [https-jsse-nio-11120-exec-4] Saved request https://my-load-balancer:11120/content/documents/myapp?test_no=I1111115432BBBBBBB&entry_number=415895J to session

Authorization:
2022-12-08 11:02:50,840 DEBUG org.springframework.security.web.DefaultRedirectStrategy [https-jsse-nio-11120-exec-4] Redirecting to https://my-load-balancer:11120/oauth2/authorization/azure

2022-12-08 11:02:50,902 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-1] Securing GET /oauth2/authorization/azure

2022-12-08 11:02:50,903 DEBUG org.springframework.security.web.DefaultRedirectStrategy [https-jsse-nio-11120-exec-1] Redirecting to https://login.microsoftonline.com/ac52f73c-fd1a-4a9a-8e7a-4a248f31
39e1/oauth2/v2.0/authorize?response_type=code&client_id=f2e26228-25f2-48e7-8131-240533efa2b7&scope=openid%20profile%20offline_access&state=XvM6aRea1X-OkDd8Lm_WFQ2-5j9CvAkFeiTnHxylQ_Y%3D&redirect_uri
=https:/my-load-balancer:11120/login/oauth2/code&nonce=-2I3k_L7dWxC3eBGHcEFz4iRXK8b5XL_qMJN2cQ6m8s

Attempt to redirect to Redirect URL:
2022-12-08 11:02:51,385 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Securing GET /login/oauth2/code?code=0.ARXXXXX

2022-12-08 11:02:51,386 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor [https-jsse-nio-11120-exec-4] Authorized filter invocation [GET /login/oauth2/code?code=0.ARXXXXX] with attributes [permitAll]

2022-12-08 11:02:51,386 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Secured GET /login/oauth2/code?code=0.ARXXXXX

2022-12-08 11:02:51,386 DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter [https-jsse-nio-11120-exec-4] Before request [GET /login/oauth2/code?code=0.ARXXXXX]

2022-12-08 11:02:51,395 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository [https-jsse-nio-11120-exec-4] Did not store anonymous SecurityContext

2022-12-08 11:02:51,395 DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter [https-jsse-nio-11120-exec-4] REQUEST DATA : GET /login/oauth2/code?code=0.ARXXXXX]

2022-12-08 11:02:51,395 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository [https-jsse-nio-11120-exec-4] Did not store anonymous SecurityContext

2022-12-08 11:02:51,395 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter [https-jsse-nio-11120-exec-4] Cleared SecurityContextHolder to complete request

Error:
2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Securing GET /error?code=0.ARXXXXX

2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter [https-jsse-nio-11120-exec-4] Set SecurityContextHolder to empty SecurityContext

2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter [https-jsse-nio-11120-exec-4] Set SecurityContextHolder to anonymous SecurityContext

2022-12-08 11:02:51,398 DEBUG org.springframework.security.web.FilterChainProxy [https-jsse-nio-11120-exec-4] Secured GET /error?code=0.ARXXXXX

It is strange that redirection to /login/oauth2/code is causing a 404 error in production but not in test. This is not an endpoint that we as developers code. I believe that it comes 'out of the box' with the Spring Security Authentication Provider.

As I am working in a tied down, production environment with no direct access myself, any changes will take a while to action, hence I am here trying to get the best advice possible before I request any changes. I would be extremely grateful for any guidance, suggestions or advice!

My own thoughts so far are that the issue may well be due to the fact that the production redirect URI points to a load balancer rather than localhost as it does in the test. Perhaps we should try using localhost rather than the load balancer, so that the redirect comes straight back to the server from which it originated without the need for extra 'jumps' to and from the load balancer?

I also think that a trailing slash should be added to the redirect URI in production - it seems like a small detail, but the importance of including this has been highlighted in several articles that I have read. Other than that, I can't see what could be causing the error.

Many thanks for reading! Please note that this post is a continuation from SO question 74707044, which was the previous hurdle we faced, which is now hopefully dealt with!


问:
Deploy on digitalocean using docker-compose and docker machine
I am trying to publish a Nodejs application with docker-compose and docker-machine on digitaocean. When I do docker-compose up -d, the application works well on the server but when I shut down my computer or stop docker everything also stops on the server.

Could someone please help me move forward. Thanks in advance


问:
LSQUnivariateSpline line equation (slope, constant, errors)
How can I get the equation of the interpolation lines (slope, constant, and their error) suggested by LSQUnivariateSpline for a data set?

The answer in this link has a good example, but I need help deriving the line's equation.


问:
Where do input files for a VS c++ code need to be if these 2 files are to be checked for syntax errors?
```<code>#include <iostream>
#include <fstream>
#include<stack>
#include<string>

using namespace std;
int main()
{
    stack<char> s;/*created a stack object with char data type*/

    string file_name;
    cout << "Enter the file name: ";
    cin >> file_name;

    ifstream testFile;
    testFile.open(file_name, ios::in);
    char ch;
    while (testFile.peek()!=EOF)
    {
        testFile >> ch;
        if (ch == '[' || ch == '(')
        {
            s.push(ch);
        }
        if (ch == ']')
        {
            if (s.empty())
            {
                s.push(ch);
            }
            if (s.top() == '[')
            {
                s.pop();
            }
        }
        if (ch == ')')
        {
            if (s.empty())
            {
                s.push(ch);
            }
            if (s.top() == '(')
            {
                s.pop();
            }
        }

    }

    if (s.empty())
    {
        cout << "No Syntax Error Occured.";
    }
    else
    {
        cout << "Syntax Error Occured.";
    }

    return 0;
}
</code>```

Hello eheveryone.  This is my first post on here and I need help with debugging a syntax checker program.  I am sure the stack portion is correct.  I think the error is towards the bottom due to the output not showing the words "Syntax Error Occured"  or "No Syntax Error Occured" I am still learning how to debug and appreciate any advice.  I started IT when covid very first came out and due to remote learning was not able to grasp the fundamentals.  Like debugging.

I expected The output of "Syntax Error Occured" or " No Syntax Error Occured"  but it just exits with code 0.

Body:
#include <iostream>
#include <fstream>
#include<stack>
#include<string>

using namespace std;
int main()
{
    stack<char> s;/*created a stack object with char data type*/

    string file_name;
    cout << "Enter the file name: ";
    cin >> file_name;

    ifstream testFile;
    testFile.open(file_name, ios::in);
    char ch;
    while (testFile.peek()!=EOF)
    {
        testFile >> ch;
        if (ch == '[' || ch == '(')
        {
            s.push(ch);
        }
        if (ch == ']')
        {
            if (s.empty())
            {
                s.push(ch);
            }
            if (s.top() == '[')
            {
                s.pop();
            }
        }
        if (ch == ')')
        {
            if (s.empty())
            {
                s.push(ch);
            }
            if (s.top() == '(')
            {
                s.pop();
            }
        }

    }

    if (s.empty())
    {
        cout << "No Syntax Error Occured.";
    }
    else
    {
        cout << "Syntax Error Occured.";
    }

    return 0;
}

Hello eheveryone.  This is my first post on here and I need help with debugging a syntax checker program.  I am sure the stack portion is correct.  I think the error is towards the bottom due to the output not showing the words "Syntax Error Occured"  or "No Syntax Error Occured" I am still learning how to debug and appreciate any advice.  I started IT when covid very first came out and due to remote learning was not able to grasp the fundamentals.  Like debugging.

I expected The output of "Syntax Error Occured" or " No Syntax Error Occured"  but it just exits with code 0.


问:
iOS: ScreenTime API FamilyControl Autorization failed
I am trying to implement the Screentime app and I have added the Family Controls capability to my sample app. But, I'm getting a FamilyControlsError Code=0 when requesting authorization from an iPad OS v15.7.1 signed in with a child iCloud account.

I am using below code:

```<code>AuthorizationCenter.shared.requestAuthorization { result in

        switch result {
        case .success():
            print("Sucess...")
        case .failure(let error):
            print("Failed... \(error)")

        }
    }
</code>```

Please let me know if I am missing anything.

Body:
I am trying to implement the Screentime app and I have added the Family Controls capability to my sample app. But, I'm getting a FamilyControlsError Code=0 when requesting authorization from an iPad OS v15.7.1 signed in with a child iCloud account.

I am using below code:

AuthorizationCenter.shared.requestAuthorization { result in

        switch result {
        case .success():
            print("Sucess...")
        case .failure(let error):
            print("Failed... \(error)")

        }
    }

Please let me know if I am missing anything.