问:
React JS : Invariant failed: You should not use <NavLink> outside a <Router>
There are many instances of this error on Stack Overflow but sadly nothing that has aided in debugging the issue. I'm trying to run my web application on localhost and when the browser opens I'm getting Invariant failed: You should not use <NavLink> outside a <Router> in the following line:

```<code>ReactDOM.render(<App />, document.getElementById('root'));
</code>```

App.js

```<code>import React, { Component } from 'react';
import './App.css';
import {BrowserRouter} from 'react-router-dom';
import Main from './components/main.js';

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Main />
      </BrowserRouter>
    );
  }
}
</code>```

Main.js

```<code>import React, {Component} from 'react';
import {Switch,Route, Router} from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store/store.js';
import JobListing from './job_listings/joblisting.js';
import JobPostings from './JobPostings/JobPostings'
import CustomJobApply from './JobApply/customApply.js';
import EasyJobApply from './JobApply/easyApplyModal.js';
import Jobs from './JobApply/jobs.js';
import JobsApplied from './JobApply/jobsApplied.js';
import ListAllConnections from './networks/listallconnections';
import ShowConnectedUsers from './networks/showconnectedusers';
import Login from './applicant/login'
import UserProfile from './applicant/userprofile'
import UserVisit from './applicant/uservisit'
import UserProfileFirst from './applicant/profilefirst'
import {history} from './../util/utils';
import Navbar from "./navbar/Navbar";
import Search from "./Search";
import UserListing from './applicant/userlistings';
import ApplicantDashBoard from './applicant/applicantDashBoard';
import RecruiterDashBoard from './applicant/recruiterdashboard';
import CityApplications from './applicant/citywiseapplication';
import DeleteAccount from './applicant/deleteapplicantaccount';
import LineChartExample from './applicant/linechartexample';
import UserSearch from './applicant/usersearch';
import ResumeView from './applicant/resumeview';
import ApplicantHome from "./feed/applicantHome.js";
import Resumes from "./JobApply/resumes.js";
import Messages from './messages/messages.js';
import RecruiterDashboard from './RecruiterDashboard/RecruiterDashboard';
import RecruiterJobsDashboard from './RecruiterJobsDashboard/RecruiterJobsDashboard';
//import PieGraph from './graph/pie.js';

class Main extends Component {
    render(){
        localStorage.setItem("counter",0)
        localStorage.setItem("HALFFILLEDRECRUITER","")
        localStorage.setItem("HALFFILLEDJOBTITLE","")
        localStorage.setItem("RECRUITERNAME","");
        return(
            <Provider store={store}>
            <Router history={history}>
            <Switch>
                <Route exact path="/listings" component={JobListing} />
                <Route exact path="/userlisting" component={UserListing} />
                <Route exact path="/postjob" component={JobPostings} />
                <Route exact path="/customapply" component={CustomJobApply} />
                <Route exact path="/mynetworks" component={ListAllConnections} />
                <Route exact path="/" component={Login} />
                <Route exact path="/easyapply" component={EasyJobApply} />
                <Route exact path="/jobs" component={Jobs} />
                <Route exact path="/jobs/applied" component={JobsApplied} />
                <Route exact path="/navbar" component={Navbar} />
                <Route exact path="/search" component={Search} />
                <Route exact path="/profilefirst" component={UserProfileFirst} />
                <Route exact path="/userprofile" component={UserProfile} />
                <Route exact path="/uservisit" component={UserVisit} />
                <Route exact path="/deleteapplicantaccount" component={DeleteAccount}/>
                <Route exact path="/applicantDashBoard" component={ApplicantDashBoard}/>
                <Route exact path="/recruiterdashboard" component={RecruiterDashBoard}/>
                <Route exact path="/usersearch" component={UserSearch}/>
                <Route exact path="/resumeview" component={ResumeView}/>
                <Route exact path="/feed" component={ApplicantHome} />
                <Route exact path="/recruiter/dashboard" component={RecruiterDashboard} />
                <Route exact path="/recruiter/myjobs" component={RecruiterJobsDashboard} />
                <Route exact path="/mynetwork/connections" component={ShowConnectedUsers} />
                <Route exact path="/messages" component={Messages} />
                <Route exact path="/citywiseapplication" component={CityApplications} />
                <Route exact path="/linechartexample" component={LineChartExample} />
                <Route exact path="/resumes/:userid/:filename" component={Resumes} />
                </Switch>
            </Router>
            </Provider>
    );
  }
}
export default Main;
</code>```

I noticed that I haven't include any <NavLink> in my code. What might be wrong?

Body:
There are many instances of this error on Stack Overflow but sadly nothing that has aided in debugging the issue. I'm trying to run my web application on localhost and when the browser opens I'm getting Invariant failed: You should not use <NavLink> outside a <Router> in the following line:

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, { Component } from 'react';
import './App.css';
import {BrowserRouter} from 'react-router-dom';
import Main from './components/main.js';

class App extends Component {
  render() {
    return (
      <BrowserRouter>

      </BrowserRouter>
    );
  }
}

Main.js

import React, {Component} from 'react';
import {Switch,Route, Router} from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store/store.js';
import JobListing from './job_listings/joblisting.js';
import JobPostings from './JobPostings/JobPostings'
import CustomJobApply from './JobApply/customApply.js';
import EasyJobApply from './JobApply/easyApplyModal.js';
import Jobs from './JobApply/jobs.js';
import JobsApplied from './JobApply/jobsApplied.js';
import ListAllConnections from './networks/listallconnections';
import ShowConnectedUsers from './networks/showconnectedusers';
import Login from './applicant/login'
import UserProfile from './applicant/userprofile'
import UserVisit from './applicant/uservisit'
import UserProfileFirst from './applicant/profilefirst'
import {history} from './../util/utils';
import Navbar from "./navbar/Navbar";
import Search from "./Search";
import UserListing from './applicant/userlistings';
import ApplicantDashBoard from './applicant/applicantDashBoard';
import RecruiterDashBoard from './applicant/recruiterdashboard';
import CityApplications from './applicant/citywiseapplication';
import DeleteAccount from './applicant/deleteapplicantaccount';
import LineChartExample from './applicant/linechartexample';
import UserSearch from './applicant/usersearch';
import ResumeView from './applicant/resumeview';
import ApplicantHome from "./feed/applicantHome.js";
import Resumes from "./JobApply/resumes.js";
import Messages from './messages/messages.js';
import RecruiterDashboard from './RecruiterDashboard/RecruiterDashboard';
import RecruiterJobsDashboard from './RecruiterJobsDashboard/RecruiterJobsDashboard';
//import PieGraph from './graph/pie.js';

class Main extends Component {
    render(){
        localStorage.setItem("counter",0)
        localStorage.setItem("HALFFILLEDRECRUITER","")
        localStorage.setItem("HALFFILLEDJOBTITLE","")
        localStorage.setItem("RECRUITERNAME","");
        return(
            <Provider store={store}>
            <Router history={history}>
            <Switch>
                <Route exact path="/listings" component={JobListing} />
                <Route exact path="/userlisting" component={UserListing} />
                <Route exact path="/postjob" component={JobPostings} />
                <Route exact path="/customapply" component={CustomJobApply} />
                <Route exact path="/mynetworks" component={ListAllConnections} />
                <Route exact path="/" component={Login} />
                <Route exact path="/easyapply" component={EasyJobApply} />
                <Route exact path="/jobs" component={Jobs} />
                <Route exact path="/jobs/applied" component={JobsApplied} />
                <Route exact path="/navbar" component={Navbar} />
                <Route exact path="/search" component={Search} />
                <Route exact path="/profilefirst" component={UserProfileFirst} />
                <Route exact path="/userprofile" component={UserProfile} />
                <Route exact path="/uservisit" component={UserVisit} />
                <Route exact path="/deleteapplicantaccount" component={DeleteAccount}/>
                <Route exact path="/applicantDashBoard" component={ApplicantDashBoard}/>
                <Route exact path="/recruiterdashboard" component={RecruiterDashBoard}/>
                <Route exact path="/usersearch" component={UserSearch}/>
                <Route exact path="/resumeview" component={ResumeView}/>
                <Route exact path="/feed" component={ApplicantHome} />
                <Route exact path="/recruiter/dashboard" component={RecruiterDashboard} />
                <Route exact path="/recruiter/myjobs" component={RecruiterJobsDashboard} />
                <Route exact path="/mynetwork/connections" component={ShowConnectedUsers} />
                <Route exact path="/messages" component={Messages} />
                <Route exact path="/citywiseapplication" component={CityApplications} />
                <Route exact path="/linechartexample" component={LineChartExample} />
                <Route exact path="/resumes/:userid/:filename" component={Resumes} />
                </Switch>
            </Router>
            </Provider>
    );
  }
}
export default Main;

I noticed that I haven't include any <NavLink> in my code. What might be wrong?


来源: stackexchange

问:
Is there any epub sdk or package for flutter that supports highlights and notes?
I want to make an Epub Reader with text highlighting, notes, and other annotations. I can't seem to find any free sdk or package that support my needs.

vocsy_epub_viewer is an option but the reader is not customizable and there aren't any docs to help out. What are my options?

ContentLicense: CC BY-SA 4.0


问:
getting error while using valuewhen function to find the pivot point
i am trying to find the higher high as below

i have defined Period as integer

pivotHigh = ta.pivothigh(Period, Period)
higherhigh = ta.valuewhen(pivotHigh, high[Period], high[Period] < high[Period+1])

how ever i am getting error as below
Cannot call 'ta.valuewhen' with argument 'occurrence'='call 'operator <' (series bool)'. An argument of 'series bool' type was used but a 'simple int' is expected


问:
KMM native used in an existing .NET project
I'm working on a project which has 3 native clients: Android, iOS and Windows (WPF).

We decided to give KMM a try and write the common business logic in Kotlin. I managed to make it work for Android. Here I didn't expect any issues.

For iOS we use the generated .framework directory as a library. No issues here as well.

The problem we have now is with the Windows client. We generate the DLL together with the .h and .def files. The DLL is Kotlin/Native and can not be just imported in the .Net project. From what I saw we should create a middle layer, like an interface, where we call the methods from the DLL, which is not that straight forward and adds some extra work.

Is there a way to somehow generate the DLL for .NET? Is there any way to import the Kotlin/Native DLL in the project and call the methods from the DLL without any extra work?


问:
actuator/health return status down but still my application is starting
When I start my application and SQL server is down I get and exception -

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection
to the host #########, port 1234 has failed. Error: "connect timed
out. Verify the connection properties. Make sure that an instance of
SQL Server is running on the host and accepting TCP/IP connections at
the port. Make sure that TCP connections to the port are not blocked
by a firewall.".

but the application starts successfully. When I check actuator/health I get response DOWN -

{
"status": "DOWN" }

I tried looking for it couldn't find a way to not let Spring application start if health is DOWN. Kindly suggest a way to do so.
Also I have another services in my project like influxDB, is there a way to check status of that while starting the application?


问:
Trying to create dynamic component with template in a string
For my project, I'm trying to create dynamic component with a template in a string which contains multiple variable.
So I'm using this answer: angular2 generate component from just a string

And it works well to display my data in my template.
But, I can't use directive like ngIf, ngModel etc...
I have the classic error: "NG0303: Can't bind to 'ngIf' since it isn't a known property of 'span' (used in the 'DynamicComponent' component template)."

I import well CommonModule and FormsModule of course.

```<code>                    const tmpCmp = Component({ template: myTemplate })(class { });
                    const tmpModule = NgModule({ declarations: [tmpCmp], imports: [CommonModule, FormsModule] })(class { });

                    const mod = this._compiler.compileModuleAndAllComponentsSync(tmpModule);
                    const factory = mod.componentFactories.find((comp) =>
                        comp.componentType === tmpCmp
                    );
                    const cmpRef = factory.create(this._injector, [], null, this._m);
                    cmpRef.instance.name = `dynamic_${j}`;
                    cmpRef.instance.data = this.data[j];
                    this.listVc.get(j).insert(cmpRef.hostView);
</code>```

I'm on Angular 14 by the way.

My template looks like:

```<code><div class="ui-grid-cell-contents text-center">
<input [value]="data.lastName">
<span *ngIf="data.teletrav" class="glyphicon glyphicon-ok-circle"></span>
</div>
</code>```

Thanks

Body:
For my project, I'm trying to create dynamic component with a template in a string which contains multiple variable.
So I'm using this answer: angular2 generate component from just a string

And it works well to display my data in my template.
But, I can't use directive like ngIf, ngModel etc...
I have the classic error: "NG0303: Can't bind to 'ngIf' since it isn't a known property of 'span' (used in the 'DynamicComponent' component template)."

I import well CommonModule and FormsModule of course.

                    const tmpCmp = Component({ template: myTemplate })(class { });
                    const tmpModule = NgModule({ declarations: [tmpCmp], imports: [CommonModule, FormsModule] })(class { });

                    const mod = this._compiler.compileModuleAndAllComponentsSync(tmpModule);
                    const factory = mod.componentFactories.find((comp) =>
                        comp.componentType === tmpCmp
                    );
                    const cmpRef = factory.create(this._injector, [], null, this._m);
                    cmpRef.instance.name = `dynamic_${j}`;
                    cmpRef.instance.data = this.data[j];
                    this.listVc.get(j).insert(cmpRef.hostView);

I'm on Angular 14 by the way.

My template looks like:

<input [value]="data.lastName">

Thanks


问:
Python installing pyttk package results error: subprocess-exited-with-error - ModuleNotFoundError
I was trying to install pyttk package and i get the following error

```<code>Collecting pyttk
  Using cached pyttk-0.3.2.tar.gz (127 kB)
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'

  error: subprocess-exited-with-error

  python setup.py egg_info did not run successfully.
  exit code: 1

  [8 lines of output]
  Traceback (most recent call last):
    File "<string>", line 2, in <module>
    File "<pip-setuptools-caller>", line 34, in <module>
    File "C:\Users\Aliha\AppData\Local\Temp\pip-install-9bqkh7pi\pyttk_814eb0b52ac14353b20fd79b4416949d\setup.py", line 2, in <module>
      import ttk
    File "C:\Users\Aliha\AppData\Local\Temp\pip-install-9bqkh7pi\pyttk_814eb0b52ac14353b20fd79b4416949d\ttk.py", line 36, in <module>
      import tkinter as Tkinter
  ModuleNotFoundError: No module named 'tkinter'
  [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

Encountered error while generating package metadata.

See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

Also when I use the command  "python -m tkinter" the GUI popsup

I was trying to install pyttk package to be able to use GUI tkinter package

Body:
I was trying to install pyttk package and i get the following error

Collecting pyttk
  Using cached pyttk-0.3.2.tar.gz (127 kB)
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'

  error: subprocess-exited-with-error

  python setup.py egg_info did not run successfully.
  exit code: 1

  [8 lines of output]
  Traceback (most recent call last):
    File "<string>", line 2, in <module>
    File "<pip-setuptools-caller>", line 34, in <module>
    File "C:\Users\Aliha\AppData\Local\Temp\pip-install-9bqkh7pi\pyttk_814eb0b52ac14353b20fd79b4416949d\setup.py", line 2, in <module>
      import ttk
    File "C:\Users\Aliha\AppData\Local\Temp\pip-install-9bqkh7pi\pyttk_814eb0b52ac14353b20fd79b4416949d\ttk.py", line 36, in <module>
      import tkinter as Tkinter
  ModuleNotFoundError: No module named 'tkinter'
  [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

Encountered error while generating package metadata.

See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Also when I use the command  "python -m tkinter" the GUI popsup

I was trying to install pyttk package to be able to use GUI tkinter package


问:
why Cartesian product of deletes the timestamp?
I'd like to replicate following date_range to a list by cartesian product:

```<code> todays_date = datetime.datetime.now().date()
 time_index = pd.date_range(todays_date-datetime.timedelta(days=1), end=todays_date,
 freq='h') # one hour intervals
</code>```

which results in :

```<code>DatetimeIndex(['2023-01-11 00:00:00', '2023-01-11 01:00:00',
           '2023-01-11 02:00:00', '2023-01-11 03:00:00',
           '2023-01-11 04:00:00', '2023-01-11 05:00:00',
           '2023-01-11 06:00:00', '2023-01-11 07:00:00',
           '2023-01-11 08:00:00', '2023-01-11 09:00:00',
           '2023-01-11 10:00:00', '2023-01-11 11:00:00',
           '2023-01-11 12:00:00', '2023-01-11 13:00:00',
           '2023-01-11 14:00:00', '2023-01-11 15:00:00',
           '2023-01-11 16:00:00', '2023-01-11 17:00:00',
           '2023-01-11 18:00:00', '2023-01-11 19:00:00',
           '2023-01-11 20:00:00', '2023-01-11 21:00:00',
           '2023-01-11 22:00:00', '2023-01-11 23:00:00',
           '2023-01-12 00:00:00'],
          dtype='datetime64[ns]', freq='H')
</code>```

then here is the ids list

```<code> ids = [1,2,3,4,5]
</code>```

then  by doing the following i do the cartesian product

```<code>pd.DataFrame(product(time_index, ids), columns=['time','id'])
</code>```

but results are not as expected as the Hour:Minute:Seconds part of the Datetime index are dropped and i get something like this :

```<code>2023-01-11  1
2023-01-11  2
2023-01-11  3
    .
    .
    .
</code>```

How can i properly do this replication while keeping all the DatetimeIndex components, join and merge also returns the same results

I believe it's not a duplicate to this question as the timestamp is included in the DatetimeIndex

Body:
I'd like to replicate following date_range to a list by cartesian product:

 todays_date = datetime.datetime.now().date()
 time_index = pd.date_range(todays_date-datetime.timedelta(days=1), end=todays_date,
 freq='h') # one hour intervals

which results in :

DatetimeIndex(['2023-01-11 00:00:00', '2023-01-11 01:00:00',
           '2023-01-11 02:00:00', '2023-01-11 03:00:00',
           '2023-01-11 04:00:00', '2023-01-11 05:00:00',
           '2023-01-11 06:00:00', '2023-01-11 07:00:00',
           '2023-01-11 08:00:00', '2023-01-11 09:00:00',
           '2023-01-11 10:00:00', '2023-01-11 11:00:00',
           '2023-01-11 12:00:00', '2023-01-11 13:00:00',
           '2023-01-11 14:00:00', '2023-01-11 15:00:00',
           '2023-01-11 16:00:00', '2023-01-11 17:00:00',
           '2023-01-11 18:00:00', '2023-01-11 19:00:00',
           '2023-01-11 20:00:00', '2023-01-11 21:00:00',
           '2023-01-11 22:00:00', '2023-01-11 23:00:00',
           '2023-01-12 00:00:00'],
          dtype='datetime64[ns]', freq='H')

then here is the ids list

 ids = [1,2,3,4,5]

then  by doing the following i do the cartesian product

pd.DataFrame(product(time_index, ids), columns=['time','id'])

but results are not as expected as the Hour:Minute:Seconds part of the Datetime index are dropped and i get something like this :

2023-01-11  1
2023-01-11  2
2023-01-11  3
    .
    .
    .

How can i properly do this replication while keeping all the DatetimeIndex components, join and merge also returns the same results

I believe it's not a duplicate to this question as the timestamp is included in the DatetimeIndex


问:
Advance filter for 9999 data in excel
There is limitation for range in advance filter data?
I had around 9999 data and try to create filter in user form, but when i try it error 1004 occur in line "Set tblRange = WSC.Range("A5:L9999" & irow)". but when i tried to delete the data in sheet to 999 its working. there is any limitatin on advance filter? thank you

```<code>Private Sub txtsearchfor_Change()
Dim irow As Long
Dim tblRange As Range, tblCriteria As Range
Dim WSC As Object

Set WSC = Worksheets("Catalog")
WSC.Activate
irow = WSC.Cells(WSC.Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Set tblRange = WSC.Range("A5:L9999" & irow)
Set tblCriteria = WSC.Range("X1:X2")
WSC.Range("X1") = cbsearchby
WSC.Range("X2") = "*" & txtsearchfor & "*"
'tblRange.AdvancedFilter xlFilterInPlace, tblCriteria
tblRange.AdvancedFilter xlFilterCopy, tblCriteria, WSC.Range("AA5:AL9999"), False

Call GetCatalogSearchData
End Sub
</code>```

Im trying to able to filter the data.

Title: Advance filter for 9999 data in excel

Body:
There is limitation for range in advance filter data?
I had around 9999 data and try to create filter in user form, but when i try it error 1004 occur in line "Set tblRange = WSC.Range("A5:L9999" & irow)". but when i tried to delete the data in sheet to 999 its working. there is any limitatin on advance filter? thank you

Private Sub txtsearchfor_Change()
Dim irow As Long
Dim tblRange As Range, tblCriteria As Range
Dim WSC As Object

Set WSC = Worksheets("Catalog")
WSC.Activate
irow = WSC.Cells(WSC.Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Set tblRange = WSC.Range("A5:L9999" & irow)
Set tblCriteria = WSC.Range("X1:X2")
WSC.Range("X1") = cbsearchby
WSC.Range("X2") = "*" & txtsearchfor & "*"
'tblRange.AdvancedFilter xlFilterInPlace, tblCriteria
tblRange.AdvancedFilter xlFilterCopy, tblCriteria, WSC.Range("AA5:AL9999"), False

Call GetCatalogSearchData
End Sub

Im trying to able to filter the data.


问:
Dxhtml Gantt chart in reactjs
When I try to add a subtask A after a subtask B which has add button when I hit the button the subtask A is getting added inside subtask B which makes subtask B as a parent of subtask A but I need subtask A to get added after subtask B and both should have same parent let us consider Task C as parent task

Output which is required where TaskC gets added after TaskB for both the tasks Parent is TaskA
output which I have got where TaskC getting added under TaskB whose parent is TaskA

Title: Dxhtml Gantt chart in reactjs


问:
JavaScript - href not working in addEventListener / innerHTML
I am stuck on a problem while making a simple website. What I want to achieve is that on the home page when I click the bootstrap navbar item 'Follow Us On', a button appears with the href to www.facebook.com.

I have achieved the button appearing through addEventListener on clicking the item, and toggling/removing it by clicking again. However the problem is that the href is not working.

The code for href, which I am injecting using innerHTML, works fine on codepen.io, however it is not working in the website. Any idea why this is so?

html code

```<code>    <!-- Nav Bar -->
      <nav class="navbar navbar-expand-lg navbar-dark flex-column ">

        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse " id="navbarSupportedContent">
          <ul class="navbar-nav ms-auto flex-column">
            <li class="nav-item">
              <a class="nav-link" href="aboutlnd.html">ABOUT L & D</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="ourprojects.html">OUR PROJECTS</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#cta">CONTACT US</a>
            </li>
            <li id="follow_us" class="nav-item">
                <a class="nav-link" href="">FOLLOW US ON</a>

              </li>
              <li class="nav-item">
                <div id="blank_space" class="nav-link"></div>

              </li>
          </ul>
        </div>
      </nav>
</code>```

Js code

```<code>
var follow_toggler = document.getElementById("follow_us");

// function to be called and removed when button is clicked
function noscroll(e) {
    e.preventDefault();
    document.getElementById("blank_space").innerHTML = `<button  type="button"   class="btn  btn-dark  btn-lg  download-button">
    <a  href="https://www.facebook.com/"  target="_blank"> <i  class="fa-brands  fa-apple"></i>Facebook</a> </button>`;

}

// TOGGLE EVENT LISTENER
var scrollToggle = false;

function toggleEventListener() {
    if (scrollToggle === false) {
        window.addEventListener("click", noscroll, false);
        scrollToggle = true;
    } else {
        window.removeEventListener("click", noscroll, false);
        scrollToggle = false;
    }
}

follow_toggler.addEventListener("click", function () {
    toggleEventListener();
}, false)

</code>```

Body:
I am stuck on a problem while making a simple website. What I want to achieve is that on the home page when I click the bootstrap navbar item 'Follow Us On', a button appears with the href to www.facebook.com.

I have achieved the button appearing through addEventListener on clicking the item, and toggling/removing it by clicking again. However the problem is that the href is not working.

The code for href, which I am injecting using innerHTML, works fine on codepen.io, however it is not working in the website. Any idea why this is so?

html code

        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >

        </button>

              ABOUT L & D

              OUR PROJECTS

              CONTACT US

                FOLLOW US ON

Js code

var follow_toggler = document.getElementById("follow_us");

// function to be called and removed when button is clicked
function noscroll(e) {
    e.preventDefault();
    document.getElementById("blank_space").innerHTML = `<button  type="button"   class="btn  btn-dark  btn-lg  download-button">
     Facebook </button>`;

}

// TOGGLE EVENT LISTENER
var scrollToggle = false;

function toggleEventListener() {
    if (scrollToggle === false) {
        window.addEventListener("click", noscroll, false);
        scrollToggle = true;
    } else {
        window.removeEventListener("click", noscroll, false);
        scrollToggle = false;
    }
}

follow_toggler.addEventListener("click", function () {
    toggleEventListener();
}, false)


问:
Transitions issues nuxtjs
I used GSAP and transitions from Nuxt to create a simple animation between this two pages.

The problem is when you leave about, home is not loaded and we see body background. Conversely, when you are on home and you go on about, home is still alive and "about" move above home

I just want to know if it's possible to "keep alive" home page in both cases.

Link for the playground : https://codesandbox.io/s/animation-between-page-test-go4k6h

link for the animation to reproduce : https://www.mirrormirror.fr/
(print and homepage transition)

Title: Transitions issues nuxtjs


问:
Get port dynamically being set in application or being run in docker
I want to use this port for Oauth2 implementation dynamic getting the port.

Implementation:
1.Get the port running before the Oauth2 will be excuted else Oauth2 will not connect.

When application run: running port 8000 but the port capture us 8080

```<code>
2023-01-12 17:14:31.767  INFO 2492 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): `8000` (http)
2023-01-12 17:14:31.777  INFO 2492 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-01-12 17:14:31.777  INFO 2492 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
System `8080`

</code>```

Class that get the port runnig but its not getting the port 8000.
And also this Class running before Oauth2 which is good but the port is wrong 8080.

```<code>
@Component
public class CustomContainer  implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        System.out.println("System " +factory.getWebServer().getPort());
    }
}

</code>```

application.properties

```<code>server.port=8000
</code>```

This will work getting the port 8000 but its only being excuted after Oauth2 which it Oauth2 will failed to connect.
I already add '@Order(Ordered.HIGHEST_PRECEDENCE'but wont be excuted first

```<code>@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class PortDomain  implements ApplicationListener<ServletWebServerInitializedEvent> {

        private static Integer port;

        private String domain = InetAddress.getLoopbackAddress().getHostName();

        @Override
        public void onApplicationEvent(ServletWebServerInitializedEvent event) {
            setPort(event.getWebServer().getPort());
            System.out.println("Check way "+event.getWebServer().getPort());
        }

        public static void setPort(Integer port) {
            PortDomain.port = port;
        }

        public String portDomain(){
            String protocolDomain = "http://"+domain+":"+port;
            log.info("UrlUtility protocolDomain{}",protocolDomain);
            return protocolDomain;
        }

}

</code>```

spring boot dynamically getting the port running

Body:
I want to use this port for Oauth2 implementation dynamic getting the port.

Implementation:
1.Get the port running before the Oauth2 will be excuted else Oauth2 will not connect.

When application run: running port 8000 but the port capture us 8080

2023-01-12 17:14:31.767  INFO 2492 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): `8000` (http)
2023-01-12 17:14:31.777  INFO 2492 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-01-12 17:14:31.777  INFO 2492 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
System `8080`

Class that get the port runnig but its not getting the port 8000.
And also this Class running before Oauth2 which is good but the port is wrong 8080.

@Component
public class CustomContainer  implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        System.out.println("System " +factory.getWebServer().getPort());
    }
}

application.properties

server.port=8000

This will work getting the port 8000 but its only being excuted after Oauth2 which it Oauth2 will failed to connect.
I already add '@Order(Ordered.HIGHEST_PRECEDENCE'but wont be excuted first

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class PortDomain  implements ApplicationListener<ServletWebServerInitializedEvent> {

        private static Integer port;

        private String domain = InetAddress.getLoopbackAddress().getHostName();

        @Override
        public void onApplicationEvent(ServletWebServerInitializedEvent event) {
            setPort(event.getWebServer().getPort());
            System.out.println("Check way "+event.getWebServer().getPort());
        }

        public static void setPort(Integer port) {
            PortDomain.port = port;
        }

        public String portDomain(){
            String protocolDomain = "http://"+domain+":"+port;
            log.info("UrlUtility protocolDomain{}",protocolDomain);
            return protocolDomain;
        }

}

spring boot dynamically getting the port running


问:
How can I automatically scroll to LazyColumn item in Kotlin?
I am making a chat bot application and I show the dialogs in lazycolumn, but the page does not scroll down as the dialog progresses, which causes a bad experience for the user. I found something related to this called rememberLazyListState and implemented it in my own code but it didn't work properly. I don't know exactly what the problem is. My codes are like this

LazyColumn

```<code>val list = remember { mutableStateListOf<Message>() }
val listState = rememberLazyListState()
LazyColumn(state = listState) {
            items(list.size) { i ->
                Row(
                    horizontalArrangement =
                    if (list[i].id == RECEIVE_ID)
                        Arrangement.Start
                    else
                        Arrangement.End
                ) {
                    if (list[i].id == RECEIVE_ID) {
                        Item(message = list[i], botName, botcolor, list, true)

                    } else {
                        Item(message = list[i], "user", usercolor, list, false)

                    }
                }
            }
        }
</code>```

Item

```<code>@Composable
fun Item(
    message: Message,
    person: String,
    color: Color,
    list: SnapshotStateList<Message>,
    simpleTextFlag: Boolean
) {

    Column(modifier = Modifier.fillMaxSize()) {
        Card(
            modifier = Modifier
                .padding(10.dp),
            backgroundColor = color,
            elevation = 10.dp
        ) {
            Column(
                horizontalAlignment = Alignment.End,
                modifier = Modifier
                    .padding(10.dp)
                    .height(IntrinsicSize.Max)
            ) {
                Row(
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(4.dp)
                ) {
                    Text(
                        buildAnnotatedString {
                            withStyle(
                                style = SpanStyle(
                                    fontWeight = FontWeight.Medium,
                                    color = Color.Black
                                )
                            ) {
                                append("$person: ")
                            }
                        },
                        modifier = Modifier
                            .padding(4.dp)
                    )
                    Text(
                        buildAnnotatedString {
                            withStyle(
                                style = SpanStyle(
                                    fontWeight = FontWeight.W900,
                                    color = Color.White//Color(/*0xFF4552B8*/)
                                )
                            )
                            {
                                append(message.message)
                            }
                        }
                    )
                    Spacer(modifier = Modifier.padding(3.dp))
                }

            }
        }
        if (simpleTextFlag)
            simpleText(list = list)
    }

}

@OptIn(ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class)
@Composable
fun simpleText(list: SnapshotStateList<Message>) {

    var visible by remember { mutableStateOf(true) }

    val coroutineScope = rememberCoroutineScope()
    val keyboardController = LocalSoftwareKeyboardController.current
    val bringIntoViewRequester = remember { BringIntoViewRequester() }

    var text by remember { mutableStateOf("") }

    AnimatedVisibility(
        visible = visible,
        enter = fadeIn() + slideInHorizontally(),
        exit = fadeOut() + slideOutHorizontally()
    ) {
    Row(
        verticalAlignment = Alignment.Bottom,
        horizontalArrangement = Arrangement.Center,
        modifier = Modifier.bringIntoViewRequester(bringIntoViewRequester)
    ) {

            OutlinedTextField(
                modifier = Modifier
                    .padding(8.dp)
                    .onFocusEvent { focusState ->
                        if (focusState.isFocused) {
                            coroutineScope.launch {
                                bringIntoViewRequester.bringIntoView()
                            }
                        }
                    },
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() }),
                value = text,
                onValueChange = { text = it },
                shape = RoundedCornerShape(12.dp),
                label = { Text("send message") })
            IconButton(onClick = {
                if (text.isNotEmpty()) {
                    //Adds it to our local list
                    list.add(
                        Message(
                            text,
                            Constants.SEND_ID,
                            Timestamp(System.currentTimeMillis()).toString()
                        )
                    )
                    customBotMessage(Messages.listOfMessages[index], list)
                    index += 1
                }
                text = ""
                visible = false

            }) {
                Icon(
                    modifier = Modifier.padding(8.dp),
                    painter = painterResource(id = R.drawable.ic_baseline_send_24),
                    contentDescription = "send message img"
                )
            }
        }

    }
}

private fun customBotMessage(message: String, list: SnapshotStateList<Message>) {

    GlobalScope.launch {
        delay(1000)
        withContext(Dispatchers.Main) {
            list.add(
                Message(
                    message,
                    Constants.RECEIVE_ID,
                    Timestamp(System.currentTimeMillis()).toString()
                )
            )
        }
    }
}
</code>```

I keep a list of type MutableStateListof

This list:

```<code>val list = remember { mutableStateListOf<Message>() }.
</code>```

This is the list I use in LazyColumn. When the bot gives a message, it is added to the list, in the same way, when the user enters a message, it is added to the list and LazyColumn displays them.

Body:
I am making a chat bot application and I show the dialogs in lazycolumn, but the page does not scroll down as the dialog progresses, which causes a bad experience for the user. I found something related to this called rememberLazyListState and implemented it in my own code but it didn't work properly. I don't know exactly what the problem is. My codes are like this

LazyColumn

val list = remember { mutableStateListOf<Message>() }
val listState = rememberLazyListState()
LazyColumn(state = listState) {
            items(list.size) { i ->
                Row(
                    horizontalArrangement =
                    if (list[i].id == RECEIVE_ID)
                        Arrangement.Start
                    else
                        Arrangement.End
                ) {
                    if (list[i].id == RECEIVE_ID) {
                        Item(message = list[i], botName, botcolor, list, true)

                    } else {
                        Item(message = list[i], "user", usercolor, list, false)

                    }
                }
            }
        }

Item

@Composable
fun Item(
    message: Message,
    person: String,
    color: Color,
    list: SnapshotStateList<Message>,
    simpleTextFlag: Boolean
) {

    Column(modifier = Modifier.fillMaxSize()) {
        Card(
            modifier = Modifier
                .padding(10.dp),
            backgroundColor = color,
            elevation = 10.dp
        ) {
            Column(
                horizontalAlignment = Alignment.End,
                modifier = Modifier
                    .padding(10.dp)
                    .height(IntrinsicSize.Max)
            ) {
                Row(
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(4.dp)
                ) {
                    Text(
                        buildAnnotatedString {
                            withStyle(
                                style = SpanStyle(
                                    fontWeight = FontWeight.Medium,
                                    color = Color.Black
                                )
                            ) {
                                append("$person: ")
                            }
                        },
                        modifier = Modifier
                            .padding(4.dp)
                    )
                    Text(
                        buildAnnotatedString {
                            withStyle(
                                style = SpanStyle(
                                    fontWeight = FontWeight.W900,
                                    color = Color.White//Color(/*0xFF4552B8*/)
                                )
                            )
                            {
                                append(message.message)
                            }
                        }
                    )
                    Spacer(modifier = Modifier.padding(3.dp))
                }

            }
        }
        if (simpleTextFlag)
            simpleText(list = list)
    }

}

@OptIn(ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class)
@Composable
fun simpleText(list: SnapshotStateList<Message>) {

    var visible by remember { mutableStateOf(true) }

    val coroutineScope = rememberCoroutineScope()
    val keyboardController = LocalSoftwareKeyboardController.current
    val bringIntoViewRequester = remember { BringIntoViewRequester() }

    var text by remember { mutableStateOf("") }

    AnimatedVisibility(
        visible = visible,
        enter = fadeIn() + slideInHorizontally(),
        exit = fadeOut() + slideOutHorizontally()
    ) {
    Row(
        verticalAlignment = Alignment.Bottom,
        horizontalArrangement = Arrangement.Center,
        modifier = Modifier.bringIntoViewRequester(bringIntoViewRequester)
    ) {

            OutlinedTextField(
                modifier = Modifier
                    .padding(8.dp)
                    .onFocusEvent { focusState ->
                        if (focusState.isFocused) {
                            coroutineScope.launch {
                                bringIntoViewRequester.bringIntoView()
                            }
                        }
                    },
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() }),
                value = text,
                onValueChange = { text = it },
                shape = RoundedCornerShape(12.dp),
                label = { Text("send message") })
            IconButton(onClick = {
                if (text.isNotEmpty()) {
                    //Adds it to our local list
                    list.add(
                        Message(
                            text,
                            Constants.SEND_ID,
                            Timestamp(System.currentTimeMillis()).toString()
                        )
                    )
                    customBotMessage(Messages.listOfMessages[index], list)
                    index += 1
                }
                text = ""
                visible = false

            }) {
                Icon(
                    modifier = Modifier.padding(8.dp),
                    painter = painterResource(id = R.drawable.ic_baseline_send_24),
                    contentDescription = "send message img"
                )
            }
        }

    }
}

private fun customBotMessage(message: String, list: SnapshotStateList<Message>) {

    GlobalScope.launch {
        delay(1000)
        withContext(Dispatchers.Main) {
            list.add(
                Message(
                    message,
                    Constants.RECEIVE_ID,
                    Timestamp(System.currentTimeMillis()).toString()
                )
            )
        }
    }
}

I keep a list of type MutableStateListof

This list:

val list = remember { mutableStateListOf<Message>() }.

This is the list I use in LazyColumn. When the bot gives a message, it is added to the list, in the same way, when the user enters a message, it is added to the list and LazyColumn displays them.


问:
Firebase - Passwordless sign-in quota exceeded just after 5 requests?
I am a bit shocked at what I observed. I am 100% sure that I have generated only 5 links for testing my web application however in the documentation it says 20,000 sign-in links generated per day:
https://firebase.google.com/docs/auth/limits

Am I missing something here? Because testing app for less than 5 links a day would be extremely hard. Can I turn on some debugging options? Like we used to have on otp verifications where we could add dummy otps and test them as per the requirement?

Edit: I also see this:

Does this mean we can only request 5 emails a day for passwordless sign in? Is there a way to create a mocked email address for development and testing purposes?


问:
using asp.net ado to update excel sheet
when i try to update data in the sheet this happens
error message :

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

```<code>    Dim excomand As String = "UPDATE [Sheet1$] SET name = @EXNAME  WHERE id = @EXID"
    Dim comand As New OleDbCommand(excomand, conn)
    comand.Parameters.AddWithValue("@EXID", TextBox1.Text)
    comand.Parameters.AddWithValue("@EXNAME", TextBox2.Text)
    comand.Parameters.AddWithValue("EXPHONE", TextBox3.Text)
</code>```

this is my code

when i use the update with plain text it works but if i use parameters the error occur

Title: using asp.net ado to update excel sheet

Body:
when i try to update data in the sheet this happens
error message :

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

    Dim excomand As String = "UPDATE [Sheet1$] SET name = @EXNAME  WHERE id = @EXID"
    Dim comand As New OleDbCommand(excomand, conn)
    comand.Parameters.AddWithValue("@EXID", TextBox1.Text)
    comand.Parameters.AddWithValue("@EXNAME", TextBox2.Text)
    comand.Parameters.AddWithValue("EXPHONE", TextBox3.Text)

this is my code

when i use the update with plain text it works but if i use parameters the error occur


问:
Access Denied Error when using Cloudfront with Signed Cookies
I know this topic has been asked and answered multiple times all over the internet but unfortunately I'm still having issues although trying basically every single related post out there!

My setup

I have an S3 bucket with video files for a frontend streaming service. The files get served via a CloudFront Distribution and in order to secure the file access, I have set up an API Gateway which redirect requests to a Custom Lambda to get my Signed Cookies for CloudFront.

However, tests for the individual services were all successful:

Setting S3 access permissions to public and requesting the *.m3u8video manifest directly from the S3 works as expected (stream works like a charm).

After setting up a custom SSL certificate for my Cloudfront distribution (to avoid CORS), and requesting the same file via CloudFront also works.

Since my frontend needs access to an entire folder on the S3 (for streaming), the only way - at least as I understood - is to use signed cookies for the request. Therefore, I have set up a Custom Lambda which returns the Set-Cookie headers for the CloudFront domain.

For returning custom headers, we need to set up an API Gateway and link it to the lambda.

I want to emphasise, that S3, CloudFront, Lambda and the API Gateway are working individually but only as long as I don't attach the cookies to the request!

So my guess is that something is wrong with the signing of the cookies.

Custom Lambda

Since the lambda is the source of truth for cookie signing, I will show a minimal example of what I'm doing here. My lambda is written in Node JS and I'm using "@aws-sdk/cloudfront-signer": "^3.229.0",.

const url = `https://my-cloudfront.domian.com/path-to-src/*`;
const expTime = new Date(Date.now() + 5 * (60 * 60 * 1000)).toISOString();

const signedCookie = getSignedCookies({
  keyPairId: awsCloudfrontKeyPairId,    // from CloudFront setup
  privateKey: awsCloudfrontPrivateKey,  // from CloudFront setup
  url: url,
  dateLessThan: getExpTime,
});

const response = {
  statusCode: 200,
  isBase64Encoded: false,
  body: JSON.stringify({ url: url, bucket: bucket, key: key }),
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Methods": "OPTIONS,POST,GET",
  },
  multiValueHeaders: {
    "Set-Cookie": [
      `CloudFront-Expires=${signedCookie["CloudFront-Expires"]}; Domain=domain.com; Path=/*`,
      `CloudFront-Signature=${signedCookie["CloudFront-Signature"]}; Domain=domain.com; Path=/*`,
      `CloudFront-Key-Pair-Id=${signedCookie["CloudFront-Key-Pair-Id"]}; Domain=domain.com; Path=/*`,
    ],
  },
};

callback(null, response);
```
<p>This works, I get the 3 <code>Set-Cookie</code> headers which also get submitted when requesting the file. However, the result is always the same:</p>
```ACCESS DENIED
```

Tests

To test the individual services I did the following:

S3 only --> stream works

CloudFront without viewer restriction --> stream works

CloudFront with viewer restriction but no cookies --> Missing Key error

CloudFront with viewer restriction and cookies --> Access Denied error

There obviously is a lot more important setup steps (e.g. bucket policies, custom domains, etc), which I did not mention here but can be posted on request if necessary.

This topic keeps me busy since a month now! Any help appreciated!

Body:
I know this topic has been asked and answered multiple times all over the internet but unfortunately I'm still having issues although trying basically every single related post out there!

My setup

I have an S3 bucket with video files for a frontend streaming service. The files get served via a CloudFront Distribution and in order to secure the file access, I have set up an API Gateway which redirect requests to a Custom Lambda to get my Signed Cookies for CloudFront.

However, tests for the individual services were all successful:

Setting S3 access permissions to public and requesting the *.m3u8video manifest directly from the S3 works as expected (stream works like a charm).

After setting up a custom SSL certificate for my Cloudfront distribution (to avoid CORS), and requesting the same file via CloudFront also works.

Since my frontend needs access to an entire folder on the S3 (for streaming), the only way - at least as I understood - is to use signed cookies for the request. Therefore, I have set up a Custom Lambda which returns the Set-Cookie headers for the CloudFront domain.

For returning custom headers, we need to set up an API Gateway and link it to the lambda.

I want to emphasise, that S3, CloudFront, Lambda and the API Gateway are working individually but only as long as I don't attach the cookies to the request!

So my guess is that something is wrong with the signing of the cookies.

Custom Lambda

Since the lambda is the source of truth for cookie signing, I will show a minimal example of what I'm doing here. My lambda is written in Node JS and I'm using "@aws-sdk/cloudfront-signer": "^3.229.0",.

const url = `https://my-cloudfront.domian.com/path-to-src/*`;
const expTime = new Date(Date.now() + 5 * (60 * 60 * 1000)).toISOString();

const signedCookie = getSignedCookies({
  keyPairId: awsCloudfrontKeyPairId,    // from CloudFront setup
  privateKey: awsCloudfrontPrivateKey,  // from CloudFront setup
  url: url,
  dateLessThan: getExpTime,
});

const response = {
  statusCode: 200,
  isBase64Encoded: false,
  body: JSON.stringify({ url: url, bucket: bucket, key: key }),
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Methods": "OPTIONS,POST,GET",
  },
  multiValueHeaders: {
    "Set-Cookie": [
      `CloudFront-Expires=${signedCookie["CloudFront-Expires"]}; Domain=domain.com; Path=/*`,
      `CloudFront-Signature=${signedCookie["CloudFront-Signature"]}; Domain=domain.com; Path=/*`,
      `CloudFront-Key-Pair-Id=${signedCookie["CloudFront-Key-Pair-Id"]}; Domain=domain.com; Path=/*`,
    ],
  },
};

callback(null, response);

This works, I get the 3 Set-Cookie headers which also get submitted when requesting the file. However, the result is always the same:

ACCESS DENIED

Tests

To test the individual services I did the following:

S3 only --> stream works

CloudFront without viewer restriction --> stream works

CloudFront with viewer restriction but no cookies --> Missing Key error

CloudFront with viewer restriction and cookies --> Access Denied error

There obviously is a lot more important setup steps (e.g. bucket policies, custom domains, etc), which I did not mention here but can be posted on request if necessary.

This topic keeps me busy since a month now! Any help appreciated!


问:
Taking Screenshot with Texture2D.Readpixels on Oculus Device Results in Blank Image
I try to take a screenshot on Oculus devices using Unity C# Script. But the result only shows a black or white image. I think read pixel is not working correctly. Can anyone help with the solution?

```<code>    public void PressedButton()
    {
        StartCoroutine(TakeScreenshotAndShare());
    }
    private IEnumerator TakeScreenshotAndShare()
    {
     yield return new WaitForEndOfFrame();
      Texture2D ss = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
      ss.ReadPixels(new Rect(0, 0, 1000, 600), 0, 0);
      ss.Apply();
      var store = ss;
       string myFileName = "Screenshot" + System.DateTime.Now.Hour + System.DateTime.Now.Minute +                  System.DateTime.Now.Second + ".png";
      string filePath = Path.Combine(Application.persistentDataPath+"/ "+ myFileName);
      File.WriteAllBytes(filePath, ss.EncodeToPNG());
      Debug.Log(Application.persistentDataPath + "path");
    }
</code>```

Resulting Image

Body:
I try to take a screenshot on Oculus devices using Unity C# Script. But the result only shows a black or white image. I think read pixel is not working correctly. Can anyone help with the solution?

    public void PressedButton()
    {
        StartCoroutine(TakeScreenshotAndShare());
    }
    private IEnumerator TakeScreenshotAndShare()
    {
     yield return new WaitForEndOfFrame();
      Texture2D ss = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
      ss.ReadPixels(new Rect(0, 0, 1000, 600), 0, 0);
      ss.Apply();
      var store = ss;
       string myFileName = "Screenshot" + System.DateTime.Now.Hour + System.DateTime.Now.Minute +                  System.DateTime.Now.Second + ".png";
      string filePath = Path.Combine(Application.persistentDataPath+"/ "+ myFileName);
      File.WriteAllBytes(filePath, ss.EncodeToPNG());
      Debug.Log(Application.persistentDataPath + "path");
    }

Resulting Image


问:
I want to host a node.js openlayer app with heroku
`
We're sorry this build is failing! You can troubleshoot common issues here:
https://devcenter.heroku.com/articles/troubleshooting-node-deploys

```<code>   If you're stuck, please submit a ticket so we can help:
   https://help.heroku.com/

   Love,
   Heroku
</code>```

!     Push rejected, failed to compile Node.js app.
!     Push failed

i try to modify package.json and dependencies`

Body:
`
We're sorry this build is failing! You can troubleshoot common issues here:
https://devcenter.heroku.com/articles/troubleshooting-node-deploys

   If you're stuck, please submit a ticket so we can help:
   https://help.heroku.com/

   Love,
   Heroku

!     Push rejected, failed to compile Node.js app.
!     Push failed

i try to modify package.json and dependencies`


问:
Python pyopenssl TYPE_EC pkey
As the title suggest, anyone know if there will be any support for TYPE_EC while generating pkey?

as i could see from the current version of the Python OpenSSL v.23.0.0 there are no support for EC.

Is there any alternative ?

thanks in advance

Title: Python pyopenssl TYPE_EC pkey


问:
Mask R-CNN doesn't work properly on its own examples/
I cloned the project from https://github.com/akTwelve/Mask_RCNN/blob/master/mrcnn/visualize.py
But it works like this on its own examples. How can I fix this?
here is the segmented image

I tried to downgrade tensorflow from 2.11 to 2.5, but it did not help.


问:
Python subplot of tricontourf
I would like to do subplots of tricontourf. I tried this but it does not work, I obtain the error message: RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

```<code>fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
fig = plt.figure()
# background_field
levels=np.linspace(0,max(max_ls, lc),5)
levels=np.r_[levels,[lc_smooth_min]]
levels=np.sort(levels)
print(levels)
ax1.tricontourf(X, Y, background_field(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")

# echelle_kolmogorov
ax2.tricontourf(X, Y, echelle_1(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")

# echelle_HTLES
ax3.tricontourf(X, Y, echelle_2(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
</code>```

Is it possible to perform subplots of tricontourf without using imshow?
Can someone explain me how should I do it?

Thanks a lot !

Title: Python subplot of tricontourf

Body:
I would like to do subplots of tricontourf. I tried this but it does not work, I obtain the error message: RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
fig = plt.figure()
# background_field
levels=np.linspace(0,max(max_ls, lc),5)
levels=np.r_[levels,[lc_smooth_min]]
levels=np.sort(levels)
print(levels)
ax1.tricontourf(X, Y, background_field(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")

# echelle_kolmogorov
ax2.tricontourf(X, Y, echelle_1(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")

# echelle_HTLES
ax3.tricontourf(X, Y, echelle_2(X,Y,Z), levels, cmap ='inferno')
plt.colorbar(boundaries=levels)
plt.xlim([0, 3])
plt.ylim([0, 0.5])
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

Is it possible to perform subplots of tricontourf without using imshow?
Can someone explain me how should I do it?

Thanks a lot !


问:
Is any way to write texts in html and convert to JSX with bootstrap style?
I am just building a simple Resume CV project, with React and GitHub pages. One section, is Blog.

I would like to write my articles in plain text, convert through html and bootstrap style, and after that to JSX.

I know it's easy to find online free solutions to convert from plain text to html, and after that to JSX, but not with bootstrap class styled, and even complex, not straightforward like: plain text to JSX with bootstrap class.

Any help or approach would be great.


问:
Microsoft.IdentityModel.Clients.ActiveDirectory is deprecated, use Microsoft.Identity.Client
I am using Microsoft.IdentityModel.Clients.ActiveDirectory NuGet and for an app I retrieve token like below code:

```<code>public async Task<IotHubClient> GetIotHubClient()
{
    var authContext = new AuthenticationContext(_configuration["IoTHub:Credentials:Authority"]);
    var credential = new ClientCredential(_configuration["IoTHub:Credentials:ClientId"], await _secretKeyReader.GetSecretValue("IotHubScalingAppKey"));
    var token = await authContext.AcquireTokenAsync(_configuration["IoTHub:Credentials:Resource"], credential);

    if (token == null) return null;

    var credentials = new TokenCredentials(token.AccessToken);
    var client = new IotHubClient(credentials)
    {
        SubscriptionId = _configuration["IoTHub:Credentials:SubscriptionId"]
    };

    return client;
}
</code>```

Since the package Microsoft.IdentityModel.Clients.ActiveDirectory is deprecated, I'm trying to use the package Microsoft.Identity.Client, but the above method no longer works.

What's the way to get the token?

Body:
I am using Microsoft.IdentityModel.Clients.ActiveDirectory NuGet and for an app I retrieve token like below code:

public async Task<IotHubClient> GetIotHubClient()
{
    var authContext = new AuthenticationContext(_configuration["IoTHub:Credentials:Authority"]);
    var credential = new ClientCredential(_configuration["IoTHub:Credentials:ClientId"], await _secretKeyReader.GetSecretValue("IotHubScalingAppKey"));
    var token = await authContext.AcquireTokenAsync(_configuration["IoTHub:Credentials:Resource"], credential);

    if (token == null) return null;

    var credentials = new TokenCredentials(token.AccessToken);
    var client = new IotHubClient(credentials)
    {
        SubscriptionId = _configuration["IoTHub:Credentials:SubscriptionId"]
    };

    return client;
}

Since the package Microsoft.IdentityModel.Clients.ActiveDirectory is deprecated, I'm trying to use the package Microsoft.Identity.Client, but the above method no longer works.

What's the way to get the token?


问:
How to change "localhost" name on docker php-apache?
I'm using php-apache image on Docker. I want to change my default domain name, from localhost, to another one.
So instead of http://localhost:81, I need to connect by: http://mycustomname:81
How I can achieve this?</p>


问:
Finding status of website with Cloudflare DDoS protection
Trying to check the status of an website using the following code:

```<code>    <?php
    $url = 'https://shop.bbc.com/';
    list($status) = get_headers($url);
    if (strpos($status, '404') !== FALSE) {
        echo '404 error';
    } else {
        echo $status;
    }
    ?>
</code>```

However since the website is protected by cloudflare it gives a 403 forbidden error when I try to access it. Is there any known workarounds for this problem?

Body:
Trying to check the status of an website using the following code:

    <?php
    $url = 'https://shop.bbc.com/';
    list($status) = get_headers($url);
    if (strpos($status, '404') !== FALSE) {
        echo '404 error';
    } else {
        echo $status;
    }
    ?>

However since the website is protected by cloudflare it gives a 403 forbidden error when I try to access it. Is there any known workarounds for this problem?


问:
Publishing to Github Packages from Jenkins Using Cake
I'm having an issue publishing to Github Packages from Jenkins using Cake.

The push task looks like this:

```<code>Task(nugetPushTask)
 .WithCriteria(() => isPublishBranch)
 .IsDependentOn(packTask)
 .Does(() => {

    foreach(var file in GetFiles(nugetFilesPath)) {
        DotNetNuGetPush(file, new DotNetNuGetPushSettings {
            ApiKey = "key_gdhsjgjhjkeykeykey",
            Source = "https://nuget.pkg.github.com/yourOrganizationOrAccount/index.json"
        });
    }

 });
</code>```

Interestingly, I can successfully push the package with the following command:

dotnet nuget push nameofpackage.1.0.0.nupkg --source github --api-key key_gdhsjgjhjkeykeykey

using a shell prompt.

The error which I see in the build log for that step is:

An error occurred when executing task 'PublishGithub'.

System.Exception: Github Package Key Environment Variable is not set
correctly.

at Submission#0.<>b__0_7(ICakeContext context)

at
Cake.Core.CakeTaskBuilderExtensions.<>c__DisplayClass39_0.b__0(ICakeContext
context) in
C:\projects\cake\src\Cake.Core\CakeTaskBuilder.Execution.cs:line 81

at Cake.Core.CakeTask.Execute(ICakeContext context) in
C:\projects\cake\src\Cake.Core\CakeTask.cs:line 119

at Cake.Core.DefaultExecutionStrategy.ExecuteAsync(CakeTask task,
ICakeContext context) in
C:\projects\cake\src\Cake.Core\DefaultExecutionStrategy.cs:line 69

at Cake.Core.CakeEngine.ExecuteTaskAsync(ICakeContext context,
IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task,
CakeReport report) in
C:\projects\cake\src\Cake.Core\CakeEngine.cs:line 318

Can anyone advise how to get Cake to do what the CLI command is doing.

Thanks

Body:
I'm having an issue publishing to Github Packages from Jenkins using Cake.

The push task looks like this:

Task(nugetPushTask)
 .WithCriteria(() => isPublishBranch)
 .IsDependentOn(packTask)
 .Does(() => {

    foreach(var file in GetFiles(nugetFilesPath)) {
        DotNetNuGetPush(file, new DotNetNuGetPushSettings {
            ApiKey = "key_gdhsjgjhjkeykeykey",
            Source = "https://nuget.pkg.github.com/yourOrganizationOrAccount/index.json"
        });
    }

 });

Interestingly, I can successfully push the package with the following command:

dotnet nuget push nameofpackage.1.0.0.nupkg --source github --api-key key_gdhsjgjhjkeykeykey

using a shell prompt.

The error which I see in the build log for that step is:

An error occurred when executing task 'PublishGithub'.

System.Exception: Github Package Key Environment Variable is not set
correctly.

at Submission#0.<>b__0_7(ICakeContext context)

at
Cake.Core.CakeTaskBuilderExtensions.<>c__DisplayClass39_0.b__0(ICakeContext
context) in
C:\projects\cake\src\Cake.Core\CakeTaskBuilder.Execution.cs:line 81

at Cake.Core.CakeTask.Execute(ICakeContext context) in
C:\projects\cake\src\Cake.Core\CakeTask.cs:line 119

at Cake.Core.DefaultExecutionStrategy.ExecuteAsync(CakeTask task,
ICakeContext context) in
C:\projects\cake\src\Cake.Core\DefaultExecutionStrategy.cs:line 69

at Cake.Core.CakeEngine.ExecuteTaskAsync(ICakeContext context,
IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task,
CakeReport report) in
C:\projects\cake\src\Cake.Core\CakeEngine.cs:line 318

Can anyone advise how to get Cake to do what the CLI command is doing.

Thanks


问:
How to authenticate user with AWS Cognito in Vue.js using Javascript
I am facing the issue that I cannot fully undertsand how to call a function that uses a callback and get the results of the callback returned in a way where the data from the response becomes available to a Vue application.

```<code>async loginUser(username, password) {
        AWS.config.update({region : region});

        const payload = {
            AuthFlow: "USER_PASSWORD_AUTH",
            ClientId: clientId,
            AuthParameters : {
                USERNAME: username,
                PASSWORD: password
            }
        }

        var cognito = new AWS.CognitoIdentityServiceProvider();
        return cognito.initiateAuth(payload, function(err,data) {
            if (err) {
                alert("Error: " + err);
                return null;
            }
            else {
                tokenData = data["AuthenticationResult"];
                console.log(tokenData);
                return tokenData;
            }
        })
    }
</code>```

I want the tokenData to be what is returned when calling loginUser, but no matter what I try to do the data from the cognito.initiateAuth, that should be used in my application to validate a sign in, will just be null and not usable.

Hope you guys can help!
Thanks

I tried different solutions using promises, async/await, while loops trying to wait for the response to contain data, but nothing seems to work. I can see the data being printed correctly in the callback, but how do it get this data to pass on to the return of loginUser.

Body:
I am facing the issue that I cannot fully undertsand how to call a function that uses a callback and get the results of the callback returned in a way where the data from the response becomes available to a Vue application.

async loginUser(username, password) {
        AWS.config.update({region : region});

        const payload = {
            AuthFlow: "USER_PASSWORD_AUTH",
            ClientId: clientId,
            AuthParameters : {
                USERNAME: username,
                PASSWORD: password
            }
        }

        var cognito = new AWS.CognitoIdentityServiceProvider();
        return cognito.initiateAuth(payload, function(err,data) {
            if (err) {
                alert("Error: " + err);
                return null;
            }
            else {
                tokenData = data["AuthenticationResult"];
                console.log(tokenData);
                return tokenData;
            }
        })
    }

I want the tokenData to be what is returned when calling loginUser, but no matter what I try to do the data from the cognito.initiateAuth, that should be used in my application to validate a sign in, will just be null and not usable.

Hope you guys can help!
Thanks

I tried different solutions using promises, async/await, while loops trying to wait for the response to contain data, but nothing seems to work. I can see the data being printed correctly in the callback, but how do it get this data to pass on to the return of loginUser.


问:
SAML2-SLO using Spring Security 6 does not send request to SAML server
I configured SAML2 registrations according to the docs and got SAML2 login working. Unfortunately I could not figure out how to get the logout working. When sending a POST to /logout, the user is logged out of the system itself, but not logged out at the AP. There is no saml2:LogoutRequest sent to the AP and the SAML session attributes are not cleared.

Debugging shows, Saml2LogoutRequestFilter is not used first-hand, since the endpoints do not match and - of course - the user does not send a saml2:LogoutRequest object; so this is expected. Saml2LogoutResponseFilter also is not utilized, since this whould only be used processing logout answers from the AP.

What is utilized, is the LogoutFilter. What I unserstood reading the docs was, this would first log out the user from the system itself (which is fine), and afterward send a saml2:LogoutRequest to the AP, which is never done.

The configuration reads as:

spring:
  security:
    saml2:
      relyingparty:
        registration:
          saml:
            acs:
              binding: POST
              location: "{baseUrl}/sso/{registrationId}/response"
            assertingparty:
              entity-id: "http://localhost:8000/saml2/idp/metadata.php"
              metadata-uri: "http://localhost:8000/saml2/idp/metadata.php"
              singlesignon:
                url: "http://localhost:8000/saml2/idp/SSOService.php"
                sign-request: false
              singlelogout:
                url: "http://localhost:8000/saml2/idp/SingleLogoutService.php"
                binding: REDIRECT
            entity-id: "localhost"
            singlelogout:
              url: "{baseUrl}/sso/logout/saml"
              binding: POST
              response-url: "{baseUrl}/sso/logout/saml"
```
<p>and the filter config looks like that:</p>
<pre class="lang-kotlin prettyprint-override"><code>    @Bean
    fun filterChain(http: HttpSecurity/*, registrations: RelyingPartyRegistrationRepository*/): SecurityFilterChain {
        ...
        // saml login
        http.saml2Login { saml2LoginConfigurer ->
            saml2LoginConfigurer
                .authenticationRequestUri("/sso/{registrationId}/login")
                .loginProcessingUrl(samlResponseUrl.replace("{baseUrl}", ""))
                .authenticationManager(ProviderManager(samlAuthenticationProvider()))
                .defaultSuccessUrl(samlRedirectUrl)
                .failureUrl(samlRedirectUrlNewUser)
        }
        // saml (sso) logout
        http.saml2Logout { saml2LogoutConfigurer ->
            saml2LogoutConfigurer
                .logoutRequest { request -> request.logoutUrl("/sso/logout/saml") }
                .logoutResponse { response -> response.logoutUrl("/sso/logout/saml") }
        }

</code>```

Body:
I configured SAML2 registrations according to the docs and got SAML2 login working. Unfortunately I could not figure out how to get the logout working. When sending a POST to /logout, the user is logged out of the system itself, but not logged out at the AP. There is no saml2:LogoutRequest sent to the AP and the SAML session attributes are not cleared.

Debugging shows, Saml2LogoutRequestFilter is not used first-hand, since the endpoints do not match and - of course - the user does not send a saml2:LogoutRequest object; so this is expected. Saml2LogoutResponseFilter also is not utilized, since this whould only be used processing logout answers from the AP.

What is utilized, is the LogoutFilter. What I unserstood reading the docs was, this would first log out the user from the system itself (which is fine), and afterward send a saml2:LogoutRequest to the AP, which is never done.

The configuration reads as:

spring:
  security:
    saml2:
      relyingparty:
        registration:
          saml:
            acs:
              binding: POST
              location: "{baseUrl}/sso/{registrationId}/response"
            assertingparty:
              entity-id: "http://localhost:8000/saml2/idp/metadata.php"
              metadata-uri: "http://localhost:8000/saml2/idp/metadata.php"
              singlesignon:
                url: "http://localhost:8000/saml2/idp/SSOService.php"
                sign-request: false
              singlelogout:
                url: "http://localhost:8000/saml2/idp/SingleLogoutService.php"
                binding: REDIRECT
            entity-id: "localhost"
            singlelogout:
              url: "{baseUrl}/sso/logout/saml"
              binding: POST
              response-url: "{baseUrl}/sso/logout/saml"

and the filter config looks like that:

    @Bean
    fun filterChain(http: HttpSecurity/*, registrations: RelyingPartyRegistrationRepository*/): SecurityFilterChain {
        ...
        // saml login
        http.saml2Login { saml2LoginConfigurer ->
            saml2LoginConfigurer
                .authenticationRequestUri("/sso/{registrationId}/login")
                .loginProcessingUrl(samlResponseUrl.replace("{baseUrl}", ""))
                .authenticationManager(ProviderManager(samlAuthenticationProvider()))
                .defaultSuccessUrl(samlRedirectUrl)
                .failureUrl(samlRedirectUrlNewUser)
        }
        // saml (sso) logout
        http.saml2Logout { saml2LogoutConfigurer ->
            saml2LogoutConfigurer
                .logoutRequest { request -> request.logoutUrl("/sso/logout/saml") }
                .logoutResponse { response -> response.logoutUrl("/sso/logout/saml") }
        }