问:
How to manage multiple sockets in Python?
How to open multiple sockets so that they work in parallel?

I found how to open one socket. What should I change to make it work for many?

```<code>if __name__ == '__main__':

   import sys

   from twisted.python import log
   from twisted.internet import reactor
   log.startLogging(sys.stdout)

   from autobahn.twisted.websocket import WebSocketClientProtocol

   class MyClientProtocol(WebSocketClientProtocol):

       def onOpen(self):
          self.sendMessage(u"[\"text\", \"connect user1 password1\",{}]".encode('utf8'))

       def onMessage(self, payload, isBinary):
          if isBinary:
             print("Binary message received: {0} bytes".format(len(payload)))
          else:
             print("Text message received: {0}".format(payload.decode('utf8')))

   from autobahn.twisted.websocket import WebSocketClientFactory
   factory = WebSocketClientFactory()
   factory.protocol = MyClientProtocol

   reactor.connectTCP("127.0.0.1", 4002, factory)
   reactor.run()
</code>```

Body:
How to open multiple sockets so that they work in parallel?

I found how to open one socket. What should I change to make it work for many?

if __name__ == '__main__':

   import sys

   from twisted.python import log
   from twisted.internet import reactor
   log.startLogging(sys.stdout)

   from autobahn.twisted.websocket import WebSocketClientProtocol

   class MyClientProtocol(WebSocketClientProtocol):

       def onOpen(self):
          self.sendMessage(u"[\"text\", \"connect user1 password1\",{}]".encode('utf8'))

       def onMessage(self, payload, isBinary):
          if isBinary:
             print("Binary message received: {0} bytes".format(len(payload)))
          else:
             print("Text message received: {0}".format(payload.decode('utf8')))

   from autobahn.twisted.websocket import WebSocketClientFactory
   factory = WebSocketClientFactory()
   factory.protocol = MyClientProtocol

   reactor.connectTCP("127.0.0.1", 4002, factory)
   reactor.run()


来源: stackexchange

问:
I am trying to get redirected to the login page after filling the info on the register page its not working
server.js

```<code>const express=require('express')
const app=express()
const bcrypt=require('bcrypt')
const users=[]
var ejs=require('ejs')
app.set('view-engine','ejs')
app.use(express.urlencoded({extended:false}))
app.get('/',(req,res)=>{
    res.render('index.ejs',{name:'Satish'})
})
app.post('/login',(req,res)=>{

})
app.get('/login',(req,res)=>{
    res.render('login.ejs')
})
app.get('/register',(req,res)=>{
    res.render('register.ejs')
})
app.post('/register', async(req,res)=>{
    try{
        const hashedPassword=await bcrypt.hash(req.body.password,10)
        users.push({
            id:Date.now.toString(),
            name:req.body.name,
            email:req.body.email,
            password:hashedPassword
        })
        res.redirect('www.google.com')

    }
    catch{
        res.redirect('/register')
    }
   console.log(users)
})

app.listen(3145)
</code>```

this is the server.js code

its not redirecting me, even though i can see the value saved in the url. I have made a form for login and register page and everything is working well.I am a beginner in  node.js please help me

ContentLicense: CC BY-SA 4.0

Body:
server.js

const express=require('express')
const app=express()
const bcrypt=require('bcrypt')
const users=[]
var ejs=require('ejs')
app.set('view-engine','ejs')
app.use(express.urlencoded({extended:false}))
app.get('/',(req,res)=>{
    res.render('index.ejs',{name:'Satish'})
})
app.post('/login',(req,res)=>{

})
app.get('/login',(req,res)=>{
    res.render('login.ejs')
})
app.get('/register',(req,res)=>{
    res.render('register.ejs')
})
app.post('/register', async(req,res)=>{
    try{
        const hashedPassword=await bcrypt.hash(req.body.password,10)
        users.push({
            id:Date.now.toString(),
            name:req.body.name,
            email:req.body.email,
            password:hashedPassword
        })
        res.redirect('www.google.com')

    }
    catch{
        res.redirect('/register')
    }
   console.log(users)
})

app.listen(3145)

this is the server.js code

its not redirecting me, even though i can see the value saved in the url. I have made a form for login and register page and everything is working well.I am a beginner in  node.js please help me


问:
I was running a test on my signal.py file and i am getting 'ValueError: seek of closed file' error
here is the signals.py file inside main app

and here is the test_signals.py file
enter image description here

the full error is


问:
How to make the 'dashboard' view returns if the user is logged in, else 'welcome' view return on Laravel?
I will give an example from Stack Overflow;

The page that returns when the user is not logged in:
here

The page that returns when the user is logged in: here

Different views are shown on the same route ('/'). I wanna do exactly this.

I am using Laravel Jetstream.

I couldn't figure out whether I should do it from routes/web.php, User Controller or Jetstream Controllers.

```<code><?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\LoginController;

Route::middleware('admin:admin')->group(function () {
    Route::get('admin/login', [LoginController::class, 'loginForm']);
    Route::post('admin/login', [LoginController::class, 'store'])->name('admin.login');
});

Route::middleware(['auth:sanctum,admin', config('jetstream.auth_session'), 'verified'
])->group(function () {
    Route::get('admin/dashboard', function () {
        return view('dashboard');
    })->name('admin.dashboard')->middleware('auth:admin');
});

Route::middleware(['auth:sanctum', config('jetstream.auth_session'), 'verified'
])->group(function () {
    Route::get('/', function () {
        return view('dashboard');
    })->name('dashboard');
});

</code>```

Body:
I will give an example from Stack Overflow;

The page that returns when the user is not logged in:
here

The page that returns when the user is logged in: here

Different views are shown on the same route ('/'). I wanna do exactly this.

I am using Laravel Jetstream.

I couldn't figure out whether I should do it from routes/web.php, User Controller or Jetstream Controllers.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\LoginController;

Route::middleware('admin:admin')->group(function () {
    Route::get('admin/login', [LoginController::class, 'loginForm']);
    Route::post('admin/login', [LoginController::class, 'store'])->name('admin.login');
});

Route::middleware(['auth:sanctum,admin', config('jetstream.auth_session'), 'verified'
])->group(function () {
    Route::get('admin/dashboard', function () {
        return view('dashboard');
    })->name('admin.dashboard')->middleware('auth:admin');
});

Route::middleware(['auth:sanctum', config('jetstream.auth_session'), 'verified'
])->group(function () {
    Route::get('/', function () {
        return view('dashboard');
    })->name('dashboard');
});


问:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
Given below is the error. I have added the apache.org.common.lang jar still am getting this . am having these .JARs in my lib folder am is missing on any?

ant-contrib-1.0b3.jar

ant-eclipse-1.0-jvm1.2.jar

avro-1.8.1.jar

mysql-connector-java-8.0.29.jar

org.apache.commons.lang-2.6.jar

sqljdbc4-chs-4.0.2206.100.jar

```<code>h-user@h-primary:~/sqoop-1.4.7/lib$ sqoop eval --connect jdbc:mysql://localhost/HADOOP_BANK_DATA_POC --username root --password xxxxxxxxx --query 'select * from E_INFO'
Warning: /home/h-user/sqoop-1.4.7/../hbase does not exist! HBase imports will fail.
Please set $HBASE_HOME to the root of your HBase installation.
Warning: /home/h-user/sqoop-1.4.7/../hcatalog does not exist! HCatalog jobs will fail.
Please set $HCAT_HOME to the root of your HCatalog installation.
Warning: /home/h-user/sqoop-1.4.7/../accumulo does not exist! Accumulo imports will fail.
Please set $ACCUMULO_HOME to the root of your Accumulo installation.
Warning: /home/h-user/sqoop-1.4.7/../zookeeper does not exist! Accumulo imports will fail.
Please set $ZOOKEEPER_HOME to the root of your Zookeeper installation.
/usr/local/hadoop/libexec/hadoop-functions.sh: line 2366: HADOOP_ORG.APACHE.SQOOP.SQOOP_USER: invalid variable name
/usr/local/hadoop/libexec/hadoop-functions.sh: line 2461: HADOOP_ORG.APACHE.SQOOP.SQOOP_OPTS: invalid variable name
2022-12-24 16:23:55,026 INFO sqoop.Sqoop: Running Sqoop version: 1.4.7
2022-12-24 16:23:55,121 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
2022-12-24 16:23:55,314 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
    at org.apache.sqoop.manager.MySQLManager.initOptionDefaults(MySQLManager.java:73)
    at org.apache.sqoop.manager.SqlManager.<init>(SqlManager.java:89)
    at com.cloudera.sqoop.manager.SqlManager.<init>(SqlManager.java:33)
    at org.apache.sqoop.manager.GenericJdbcManager.<init>(GenericJdbcManager.java:51)
    at com.cloudera.sqoop.manager.GenericJdbcManager.<init>(GenericJdbcManager.java:30)
    at org.apache.sqoop.manager.CatalogQueryManager.<init>(CatalogQueryManager.java:46)
    at com.cloudera.sqoop.manager.CatalogQueryManager.<init>(CatalogQueryManager.java:31)
    at org.apache.sqoop.manager.InformationSchemaManager.<init>(InformationSchemaManager.java:38)
    at com.cloudera.sqoop.manager.InformationSchemaManager.<init>(InformationSchemaManager.java:31)
    at org.apache.sqoop.manager.MySQLManager.<init>(MySQLManager.java:65)
    at org.apache.sqoop.manager.DefaultManagerFactory.accept(DefaultManagerFactory.java:67)
    at org.apache.sqoop.ConnFactory.getManager(ConnFactory.java:184)
    at org.apache.sqoop.tool.BaseSqoopTool.init(BaseSqoopTool.java:272)
    at org.apache.sqoop.tool.EvalSqlTool.run(EvalSqlTool.java:56)
    at org.apache.sqoop.Sqoop.run(Sqoop.java:147)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
    at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:183)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:234)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:243)
    at org.apache.sqoop.Sqoop.main(Sqoop.java:252)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.StringUtils
    at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 20 more

</code>```

Body:
Given below is the error. I have added the apache.org.common.lang jar still am getting this . am having these .JARs in my lib folder am is missing on any?

ant-contrib-1.0b3.jar

ant-eclipse-1.0-jvm1.2.jar

avro-1.8.1.jar

mysql-connector-java-8.0.29.jar

org.apache.commons.lang-2.6.jar

sqljdbc4-chs-4.0.2206.100.jar

h-user@h-primary:~/sqoop-1.4.7/lib$ sqoop eval --connect jdbc:mysql://localhost/HADOOP_BANK_DATA_POC --username root --password xxxxxxxxx --query 'select * from E_INFO'
Warning: /home/h-user/sqoop-1.4.7/../hbase does not exist! HBase imports will fail.
Please set $HBASE_HOME to the root of your HBase installation.
Warning: /home/h-user/sqoop-1.4.7/../hcatalog does not exist! HCatalog jobs will fail.
Please set $HCAT_HOME to the root of your HCatalog installation.
Warning: /home/h-user/sqoop-1.4.7/../accumulo does not exist! Accumulo imports will fail.
Please set $ACCUMULO_HOME to the root of your Accumulo installation.
Warning: /home/h-user/sqoop-1.4.7/../zookeeper does not exist! Accumulo imports will fail.
Please set $ZOOKEEPER_HOME to the root of your Zookeeper installation.
/usr/local/hadoop/libexec/hadoop-functions.sh: line 2366: HADOOP_ORG.APACHE.SQOOP.SQOOP_USER: invalid variable name
/usr/local/hadoop/libexec/hadoop-functions.sh: line 2461: HADOOP_ORG.APACHE.SQOOP.SQOOP_OPTS: invalid variable name
2022-12-24 16:23:55,026 INFO sqoop.Sqoop: Running Sqoop version: 1.4.7
2022-12-24 16:23:55,121 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
2022-12-24 16:23:55,314 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
    at org.apache.sqoop.manager.MySQLManager.initOptionDefaults(MySQLManager.java:73)
    at org.apache.sqoop.manager.SqlManager.<init>(SqlManager.java:89)
    at com.cloudera.sqoop.manager.SqlManager.<init>(SqlManager.java:33)
    at org.apache.sqoop.manager.GenericJdbcManager.<init>(GenericJdbcManager.java:51)
    at com.cloudera.sqoop.manager.GenericJdbcManager.<init>(GenericJdbcManager.java:30)
    at org.apache.sqoop.manager.CatalogQueryManager.<init>(CatalogQueryManager.java:46)
    at com.cloudera.sqoop.manager.CatalogQueryManager.<init>(CatalogQueryManager.java:31)
    at org.apache.sqoop.manager.InformationSchemaManager.<init>(InformationSchemaManager.java:38)
    at com.cloudera.sqoop.manager.InformationSchemaManager.<init>(InformationSchemaManager.java:31)
    at org.apache.sqoop.manager.MySQLManager.<init>(MySQLManager.java:65)
    at org.apache.sqoop.manager.DefaultManagerFactory.accept(DefaultManagerFactory.java:67)
    at org.apache.sqoop.ConnFactory.getManager(ConnFactory.java:184)
    at org.apache.sqoop.tool.BaseSqoopTool.init(BaseSqoopTool.java:272)
    at org.apache.sqoop.tool.EvalSqlTool.run(EvalSqlTool.java:56)
    at org.apache.sqoop.Sqoop.run(Sqoop.java:147)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
    at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:183)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:234)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:243)
    at org.apache.sqoop.Sqoop.main(Sqoop.java:252)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.StringUtils
    at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 20 more


问:
Trying to improve my search bar using Flutter
Im trying to improve my search bar using flutter but it doesnt seem to work. I want it so that the user can find the note title without to write the whole note title. I works but i want to improve it. Any help is greatly apprieciated

Original code:

```<code>Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: _searchController.text.isEmpty
        ? FirebaseFirestore.instance.collection('notes').snapshots()
        : FirebaseFirestore.instance
            .collection('notes')
            .where('note_title', isEqualTo: _searchController.text)
            .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (snapshot.hasData) {
        final List<DocumentSnapshot> notes = snapshot.data!.docs;
        final List<DocumentSnapshot> matchingNotes = notes
            .where((note) => note['note_title']
                .toString()
                .toLowerCase()
                .contains(_searchController.text.toLowerCase()))
            .toList();
        return GridView.count(
          crossAxisCount: 2,
          children: snapshot.data!.docs
              .map((note) => noteCard(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                NoteReaderScreen(note)));
                  }, note))
              .toList(),
        );
      }
      return Container();
    },
  ),
)
</code>```

Modified code:

```<code>Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: _searchController.text.isEmpty
        ? FirebaseFirestore.instance.collection('notes').snapshots()
        : FirebaseFirestore.instance
            .collection('notes')
            .where('note_title',
                isGreaterThanOrEqualTo:
                    _searchController.text.toLowerCase())
            .where('note_title',
                isLessThanOrEqualTo:
                    '${_searchController.text.toLowerCase()}\uf8ff')
            .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (snapshot.hasData) {
        final List<DocumentSnapshot> notes = snapshot.data!.docs;
        final List<DocumentSnapshot> matchingNotes = notes
            .where((note) => note['note_title']
                .toString()
                .toLowerCase()
                .contains(_searchController.text.toLowerCase()))
            .toList();
        return GridView.count(
          crossAxisCount: 2,
          children: snapshot.data!.docs
              .map((note) => noteCard(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                NoteReaderScreen(note)));
                  }, note))
              .toList(),
        );
      }
      return Container();
    },
  ),
)
</code>```

I tried adding:

```<code>.where('note_title', isGreaterThanOrEqualTo: _searchController.text.toLowerCase())
  .where('note_title', isLessThanOrEqualTo: _searchController.text.toLowerCase() + '\uf8ff')
</code>```

and it doesnt have an effect.

Body:
Im trying to improve my search bar using flutter but it doesnt seem to work. I want it so that the user can find the note title without to write the whole note title. I works but i want to improve it. Any help is greatly apprieciated

Original code:

Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: _searchController.text.isEmpty
        ? FirebaseFirestore.instance.collection('notes').snapshots()
        : FirebaseFirestore.instance
            .collection('notes')
            .where('note_title', isEqualTo: _searchController.text)
            .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (snapshot.hasData) {
        final List<DocumentSnapshot> notes = snapshot.data!.docs;
        final List<DocumentSnapshot> matchingNotes = notes
            .where((note) => note['note_title']
                .toString()
                .toLowerCase()
                .contains(_searchController.text.toLowerCase()))
            .toList();
        return GridView.count(
          crossAxisCount: 2,
          children: snapshot.data!.docs
              .map((note) => noteCard(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                NoteReaderScreen(note)));
                  }, note))
              .toList(),
        );
      }
      return Container();
    },
  ),
)

Modified code:

Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: _searchController.text.isEmpty
        ? FirebaseFirestore.instance.collection('notes').snapshots()
        : FirebaseFirestore.instance
            .collection('notes')
            .where('note_title',
                isGreaterThanOrEqualTo:
                    _searchController.text.toLowerCase())
            .where('note_title',
                isLessThanOrEqualTo:
                    '${_searchController.text.toLowerCase()}\uf8ff')
            .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (snapshot.hasData) {
        final List<DocumentSnapshot> notes = snapshot.data!.docs;
        final List<DocumentSnapshot> matchingNotes = notes
            .where((note) => note['note_title']
                .toString()
                .toLowerCase()
                .contains(_searchController.text.toLowerCase()))
            .toList();
        return GridView.count(
          crossAxisCount: 2,
          children: snapshot.data!.docs
              .map((note) => noteCard(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                NoteReaderScreen(note)));
                  }, note))
              .toList(),
        );
      }
      return Container();
    },
  ),
)

I tried adding:

.where('note_title', isGreaterThanOrEqualTo: _searchController.text.toLowerCase())
  .where('note_title', isLessThanOrEqualTo: _searchController.text.toLowerCase() + '\uf8ff')

and it doesnt have an effect.


问:
Creating dynamic split functionality using sliders
Currently I'm creating an application where the user can split the bill to individual candidates. Initially the slider values are equal for all candidates and the user can adjust them on the page accordingly where to increase someone's percentage, they have to decrease someone else's first. If the total amount of all sliders equal to 100, the sliders cannot move further which I'm achieving using upperLimit in the slider library

So far I've been able to achieve this with 2 users where I basically hardcoded the states and the logic by saying if when slider 1 is moved and state1 + state2 < 101 then pass the value 100 - (slider 1 value) to the slider 2 value. I'm achieving this with the following code:

```<code>const SplitBillPage = () => {
  const splitUsers = 2;
  const equalValueSplit = 100 / splitUsers;
  const [range, setRange] = useState(equalValueSplit + '%');
  const [secondRange, setSecondRange] = useState(equalValueSplit + '%');
  const [limit, setLimit] = useState(100);
  const [limitSecond, setLimitSecond] = useState(100);

  function rangeSetter(value) {
    setRange(parseInt(value) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    let valueLimit = 100 - parseInt(withoutPercentage);
    if (parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) < 101) {
      setLimitSecond(valueLimit);
    }
  }

  function rangeSetterSecond(value) {
    setSecondRange(parseInt(value) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    let valueLimit = 100 - parseInt(withoutPercentageSecond);
    if (parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) < 101) {
      setLimit(valueLimit);
    }
  }

  return (
    <View>
      <Text>{range}</Text>
      <Slider
        minimumValue={0}
        value={equalValueSplit}
        maximumValue={100}
        upperLimit={limit}
        onValueChange={value => rangeSetter(value)}
      />
      <Text>{secondRange}</Text>
      <Slider
        minimumValue={0}
        value={equalValueSplit}
        maximumValue={100}
        upperLimit={limitSecond}
        onValueChange={value => rangeSetterSecond(value)}
      />
    </View>
  );
};

export default SplitBillPage;
</code>```

Now I'm confused on how to create the logic when the number increases above 2. Here I've used 1 states for each user which are limit and limitSecond, but this doesnt seem efficient when I've 10 users and me creating an individual state for each of them and the using state1 +state2 + ... <101.

So I need a way to solve this logic when the number increases from 2.

Body:
Currently I'm creating an application where the user can split the bill to individual candidates. Initially the slider values are equal for all candidates and the user can adjust them on the page accordingly where to increase someone's percentage, they have to decrease someone else's first. If the total amount of all sliders equal to 100, the sliders cannot move further which I'm achieving using upperLimit in the slider library

So far I've been able to achieve this with 2 users where I basically hardcoded the states and the logic by saying if when slider 1 is moved and state1 + state2 < 101 then pass the value 100 - (slider 1 value) to the slider 2 value. I'm achieving this with the following code:

const SplitBillPage = () => {
  const splitUsers = 2;
  const equalValueSplit = 100 / splitUsers;
  const [range, setRange] = useState(equalValueSplit + '%');
  const [secondRange, setSecondRange] = useState(equalValueSplit + '%');
  const [limit, setLimit] = useState(100);
  const [limitSecond, setLimitSecond] = useState(100);

  function rangeSetter(value) {
    setRange(parseInt(value) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    let valueLimit = 100 - parseInt(withoutPercentage);
    if (parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) < 101) {
      setLimitSecond(valueLimit);
    }
  }

  function rangeSetterSecond(value) {
    setSecondRange(parseInt(value) + '%');
    let x = range;
    let y = secondRange;
    let withoutPercentage = x.replace('%', '');
    let withoutPercentageSecond = y.replace('%', '');
    let valueLimit = 100 - parseInt(withoutPercentageSecond);
    if (parseInt(withoutPercentage) + parseInt(withoutPercentageSecond) < 101) {
      setLimit(valueLimit);
    }
  }

  return (
    <View>
      <Text>{range}</Text>
      <Slider
        minimumValue={0}
        value={equalValueSplit}
        maximumValue={100}
        upperLimit={limit}
        onValueChange={value => rangeSetter(value)}
      />
      <Text>{secondRange}</Text>
      <Slider
        minimumValue={0}
        value={equalValueSplit}
        maximumValue={100}
        upperLimit={limitSecond}
        onValueChange={value => rangeSetterSecond(value)}
      />
    </View>
  );
};

export default SplitBillPage;

Now I'm confused on how to create the logic when the number increases above 2. Here I've used 1 states for each user which are limit and limitSecond, but this doesnt seem efficient when I've 10 users and me creating an individual state for each of them and the using state1 +state2 + ... <101.

So I need a way to solve this logic when the number increases from 2.


问:
WebClient subscribe not working for POST API call which return only HTTP status but no response body
I am trying to asynchronously call the endpoint with the POST HTTP method using WebClient with Java 11 and spring 5.

```<code>Mono<Void> response = client.post()
    .uri(new URI("https://test.org/example"))
    .header("Authorization", "Bearer MY_SECRET_TOKEN")
    .accept(MediaType.APPLICATION_JSON)
    .body(bodyValues)
    .retrieve()
    .bodyToMono(Void.class);

response.subscribe((response)->{
   log.info("This never gets executed , I want to perform DB operations after this");
},error->{
   log.error("In case error this gets executed");
});
</code>```

In case of success, I want to perform some database operations which are not getting executed even response is a success from called API.

Any help will be much appreciated!

I tried changing .bodyToMono(String.class) instead of void but no change in program execution behavior.

Body:
I am trying to asynchronously call the endpoint with the POST HTTP method using WebClient with Java 11 and spring 5.

Mono<Void> response = client.post()
    .uri(new URI("https://test.org/example"))
    .header("Authorization", "Bearer MY_SECRET_TOKEN")
    .accept(MediaType.APPLICATION_JSON)
    .body(bodyValues)
    .retrieve()
    .bodyToMono(Void.class);

response.subscribe((response)->{
   log.info("This never gets executed , I want to perform DB operations after this");
},error->{
   log.error("In case error this gets executed");
});

In case of success, I want to perform some database operations which are not getting executed even response is a success from called API.

Any help will be much appreciated!

I tried changing .bodyToMono(String.class) instead of void but no change in program execution behavior.


问:
CXX1405 error when building with cmake using filePath:D:\..\\CMakeLists.txt: Build command failed. Unable to build the Android project
I have integrated C module to the project. Build is failed while run the app and got the below error,

Task :app:configureCMakeDebug[x86_64] FAILED
Execution failed for task ':app:configureCMakeDebug[x86_64]'.
[CXX1405] error when building with cmake using D:..\CMakeLists.txt: Build command failed.

I've used the below versions in the project,
compileSdk 33
minSdk 26
targetSdk 33

Cmake version - 3.18.1
NDK - 21.4.7075529
Gradle - distributionUrl=https://services.gradle.org/distributions/gradle-7.4-bin.zip

Any help will be appreciated. Thanks!


问:
Unable to access php variables returned by class method using include_once and ob_start function
I have 2 classes one is Language.php and the second is Landing.php.

The language class contains :

```<code><?php

namespace App\Core;

class Language {

    function getLanguage($language = null)
    {
        $lang = $this->setLanguage($language);
        if(file_exists(LANGUAGE_DIR ."/".$lang.".php"))
        {
            ob_start();
            include LANGUAGE_DIR."/".$lang.".php"; //INCLUDE EN.PHP
            return ob_get_clean();

        } else {

            ob_start();
            include LANGUAGE_DIR."/en.php";
            return ob_get_clean();
        }
    }
}
</code>```

The landing class contains:

```<code><?php

namespace App\Models\Landing;

use App\Core\Database;
use App\Core\Language;

class Landing extends Database
{
    public function reportBug(string $language, int $video, string $sender, string $commentaire)
    {
        $lang = new Language;
        $lang->getLanguage($language);   //THIS DOESN'T WORK
        //include LANGUAGE_DIR."/".$language.".php";  //UNCOMMENT THIS LINE EVERYTHING WORKS

        //Save the comment
        $rowCount = $this->insert("INSERT INTO comments(video, message)VALUES(?, ?)", array($video, $commentaire), false);
        if($rowCount == 1){
            return '1'; //Success
        }else {
            return '<div class="alert alert-danger">'. $commentNotSent .'</div>'; //$commentNotSent throw error
        }
    }

}
</code>```

I have also this file en.php:

```<code><?php

$commentNotSent = "Comment not sent";
</code>```

The problem is that I cannot display $commentNotSent variable. Can you help me please?

Body:
I have 2 classes one is Language.php and the second is Landing.php.

The language class contains :

<?php

namespace App\Core;

class Language {

    function getLanguage($language = null)
    {
        $lang = $this->setLanguage($language);
        if(file_exists(LANGUAGE_DIR ."/".$lang.".php"))
        {
            ob_start();
            include LANGUAGE_DIR."/".$lang.".php"; //INCLUDE EN.PHP
            return ob_get_clean();

        } else {

            ob_start();
            include LANGUAGE_DIR."/en.php";
            return ob_get_clean();
        }
    }
}

The landing class contains:

<?php

namespace App\Models\Landing;

use App\Core\Database;
use App\Core\Language;

class Landing extends Database
{
    public function reportBug(string $language, int $video, string $sender, string $commentaire)
    {
        $lang = new Language;
        $lang->getLanguage($language);   //THIS DOESN'T WORK
        //include LANGUAGE_DIR."/".$language.".php";  //UNCOMMENT THIS LINE EVERYTHING WORKS

        //Save the comment
        $rowCount = $this->insert("INSERT INTO comments(video, message)VALUES(?, ?)", array($video, $commentaire), false);
        if($rowCount == 1){
            return '1'; //Success
        }else {
            return '
'. $commentNotSent .'
'; //$commentNotSent throw error
        }
    }

}

I have also this file en.php:

<?php

$commentNotSent = "Comment not sent";

The problem is that I cannot display $commentNotSent variable. Can you help me please?


问:
Detect DOM change in Javascript or Jquery
An advertiser inserts an iframe on my website in the Dom via an external script. The content of the iframe takes a long time to load the browser. I want, that as soon as the iframe appears in the dom, the iframe is removed again. The iframe has no ID.

My solution so far is setInterval. I check a total of 10 times at intervals of 600ms whether the iframe has been inserted and if so, then remove the iframe and stop the interval. I dont like working with setInterval for performance issues and would rather use addeventlistener or mutationobserver but it doesn't work.

This is what I have at the moment and it works:

```<code>var removeRun = 0;
  intervalremove = setInterval(function () {
    removeRun += 1;
    if (removeRun === 10) {
      clearInterval(intervalremove);
    }

    if($("iframe[src*='//ad.adserver.cy']").length == 1) {
    console.log('dom contains adserver iframe');

    $("iframe[src*='//ad.adserver.cy']").remove();

    clearInterval(intervalremove);

    console.log('iframe removed / interval stoped');
    }

  }, 600);
</code>```

I already searched for mutation and addeventlistener and found many sites. e.g. B.

Is there a JavaScript / jQuery DOM change listener?

So far I haven't managed to build any code that works. Thanks for your help.

Here is one of the hundreds mutationobserver codes I tried

```<code>   // Select the node that will be observed for mutations
  var target =
 document.querySelector("iframe[src*='csync.smartadserver.com']");

 // Create an observer instance
 var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
   var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added

    console.log('iframe found');

    });
   }
  });
  });

  // Configuration of the observer:
var config = {
   attributes: true,
   childList: true,
   characterData: true
  };

 // Pass in the target node, as well as the observer options
observer.observe(target, config);

// Later, you can stop observing
observer.disconnect();
</code>```

Body:
An advertiser inserts an iframe on my website in the Dom via an external script. The content of the iframe takes a long time to load the browser. I want, that as soon as the iframe appears in the dom, the iframe is removed again. The iframe has no ID.

My solution so far is setInterval. I check a total of 10 times at intervals of 600ms whether the iframe has been inserted and if so, then remove the iframe and stop the interval. I dont like working with setInterval for performance issues and would rather use addeventlistener or mutationobserver but it doesn't work.

This is what I have at the moment and it works:

var removeRun = 0;
  intervalremove = setInterval(function () {
    removeRun += 1;
    if (removeRun === 10) {
      clearInterval(intervalremove);
    }

    if($("iframe[src*='//ad.adserver.cy']").length == 1) {
    console.log('dom contains adserver iframe');

    $("iframe[src*='//ad.adserver.cy']").remove();

    clearInterval(intervalremove);

    console.log('iframe removed / interval stoped');
    }

  }, 600);

I already searched for mutation and addeventlistener and found many sites. e.g. B.

Is there a JavaScript / jQuery DOM change listener?

So far I haven't managed to build any code that works. Thanks for your help.

Here is one of the hundreds mutationobserver codes I tried

   // Select the node that will be observed for mutations
  var target =
 document.querySelector("iframe[src*='csync.smartadserver.com']");

 // Create an observer instance
 var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
   var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added

    console.log('iframe found');

    });
   }
  });
  });

  // Configuration of the observer:
var config = {
   attributes: true,
   childList: true,
   characterData: true
  };

 // Pass in the target node, as well as the observer options
observer.observe(target, config);

// Later, you can stop observing
observer.disconnect();


问:
React Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
I am getting the following error:  Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Since I am using useEffect I don't see how this can result in an infinite loop. I am new to React so it could just be an obvious mistake, thanks for your time.

This is where the error occurs:
`

```<code>  53 |         else
  54 |         {
  55 |             setCompanies(response.data.companies);
> 56 |             setNoCompanyFound(false);
     | ^  57 |         }
  58 |     }
  59 | }
</code>```

Here is the function:

```<code>export default function FindAvailableEmployee() {
    const [noCompanyFound, setNoCompanyFound] = useState(true);
    const [companies, setCompanies] = useState([]);

    useEffect(() => {
       getCompanies();
      }, [])

    const getCompanies = async () => {
        const response = await getMyCompanies();

        if(response.data.status === 200)
        {
            if(response.data.companies.length === 0)
            {
                setNoCompanyFound(true);
            }
            else
            {
                setCompanies(response.data.companies);
                setNoCompanyFound(false);
            }
        }
    }

  return (
    <div>
        {noCompanyFound? <NoCompaniesFound/> : <FindAvailableEmployeesForm companyData={companies}/>}
    </div>
  )
}
</code>```

`

Body:
I am getting the following error:  Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Since I am using useEffect I don't see how this can result in an infinite loop. I am new to React so it could just be an obvious mistake, thanks for your time.

This is where the error occurs:
`

  53 |         else
  54 |         {
  55 |             setCompanies(response.data.companies);
> 56 |             setNoCompanyFound(false);
     | ^  57 |         }
  58 |     }
  59 | }

Here is the function:

export default function FindAvailableEmployee() {
    const [noCompanyFound, setNoCompanyFound] = useState(true);
    const [companies, setCompanies] = useState([]);

    useEffect(() => {
       getCompanies();
      }, [])

    const getCompanies = async () => {
        const response = await getMyCompanies();

        if(response.data.status === 200)
        {
            if(response.data.companies.length === 0)
            {
                setNoCompanyFound(true);
            }
            else
            {
                setCompanies(response.data.companies);
                setNoCompanyFound(false);
            }
        }
    }

  return (

        {noCompanyFound? <NoCompaniesFound/> : <FindAvailableEmployeesForm companyData={companies}/>}

  )
}

`


问:
How to handle requests for forwarded domain with nginx?
I am quite new to nginx and could not figure out how to configure nginx for the following scenario:

I have a domain domain1.com at some web hoster. There, an nginx server is running on a VPS serving for domain1.com -> everything is running as expected.

I have a domain domain2.com at another web hoster. There, I configured domain2.com to be forwarded to the IP of my VPS at the first web hoster. This does not work. Calling domain2.com via browser leads to a 404 error.

My nginx configuration looks like this:

```<code>server {
    root /var/www/domain2.com/public;

    index index.html;

    server_name domain2.com www.domain2.com;

    location / {
        root /var/www/domain2.com/public/html;
        try_files $uri $uri/ =404;
    }
}
</code>```

What's missing? I guess that I have to tell nginx somehow how to get the original domain (domain2.com) since (as I assume) it currently uses the IP/domain of the second web hoster to identify the correct config. But I do not know how I can do this.

Body:
I am quite new to nginx and could not figure out how to configure nginx for the following scenario:

I have a domain domain1.com at some web hoster. There, an nginx server is running on a VPS serving for domain1.com -> everything is running as expected.

I have a domain domain2.com at another web hoster. There, I configured domain2.com to be forwarded to the IP of my VPS at the first web hoster. This does not work. Calling domain2.com via browser leads to a 404 error.

My nginx configuration looks like this:

server {
    root /var/www/domain2.com/public;

    index index.html;

    server_name domain2.com www.domain2.com;

    location / {
        root /var/www/domain2.com/public/html;
        try_files $uri $uri/ =404;
    }
}

What's missing? I guess that I have to tell nginx somehow how to get the original domain (domain2.com) since (as I assume) it currently uses the IP/domain of the second web hoster to identify the correct config. But I do not know how I can do this.


问:
Is it possibly to use shiny::bindCache in a shiny module that is used several times?
I have a shiny app with three tabs, two of which are almost identical except for the input data, so I put that into a module. In the module, I have one input, and a leaflet plot and a reactable output. I tried using bindCache on the plot and the table - not because the computations are very heavy, but because I learned about it and wanted to apply it. It turns out that when I use bindCache like this (github repo), it has just one cache for both modules, which leads to a wrong output. Adding the parameter cache = "session" does not help either.
So is there a possibility to assign a different cache to each instance of the shiny module?


问:
Using window softinputmode in jetpack compose ui test
I have the following activity in the AndroidManifest file for the AndroidTest project:

```<code>        <activity
            android:name=".SoftInputActivity"
            android:windowSoftInputMode="adjustResize"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
</code>```

I use this activity through:

```<code>    @get:Rule
    val composeTestRule = createAndroidComposeRule<SoftInputActivity>()
</code>```

However, when testing, the windowInputMode=adjustResize does not seem to apply its effects. This causes my tests to fail since the buttons are hidden behind the software keyboard.  Has anyone else experienced this, am I missing something?

Body:
I have the following activity in the AndroidManifest file for the AndroidTest project:

        <activity
            android:name=".SoftInputActivity"
            android:windowSoftInputMode="adjustResize"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>

I use this activity through:

    @get:Rule
    val composeTestRule = createAndroidComposeRule<SoftInputActivity>()

However, when testing, the windowInputMode=adjustResize does not seem to apply its effects. This causes my tests to fail since the buttons are hidden behind the software keyboard.  Has anyone else experienced this, am I missing something?


问:
Swap even elements
In a given array of integers nums swap values of the first and the last array elements, the second and the penultimate, and so on, if both of these exchanged values are even.
Note that input array may be empty.

Code Sample:
...
int[] array = new int[] {100, 2, 3, 45, 33, 8, 4, 54};
...
Output:
[54, 4, 3, 45, 33, 8, 2, 100]

```<code>**if(array[0]%2==0  && array[array.length-1]%2==0){
   for (int i = 0; i < array.length / 2; i++) { // Here!
      int temp = array[i];
      array[i]  = array[array.length - 1 - i];
      array[array.length - 1 - i] = temp;
   }
} else {
   return;
}**
</code>```

Title: Swap even elements

Body:
In a given array of integers nums swap values of the first and the last array elements, the second and the penultimate, and so on, if both of these exchanged values are even.
Note that input array may be empty.

Code Sample:
...
int[] array = new int[] {100, 2, 3, 45, 33, 8, 4, 54};
...
Output:
[54, 4, 3, 45, 33, 8, 2, 100]

**if(array[0]%2==0  && array[array.length-1]%2==0){
   for (int i = 0; i < array.length / 2; i++) { // Here!
      int temp = array[i];
      array[i]  = array[array.length - 1 - i];
      array[array.length - 1 - i] = temp;
   }
} else {
   return;
}**


问:
npm doesn't give any output on windows (command fails with exit code 1)
I've recently installed nodejs v18.12.1 on Windows 11 but the npm command doesn't give any output.
Running it with vscode terminal I can see that the command fails with exit code 1.

I've tried to reinstall nodejs several times, using nvm or in a conda environment but the npm command always fails:
npm -v no output
npm -v exit 1

please help me fix this problem


问:
unable to match string after getting it from the user in rust
I'm trying to get a boolean string from the user and match it with multiple options so as to support multiple boolean inputs, but the control always goes to the default case and is not matching the correct case.

let mut input_str = String::new();
io::stdin()
    .read_line(&mut input_str)
    .expect("read failed");

match input_str.as_str() {
    "true" => println!("true"),
    "t" => println!("t"),
    "false" => println!("false"),
    "f" => println!("f"),
    _ => println!("default")
}
```

But if use a hardcoded &str like let input_str = "true";, it gets matched to the correct case.

Body:
I'm trying to get a boolean string from the user and match it with multiple options so as to support multiple boolean inputs, but the control always goes to the default case and is not matching the correct case.

let mut input_str = String::new();
io::stdin()
    .read_line(&mut input_str)
    .expect("read failed");

match input_str.as_str() {
    "true" => println!("true"),
    "t" => println!("t"),
    "false" => println!("false"),
    "f" => println!("f"),
    _ => println!("default")
}

But if use a hardcoded &str like let input_str = "true";, it gets matched to the correct case.


问:
PHP Imagick PDF to JPG setResolution not equivalent of convert -density
I have a PHP function that generates high-res jpeg copies of PDF files (to be used for OCR later) and on particular pdf documents the result image has the text really blurred, kind of scaled up from a low resolution file (which is not).

I experiment setting the resolution of Imagick according to PHP docs and SO posts and I do not see any improvement.

However I noted that using the convert -density 200 command it gets the job fine really well.

So I am looking for the imagick equivalent of -density or if I can set this anywhere.

Imagick's setResolution doesn't help, nor setImageResolution.

Last resort would be to wrap the convert command in a php function, but for now would like to avoid it.


问:
Plugin for CKEditor 5: Popup with input, textara and checkbox
I already created a CKEditor 4 Plugin (within TYPO3 CMS) that can be used by editors to add data-Attributes to an A-Tag.
I now want to migrate this plugin for version 5 and it seems that nearly everything changed here.
I already played a bit with the documentation on https://ckeditor.com/docs/ckeditor5/latest/framework/guides/plugins/abbreviation-plugin/abbreviation-plugin-level-2.html

Nevertheless, I have now clue, how to add an input field, a textarea, a checkbox and some text (see screenshot below).
Does anyone have some code or a plugin where I can look into how to create my own popup?

My current trial, that works with two simple input fields in a view.js file:

```<code>import {UI} from "@typo3/ckeditor5-bundle.js";

export default class Email4LinkView extends UI.View {
constructor(locale) {
super(locale);

this.titleInputView = this._createInput('Title');
this.descriptionInputView = this._createInput('Description');
this.saveButtonView = this._createButton(
  'Save',
  '<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m2.25 12.321 7.27 6.491c.143.127.321.19.499.19.206 0 .41-.084.559-.249l11.23-12.501c.129-.143.192-.321.192-.5 0-.419-.338-.75-.749-.75-.206 0-.411.084-.559.249l-10.731 11.945-6.711-5.994c-.144-.127-.322-.19-.5-.19-.417 0-.75.336-.75.749 0 .206.084.412.25.56" fill-rule="nonzero"/></svg>',
  'ck-button-save'
);
this.saveButtonView.type = 'submit';
this.cancelButtonView = this._createButton(
  'Cancel',
  '<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m12 10.93 5.719-5.72c.146-.146.339-.219.531-.219.404 0 .75.324.75.749 0 .193-.073.385-.219.532l-5.72 5.719 5.719 5.719c.147.147.22.339.22.531 0 .427-.349.75-.75.75-.192 0-.385-.073-.531-.219l-5.719-5.719-5.719 5.719c-.146.146-.339.219-.531.219-.401 0-.75-.323-.75-.75 0-.192.073-.384.22-.531l5.719-5.719-5.72-5.719c-.146-.147-.219-.339-.219-.532 0-.425.346-.749.75-.749.192 0 .385.073.531.219z"/></svg>',
  'ck-button-cancel'
);

this.cancelButtonView.delegate('execute').to(this, 'cancel');

this.childViews = this.createCollection([
  this.titleInputView,
  this.descriptionInputView,
  this.saveButtonView,
  this.cancelButtonView
]);

this.setTemplate({
  tag: 'form',
  attributes: {
    class: ['ck', 'ck-email4link-form'],
    tabindex: '-1'
  },
  children: this.childViews,
});
}

render() {
super.render();

UI.submitHandler({
  view: this
});
}

focus() {
// this.childViews.first.focus();
}

_createInput(label) {
const labeledInput = new UI.LabeledFieldView(this.locale, UI.createLabeledInputText);
labeledInput.label = label;
return labeledInput;
}

_createButton(label, icon, className) {
const button = new UI.ButtonView();
button.set({
  label,
  icon,
  tooltip: true,
  class: className
});
return button;
}
}
</code>```

Screenshot from old version:

Body:
I already created a CKEditor 4 Plugin (within TYPO3 CMS) that can be used by editors to add data-Attributes to an A-Tag.
I now want to migrate this plugin for version 5 and it seems that nearly everything changed here.
I already played a bit with the documentation on https://ckeditor.com/docs/ckeditor5/latest/framework/guides/plugins/abbreviation-plugin/abbreviation-plugin-level-2.html

Nevertheless, I have now clue, how to add an input field, a textarea, a checkbox and some text (see screenshot below).
Does anyone have some code or a plugin where I can look into how to create my own popup?

My current trial, that works with two simple input fields in a view.js file:

import {UI} from "@typo3/ckeditor5-bundle.js";

export default class Email4LinkView extends UI.View {
constructor(locale) {
super(locale);

this.titleInputView = this._createInput('Title');
this.descriptionInputView = this._createInput('Description');
this.saveButtonView = this._createButton(
  'Save',
  '<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m2.25 12.321 7.27 6.491c.143.127.321.19.499.19.206 0 .41-.084.559-.249l11.23-12.501c.129-.143.192-.321.192-.5 0-.419-.338-.75-.749-.75-.206 0-.411.084-.559.249l-10.731 11.945-6.711-5.994c-.144-.127-.322-.19-.5-.19-.417 0-.75.336-.75.749 0 .206.084.412.25.56" fill-rule="nonzero"/></svg>',
  'ck-button-save'
);
this.saveButtonView.type = 'submit';
this.cancelButtonView = this._createButton(
  'Cancel',
  '<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m12 10.93 5.719-5.72c.146-.146.339-.219.531-.219.404 0 .75.324.75.749 0 .193-.073.385-.219.532l-5.72 5.719 5.719 5.719c.147.147.22.339.22.531 0 .427-.349.75-.75.75-.192 0-.385-.073-.531-.219l-5.719-5.719-5.719 5.719c-.146.146-.339.219-.531.219-.401 0-.75-.323-.75-.75 0-.192.073-.384.22-.531l5.719-5.719-5.72-5.719c-.146-.147-.219-.339-.219-.532 0-.425.346-.749.75-.749.192 0 .385.073.531.219z"/></svg>',
  'ck-button-cancel'
);

this.cancelButtonView.delegate('execute').to(this, 'cancel');

this.childViews = this.createCollection([
  this.titleInputView,
  this.descriptionInputView,
  this.saveButtonView,
  this.cancelButtonView
]);

this.setTemplate({
  tag: 'form',
  attributes: {
    class: ['ck', 'ck-email4link-form'],
    tabindex: '-1'
  },
  children: this.childViews,
});
}

render() {
super.render();

UI.submitHandler({
  view: this
});
}

focus() {
// this.childViews.first.focus();
}

_createInput(label) {
const labeledInput = new UI.LabeledFieldView(this.locale, UI.createLabeledInputText);
labeledInput.label = label;
return labeledInput;
}

_createButton(label, icon, className) {
const button = new UI.ButtonView();
button.set({
  label,
  icon,
  tooltip: true,
  class: className
});
return button;
}
}

Screenshot from old version:


问:
Why moment() does not increment seconds?
I am new to Node JS and sorry if my question is really simple

Tried the following code on Windows 10 and Ubuntu and I don't get the 'seconds' incremented in the output

Code

```<code>var moment = require('moment')

for(let step = 0; step < 5; step++ ) {
    console.log(moment().format('DDMMYYYY-hhmmss'));
}
</code>```

Output

```<code>C:\Users\sathish>node form.js
23122022-045601
23122022-045601
23122022-045601
23122022-045601
23122022-045601
</code>```

Expected output

```<code>23122022-045601
23122022-045602
23122022-045603
23122022-045604
23122022-045605
</code>```

Kindly let me know what am I missing

Body:
I am new to Node JS and sorry if my question is really simple

Tried the following code on Windows 10 and Ubuntu and I don't get the 'seconds' incremented in the output

Code

var moment = require('moment')

for(let step = 0; step < 5; step++ ) {
    console.log(moment().format('DDMMYYYY-hhmmss'));
}

Output

C:\Users\sathish>node form.js
23122022-045601
23122022-045601
23122022-045601
23122022-045601
23122022-045601

Expected output

23122022-045601
23122022-045602
23122022-045603
23122022-045604
23122022-045605

Kindly let me know what am I missing


问:
Where should I load up-to-date data required for ui and server in a golem shiny app?
I have a golem app that loads data from an open government data portal. I need to access the data both in the ui (to make the choices fit the data) and in the server (to make a table and a plot), and I need the data to be up-to-date. Because I want the latest data, I do not load it as raw data and package it with the app. If this were not golem, I would probably load it at the top of the app.R file, thereby making it available both for the ui and the server. I ended up running the data-loading function in the file of the data-loading function, which seems like a bit of a hack. I found other golem apps (e.g. this one) that load the data in the server, where it would be up-to-date but not available to the ui. Where would you recommend to load data - within the golem framework - in a way that it is more or less up to date and available for both the ui and the server?


问:
An error occurred while retrieving token. Failed to register a ServiceWorker for scope
Hi am implementing web push notification using firebase and angular 6. its local working fine. but when we deploy same application to server its showing this error

```<code>An error occurred while retrieving token.  FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://domainName/firebase-cloud-messaging-push-scope') with script ('https://domainName/firebase-messaging-sw.js'): The script resource is behind a redirect, which is disallowed. (messaging/failed-service-worker-registration).
    at e.<anonymous> (10.5418b275bf55709baaf2.js:1:34826)
</code>```

our firebase-messaging-sw.js file access by
https://domainName/folder/firebase-messaging-sw.js same for manifest.json

register Service worker path this one
https://domainName/folder/firebase-messaging-sw.js   its showing in application console

I am registring sw.js file in main.ts

```<code>if('serviceWorker' in navigator) {
          navigator.serviceWorker.register('./firebase-messaging-sw.js')
        .then(function(registration) {
         console.log("Service Worker Registered");
          });
          }
</code>```

firebase-sw.js and mainfest.json are same root folder.
How to fixed this error

Body:
Hi am implementing web push notification using firebase and angular 6. its local working fine. but when we deploy same application to server its showing this error

An error occurred while retrieving token.  FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://domainName/firebase-cloud-messaging-push-scope') with script ('https://domainName/firebase-messaging-sw.js'): The script resource is behind a redirect, which is disallowed. (messaging/failed-service-worker-registration).
    at e.<anonymous> (10.5418b275bf55709baaf2.js:1:34826)

our firebase-messaging-sw.js file access by
https://domainName/folder/firebase-messaging-sw.js same for manifest.json

register Service worker path this one
https://domainName/folder/firebase-messaging-sw.js   its showing in application console

I am registring sw.js file in main.ts

if('serviceWorker' in navigator) {
          navigator.serviceWorker.register('./firebase-messaging-sw.js')
        .then(function(registration) {
         console.log("Service Worker Registered");
          });
          }

firebase-sw.js and mainfest.json are same root folder.
How to fixed this error


问:
HPA Autoscaler cannot read all the metrics (Google Kubernetes Engine)
I have configured hpa such that it gets value from prometheus but my hpa says "Unable to read all metrics".
I have also tried adding cpu requests in resource block in yml file of the deployment.this deployment yaml
[the error I'm getting]
(https://i.stack.imgur.com/e1cLk.png)

This is my scaledObject.yml file

```<code>
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: prometheus-scaledobject
  namespace: default
spec:
  maxReplicaCount: 7
  cooldownPeriod: 30
  pollingInterval: 10
  scaleTargetRef:
    name: application
  triggers:
  - type: prometheus
    metadata:
      serverAddress:
      metricName: cpu_usage
      threshold: '3'
      query: rate(container_cpu_usage_seconds_total{ image=""}[1m])*100

</code>```

Please help me in this

Body:
I have configured hpa such that it gets value from prometheus but my hpa says "Unable to read all metrics".
I have also tried adding cpu requests in resource block in yml file of the deployment.this deployment yaml
[the error I'm getting]
(https://i.stack.imgur.com/e1cLk.png)

This is my scaledObject.yml file

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: prometheus-scaledobject
  namespace: default
spec:
  maxReplicaCount: 7
  cooldownPeriod: 30
  pollingInterval: 10
  scaleTargetRef:
    name: application
  triggers:
  - type: prometheus
    metadata:
      serverAddress:
      metricName: cpu_usage
      threshold: '3'
      query: rate(container_cpu_usage_seconds_total{ image=""}[1m])*100

Please help me in this


问:
Discord.py using asyncio.ensure_future() to run a async function in another script without waiting for completion?
I'm new to stack overflow, so sorry if I mess something up here. I'm trying to make a discord bot in Python. I'm currently experiencing an issue with commands. When I run a certain command it won't take any other commands until the command is fully finished. I tried to use asyncio.ensure_future such that bot will move on without waiting for my function in the second script from completing.</p>
```<code>#Yes, I am importing stuff.
    @commands.command("echo")
    async def echo(self, ctx, *, input):
        future = asyncio.ensure_future(secondscript.foo(input, ctx.channel))
        #This should execute "foo" in the secondscript without waiting for it to finish.
</code>```
```<code>#The second script, "secondscript.py"
import time
async def foo(input, channel):
    time.sleep(5)
    #I know I can use asyncio.sleep(), but let's say it's important I use time.sleep() instead.
    await channel.send(input)
    #Sends input to channel after 5 seconds.
</code>```

Body:
I'm new to stack overflow, so sorry if I mess something up here. I'm trying to make a discord bot in Python. I'm currently experiencing an issue with commands. When I run a certain command it won't take any other commands until the command is fully finished. I tried to use asyncio.ensure_future such that bot will move on without waiting for my function in the second script from completing.

#Yes, I am importing stuff.
    @commands.command("echo")
    async def echo(self, ctx, *, input):
        future = asyncio.ensure_future(secondscript.foo(input, ctx.channel))
        #This should execute "foo" in the secondscript without waiting for it to finish.

#The second script, "secondscript.py"
import time
async def foo(input, channel):
    time.sleep(5)
    #I know I can use asyncio.sleep(), but let's say it's important I use time.sleep() instead.
    await channel.send(input)
    #Sends input to channel after 5 seconds.


问:
How to turn a string into an html tag in a flask app template
I have this template in a Flask app:

```<code>{% extends 'base.html' %}

{% block content %}
    <h1>{% block title %} Welcome to the Testbank {% endblock %}</h1>

        <table>
            <tr>
                <th>ID
                </th>
                <th>Content
                </th>
                <th>Level</th>
            </tr>
            {% for question in questions %}
            <tr>
                <td>
                    {{question['qid']}}
                </td>
                <td>
                    {{question['content']}}
                </td>
                <td>{{question['level']}}</td>
            </tr>
            {% endfor %}

        </table>

{% endblock %}
</code>```

then it prints out '
 content
'	 instead of
 content

Is there a way to turn the string tag into an html tag in python. In ruby, there is this syntax  {{question['qid']}} | to_html

Body:
I have this template in a Flask app:

{% extends 'base.html' %}

{% block content %}

{% block title %} Welcome to the Testbank {% endblock %}

                ID

                Content

                Level

            {% for question in questions %}

                    {{question['qid']}}

                    {{question['content']}}

                {{question['level']}}

            {% endfor %}

{% endblock %}

then it prints out '
 content
'	 instead of
 content

Is there a way to turn the string tag into an html tag in python. In ruby, there is this syntax  {{question['qid']}} | to_html


问:
Redirect to index.php to prevent duplicate content
I would like to redirect to index.php in url for seo reasons to prevent duplicate content without breaking the site.

https://www.example.com/index.php/fr/google [WORKS]

https://www.example.com/index.php/id/google [WORKS]

https://www.example.com/index.php - [NOT WORKING]

should redirect to

https://www.example.com/fr/google

https://www.example.com/id/google

https://www.example.com/

My nginx config looks as follows

```<code>location / {
        # Redirect index.php to root (prevent duplicate content)
        rewrite ^/(.*?)index\.php[^/] /$1? permanent;
        rewrite ^/(.*?)index\.php(?:/(.*))?$ /$1$2? permanent;

        try_files $uri $uri/ /index.php?$query_string;
    }
</code>```

https://www.example.com/index.php is not getting redirect to https://www.example.com/

Body:
I would like to redirect to index.php in url for seo reasons to prevent duplicate content without breaking the site.

https://www.example.com/index.php/fr/google [WORKS]

https://www.example.com/index.php/id/google [WORKS]

https://www.example.com/index.php - [NOT WORKING]

should redirect to

https://www.example.com/fr/google

https://www.example.com/id/google

https://www.example.com/

My nginx config looks as follows

location / {
        # Redirect index.php to root (prevent duplicate content)
        rewrite ^/(.*?)index\.php[^/] /$1? permanent;
        rewrite ^/(.*?)index\.php(?:/(.*))?$ /$1$2? permanent;

        try_files $uri $uri/ /index.php?$query_string;
    }

https://www.example.com/index.php is not getting redirect to https://www.example.com/


问:
I have added the following code to add extra tab in woocommerce single product page. And the extra tab is used for to create questions and and answers
```<code>add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 );

function custom_questions_answers_tab( $tabs ) {
  $tabs['questions_answers'] = array(
    'title'    => __( 'Questions & Answers', 'text-domain' ),
    'callback' => 'custom_questions_answers_tab_content',
    'priority' => 50,
  );
  return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'custom_questions_answers_tab' );

function custom_questions_answers_tab_content() {
  global $product;

  // Display form to submit a question
  echo '<form action="" method="post" class="question-form">';
  echo '<label for="question">Ask a question:</label>';
  echo '<textarea name="question" id="question"></textarea>';
  echo '<input type="hidden" name="product_id" value="' . $product->get_id() . '">';
  echo '<input type="submit" value="Submit">';
  echo '</form>';

  // Display list of previous questions and answers
  $questions = get_questions_and_answers_for_product( $product->get_id() );
  if ( ! empty( $questions ) ) {
    echo '<ul class="questions-answers">';
    foreach ( $questions as $question ) {
      echo '<li>';
      echo '<p class="question">' . $question['question'] . '</p>';
      if ( ! empty( $question['answer'] ) ) {
        echo '<p class="answer">' . $question['answer'] . '</p>';
      }
      echo '</li>';
    }
    echo '</ul>';
  }
}

function get_questions_answers_for_product( $product_id ) {
    echo 'Hello World';
    global $wpdb;

    $questions_answers = $wpdb->get_results( $wpdb->prepare( "SELECT question, answer FROM {$wpdb->prefix}questions_answers WHERE product_id = %d", $product_id ) );

    return $questions_answers;
}

</code>```

I'm using Astra pro theme.

Can you guide me. What should i change here to get it done exactly what i expect. Initially i had uncaught error and function undefined error. Finally it has been solved. But the questions which i typed is not showing up for the admin to answer.

Body:
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 );

function custom_questions_answers_tab( $tabs ) {
  $tabs['questions_answers'] = array(
    'title'    => __( 'Questions & Answers', 'text-domain' ),
    'callback' => 'custom_questions_answers_tab_content',
    'priority' => 50,
  );
  return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'custom_questions_answers_tab' );

function custom_questions_answers_tab_content() {
  global $product;

  // Display form to submit a question
  echo '<form action="" method="post" class="question-form">';
  echo 'Ask a question:';
  echo '<textarea name="question" id="question"></textarea>';
  echo '<input type="hidden" name="product_id" value="' . $product->get_id() . '">';
  echo '<input type="submit" value="Submit">';
  echo '</form>';

  // Display list of previous questions and answers
  $questions = get_questions_and_answers_for_product( $product->get_id() );
  if ( ! empty( $questions ) ) {
    echo '
';
    foreach ( $questions as $question ) {
      echo '
';
      echo '
' . $question['question'] . '
';
      if ( ! empty( $question['answer'] ) ) {
        echo '
' . $question['answer'] . '
';
      }
      echo '
';
    }
    echo '
';
  }
}

function get_questions_answers_for_product( $product_id ) {
    echo 'Hello World';
    global $wpdb;

    $questions_answers = $wpdb->get_results( $wpdb->prepare( "SELECT question, answer FROM {$wpdb->prefix}questions_answers WHERE product_id = %d", $product_id ) );

    return $questions_answers;
}

I'm using Astra pro theme.

Can you guide me. What should i change here to get it done exactly what i expect. Initially i had uncaught error and function undefined error. Finally it has been solved. But the questions which i typed is not showing up for the admin to answer.


问:
How to get Bitmap from surface view in order to reach pixels
Sorry for bad English. I am currently working on android project. I have a surface view to display camera preview. In this previev i want to get pixels to convert them to hexes then show the name of color where you touched. My activity covered with surface view Using firebase to
for names and hexes. I am getting error in this piece of code:

```<code>@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // get coordinates where you touched
        int x = (int) event.getX();
        int y = (int) event.getY();

        // get color where you touched
        final int pixel = surfaceView.getBitmap().getPixel(x, y);

        // convert color to RGB
        int redValue = Color.red(pixel);
        int greenValue = Color.green(pixel);
        int blueValue = Color.blue(pixel);

        // Firebase
        FirebaseConnection firebaseConnection = new FirebaseConnection();
        final ArrayList<String> nameList = firebaseConnection.getNameList();
        final ArrayList<String> hexList = firebaseConnection.getHexList();

        // nearest color name if there is no name in database for color
        String nearestColorName = findNearestColor(redValue, greenValue, blueValue, nameList, hexList);
        Toast.makeText(CanliTanima.this, nearestColorName, Toast.LENGTH_SHORT).show();
    }
    return true;
}
</code>```

final int pixel = surfaceView.getBitmap().getPixel(x, y); I cannot use getBitmap()

What can I use instead of getBitmap() ?

Body:
Sorry for bad English. I am currently working on android project. I have a surface view to display camera preview. In this previev i want to get pixels to convert them to hexes then show the name of color where you touched. My activity covered with surface view Using firebase to
for names and hexes. I am getting error in this piece of code:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // get coordinates where you touched
        int x = (int) event.getX();
        int y = (int) event.getY();

        // get color where you touched
        final int pixel = surfaceView.getBitmap().getPixel(x, y);

        // convert color to RGB
        int redValue = Color.red(pixel);
        int greenValue = Color.green(pixel);
        int blueValue = Color.blue(pixel);

        // Firebase
        FirebaseConnection firebaseConnection = new FirebaseConnection();
        final ArrayList<String> nameList = firebaseConnection.getNameList();
        final ArrayList<String> hexList = firebaseConnection.getHexList();

        // nearest color name if there is no name in database for color
        String nearestColorName = findNearestColor(redValue, greenValue, blueValue, nameList, hexList);
        Toast.makeText(CanliTanima.this, nearestColorName, Toast.LENGTH_SHORT).show();
    }
    return true;
}

final int pixel = surfaceView.getBitmap().getPixel(x, y); I cannot use getBitmap()

What can I use instead of getBitmap() ?


问:
My application don't start when I change intent-filter of activity
I am learning to build a mobile app and after looking at the docs where they change the main display page of the app I have a problem that after I change it my app can't run.

In my AndroidManifest.xml before:

```<code>    <activity
        android:name=".ProfileActivity"
        android:exported="false">

        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

</code>```

and after i copy and paste intent-filter from .MainActivity to .ProfileActivity then my app doesn't run.

```<code>    <activity
        android:name=".ProfileActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

    <activity
        android:name=".MainActivity"
        android:exported="false">

        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>
</code>```

Is there any way to solve this for me? Thank you <3

Body:
I am learning to build a mobile app and after looking at the docs where they change the main display page of the app I have a problem that after I change it my app can't run.

In my AndroidManifest.xml before:

    <activity
        android:name=".ProfileActivity"
        android:exported="false">

        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

and after i copy and paste intent-filter from .MainActivity to .ProfileActivity then my app doesn't run.

    <activity
        android:name=".ProfileActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

    <activity
        android:name=".MainActivity"
        android:exported="false">

        <meta-data
            android:name="android.app.lib_name"
            android:value="" />
    </activity>

Is there any way to solve this for me? Thank you <3


问:
python / pylint: Type "property" cannot be assigned to type problem
I got a problem with trying to annotate some of my code and i can't really wrap my head around it. I simply dont know if its a pylint Problem or I am just to stupid to figured it out.

so I got a class that inherits from type and has a property like so:

class MyType(type):

    @property
    def keys(cls) -> list[str]:
        """
        Property to return a list of Keys
        """
        result: list[str] = [key for key, val in vars(cls).items() if not callable(val)
                and not key.startswith('__')
                or not type(val).__name__ != 'method']
        return result

```
<p>so  I thought i do a Protocol class that Supports this property and i can use this protocol tho annotated stuff in my code.</p>
<pre class="lang-py prettyprint-override"><code>
class IsMyType(Protocol):
    "Protocol to implement an interface for key property"
    @property
    def keys(cls) -> list[str]: ...

</code>```

so now when i try to use it

foo: IsMyType = MyType(bar)

```
<p>I get pylint complaining that</p>
```Expression of type "Type[__class_MyType]" cannot be assigned to declared type "IsMyType"
  "keys" is an incompatible type
    "property" is incompatible with "list[str]"PylancereportGeneralTypeIssues
```
<p>I am close to just do an return of Any in the protocol which is just messed up or simply try to use some</p>
<pre class="lang-py prettyprint-override"><code>
#pylint: disabel=

</code>```

on this. Last resort is simply skipping the whole typing thing for this alltogether.

So if anyone out there has a solution to a situation like that it would be much appreciated.

cheers

Markus

Body:
I got a problem with trying to annotate some of my code and i can't really wrap my head around it. I simply dont know if its a pylint Problem or I am just to stupid to figured it out.

so I got a class that inherits from type and has a property like so:

class MyType(type):

    @property
    def keys(cls) -> list[str]:
        """
        Property to return a list of Keys
        """
        result: list[str] = [key for key, val in vars(cls).items() if not callable(val)
                and not key.startswith('__')
                or not type(val).__name__ != 'method']
        return result

so  I thought i do a Protocol class that Supports this property and i can use this protocol tho annotated stuff in my code.

class IsMyType(Protocol):
    "Protocol to implement an interface for key property"
    @property
    def keys(cls) -> list[str]: ...

so now when i try to use it

foo: IsMyType = MyType(bar)

I get pylint complaining that

Expression of type "Type[__class_MyType]" cannot be assigned to declared type "IsMyType"
  "keys" is an incompatible type
    "property" is incompatible with "list[str]"PylancereportGeneralTypeIssues

I am close to just do an return of Any in the protocol which is just messed up or simply try to use some

#pylint: disabel=

on this. Last resort is simply skipping the whole typing thing for this alltogether.

So if anyone out there has a solution to a situation like that it would be much appreciated.

cheers

Markus


问:
Expo Updates Custom Server
I have been trying to implement the custom server for expo updates as explained in this repo for my App
https://github.com/expo/custom-expo-updates-server

The expo-updates-server code I haven't touched, just changed the path in sripts/publish.sh and scripts/exportClientExpoConfig.js to point to my App rather than expo-updates-client

The issue which I am facing is that when my app is loading I am not sure whether or not its calling the server running at http://localhost:3000/api/manifest because its not logging any request in logs

Is there a way to debug this thing to be completely sure about whether or not this is the issue.

In my client app I have done the following things before making the release version of my App using eas build

I have installed expo-updates in my client app

Added runtimeVersion=1 in my app.json

Also I have copied the updates block in my client app from expo-update-client app

I am attaching screenshots of my app.json file

Please note that my dist folder is successfully created and update is being copied in expo-updates-server/updates/1 folder

Has anyone implemented this before? Any Kind of help is appreciated

Thanks

Title: Expo Updates Custom Server


问:
Hooking functions which take multidimensional arrays
I'm building an in-process JNI library fuzzer using Frida and I think I got everything to work except for multidimensional arrays.
When testing on Linux_64, I'm not able to even create a valid hook for a function which takes multidimensional arrays. No matter what I try I'm getting something like:

Exception in thread "main" java.lang.NoClassDefFoundError: [L[I;
at CallCrashingFun.crashingMethod_dbarr(Native Method)
at CallCrashingFun.main(CallCrashingFun.java:100)
Caused by: java.lang.ClassNotFoundException: [I
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)

My hooking script looks similar to this:

```<code>
var t_class = Java.use("CallCrashingFun")
var method_name = "crashingMethod_dbarr"
t_class[method_name].implementation = function(dbint) {
    console.log("Hook works!")
}

/* Also tried with params
t_class[method_name].overload.apply(t_class[method_name], param_types).implementation = function(dbint) {
    console.log("Hook works!")
}*/

/* This however doesn't crash
var imp_cp = t_class[method_name].implementation
t_class[method_name].implementation = imp_cp
*/
</code>```

The Java code I use for tests:

```<code>System.loadLibrary("native");
int arr[] = {2,2,2};
int[][] dbarr = {arr};
new CallCrashingFun().crashingMethod_dbarr(dbarr);
private native void crashingMethod_dbarr(int[][] dbarr);
</code>```

The JNI C++ code:

```<code>JNIEXPORT void JNICALL Java_CallCrashingFun_crashingMethod_1dbarr
  (JNIEnv *env, jobject thisObject, jobjectArray dbtab) {
      int i, j;
      std::cout << "DbArray: " << "[" << std::endl;
      jsize len = (env)->GetArrayLength(dbtab);
      for (i=0; i<len; i++) {
         std::cout << "[";
          jintArray insArr = (jintArray) (env)->GetObjectArrayElement(dbtab, i);
          jsize inlen = (env)->GetArrayLength(insArr);
          jint *body = (env)->GetIntArrayElements(insArr, 0);
          for (j=0; j<inlen; j++) {
            std::cout << body[i] << ",";
          }
          std::cout << "]" << std::endl;
      }
      std::cout << "]" <<  std::endl;
  }
</code>```

Java version that I'm using:

$ /usr/bin/java --version
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
openjdk 11.0.17 2022-10-18
OpenJDK Runtime Environment Temurin-11.0.17+8 (build 11.0.17+8)
OpenJDK 64-Bit Server VM Temurin-11.0.17+8 (build 11.0.17+8, mixed mode)

Frida server version:

frida-server-16.0.8-linux-x86_64

Without hook the function works correctly:

DbArray: [
[2,2,2,]
]

How can I get this hook to work?

Body:
I'm building an in-process JNI library fuzzer using Frida and I think I got everything to work except for multidimensional arrays.
When testing on Linux_64, I'm not able to even create a valid hook for a function which takes multidimensional arrays. No matter what I try I'm getting something like:

Exception in thread "main" java.lang.NoClassDefFoundError: [L[I;
at CallCrashingFun.crashingMethod_dbarr(Native Method)
at CallCrashingFun.main(CallCrashingFun.java:100)
Caused by: java.lang.ClassNotFoundException: [I
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)

My hooking script looks similar to this:

var t_class = Java.use("CallCrashingFun")
var method_name = "crashingMethod_dbarr"
t_class[method_name].implementation = function(dbint) {
    console.log("Hook works!")
}

/* Also tried with params
t_class[method_name].overload.apply(t_class[method_name], param_types).implementation = function(dbint) {
    console.log("Hook works!")
}*/

/* This however doesn't crash
var imp_cp = t_class[method_name].implementation
t_class[method_name].implementation = imp_cp
*/

The Java code I use for tests:

System.loadLibrary("native");
int arr[] = {2,2,2};
int[][] dbarr = {arr};
new CallCrashingFun().crashingMethod_dbarr(dbarr);
private native void crashingMethod_dbarr(int[][] dbarr);

The JNI C++ code:

JNIEXPORT void JNICALL Java_CallCrashingFun_crashingMethod_1dbarr
  (JNIEnv *env, jobject thisObject, jobjectArray dbtab) {
      int i, j;
      std::cout << "DbArray: " << "[" << std::endl;
      jsize len = (env)->GetArrayLength(dbtab);
      for (i=0; i<len; i++) {
         std::cout << "[";
          jintArray insArr = (jintArray) (env)->GetObjectArrayElement(dbtab, i);
          jsize inlen = (env)->GetArrayLength(insArr);
          jint *body = (env)->GetIntArrayElements(insArr, 0);
          for (j=0; j<inlen; j++) {
            std::cout << body[i] << ",";
          }
          std::cout << "]" << std::endl;
      }
      std::cout << "]" <<  std::endl;
  }

Java version that I'm using:

$ /usr/bin/java --version
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
openjdk 11.0.17 2022-10-18
OpenJDK Runtime Environment Temurin-11.0.17+8 (build 11.0.17+8)
OpenJDK 64-Bit Server VM Temurin-11.0.17+8 (build 11.0.17+8, mixed mode)

Frida server version:

frida-server-16.0.8-linux-x86_64

Without hook the function works correctly:

DbArray: [
[2,2,2,]
]

How can I get this hook to work?


问:
How to make a expand tab row and it can overlap navigation bar in Jetpack Compose
I'm new in Jetpack Compose and kotlin.
I want to make a custom scrollable tab row with an arrow icon and when I click this icon ,
the tap row will expand to show all taps and have a black block below this row ,this block can overlap navigation bar and if I click this block the expanded row will be collapse

(black block I meant like this photo
black block example

I use Scaffold Composable and put this tap row in topbar but when I expand the row ,
Scaffold content and bottom bar will be push down,
if I put this row into Scaffold content when I expanded it the black block region can't overlap bottom bar .

I would appreciate it if someone can give me some suggestions,thx

(Sorry, I am foreigner,English and words may have some wrong


问:
NestJs, RabbitMq, CQRS & BFF: Listening for event inside the bff
I'm about to implement a Microservice Architecture with CQRS Design Pattern. The Microservices are communicating with RMQ.
Additionally, I'm adding a BFF for my Application UI.
In this scenario, the BFF needs to listen to certain domain events.

For instance: After the user sends an request to the BFF, the BFF calls a method of a Microservice which invokes an asynchronous event.
The events result will go back to the BFF and then to the user.

I'm thinking of different ways I might be able to implement this and I came up with this concept:

// BFF Application: sign-up.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { Client, ClientProxy, Transport } from '@nestjs/microservices';

@Controller('signup')
export class SignupController {
  @Client({ transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'signup_request' } })
  client: ClientProxy;

  @Post()
  async signup(@Body() body: any) {
    // Generate a unique identifier for the request
    const requestId = uuid();

    // Send the request with the unique identifier
    const response = await this.client.send<any>({ cmd: 'signup', requestId }, body).toPromise();

    // Wait for the SignUpEvent to be emitted before sending the response
    return new Promise((resolve, reject) => {
      this.client.subscribe<any>('signup_response', (response: any) => {
        // Check the unique identifier to ensure the event corresponds to the original request
        if (response.requestId === requestId) {
          resolve(response);
        }
      });
    });
  }
}
```
<p>After sending the request with the unique identifier, the microservice will execute a sign up command:</p>
<pre class="lang-js prettyprint-override"><code>// Microservice Application: sign-up.handler.ts

import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { SignUpCommand } from './commands/sign-up.command';
import { SignUpEvent } from './events/sign-up.event';
import { EventBus } from '@nestjs/cqrs';

@CommandHandler(SignUpCommand)
export class SignUpCommandHandler implements ICommandHandler<SignUpCommand> {
  constructor(private readonly eventBus: EventBus) {}

  async execute(command: SignUpCommand) {
    // Validating the user/account aggregate
    // ...

    // Emit the SignUpEvent with the unique identifier
    this.eventBus.publish(new SignUpEvent(user, command.requestId));
  }
}
</code>```

Now the Event Handler gets called:

// Microservice Application: signed-up.handler.ts

import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { SignUpEvent } from './events/sign-up.event';
import { ClientProxy, Transport } from '@nestjs/microservices';

@EventsHandler(SignUpEvent)
export class SignUpEventHandler implements IEventHandler<SignUpEvent> {
  @Client({ transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'signup_response' } })
  client: ClientProxy;

  async handle(event: SignUpEvent) {
    // Persist the user
    const user = await this.persistUser(event.user);

    // Generate access and refresh tokens
    const tokens = this.generateTokens(user);

    // Emit the SignUpResponse event with a unique identifier
    await this.client.emit('signup_response', { user, tokens, requestId: event.requestId });
  }
}
```

Is this, a valid way to implement this type of behaviour?
Thank you in advance.

Body:
I'm about to implement a Microservice Architecture with CQRS Design Pattern. The Microservices are communicating with RMQ.
Additionally, I'm adding a BFF for my Application UI.
In this scenario, the BFF needs to listen to certain domain events.

For instance: After the user sends an request to the BFF, the BFF calls a method of a Microservice which invokes an asynchronous event.
The events result will go back to the BFF and then to the user.

I'm thinking of different ways I might be able to implement this and I came up with this concept:

// BFF Application: sign-up.controller.ts

import { Controller, Post, Body } from '@nestjs/common';
import { Client, ClientProxy, Transport } from '@nestjs/microservices';

@Controller('signup')
export class SignupController {
  @Client({ transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'signup_request' } })
  client: ClientProxy;

  @Post()
  async signup(@Body() body: any) {
    // Generate a unique identifier for the request
    const requestId = uuid();

    // Send the request with the unique identifier
    const response = await this.client.send<any>({ cmd: 'signup', requestId }, body).toPromise();

    // Wait for the SignUpEvent to be emitted before sending the response
    return new Promise((resolve, reject) => {
      this.client.subscribe<any>('signup_response', (response: any) => {
        // Check the unique identifier to ensure the event corresponds to the original request
        if (response.requestId === requestId) {
          resolve(response);
        }
      });
    });
  }
}

After sending the request with the unique identifier, the microservice will execute a sign up command:

// Microservice Application: sign-up.handler.ts

import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { SignUpCommand } from './commands/sign-up.command';
import { SignUpEvent } from './events/sign-up.event';
import { EventBus } from '@nestjs/cqrs';

@CommandHandler(SignUpCommand)
export class SignUpCommandHandler implements ICommandHandler<SignUpCommand> {
  constructor(private readonly eventBus: EventBus) {}

  async execute(command: SignUpCommand) {
    // Validating the user/account aggregate
    // ...

    // Emit the SignUpEvent with the unique identifier
    this.eventBus.publish(new SignUpEvent(user, command.requestId));
  }
}

Now the Event Handler gets called:

// Microservice Application: signed-up.handler.ts

import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { SignUpEvent } from './events/sign-up.event';
import { ClientProxy, Transport } from '@nestjs/microservices';

@EventsHandler(SignUpEvent)
export class SignUpEventHandler implements IEventHandler<SignUpEvent> {
  @Client({ transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'signup_response' } })
  client: ClientProxy;

  async handle(event: SignUpEvent) {
    // Persist the user
    const user = await this.persistUser(event.user);

    // Generate access and refresh tokens
    const tokens = this.generateTokens(user);

    // Emit the SignUpResponse event with a unique identifier
    await this.client.emit('signup_response', { user, tokens, requestId: event.requestId });
  }
}

Is this, a valid way to implement this type of behaviour?
Thank you in advance.


问:
makeMove function is not working as i wish
void makeMove(int player, int move) {
int i, stones, nextPit;

```<code>// Get the number of stones in the selected pit
stones = board[player * 6 + move];
board[player * 6 + move] = 0;  // Clear the pit

// Distribute the stones
nextPit = player * 6 + move + 1;  // Start at the next pit
for (i = 0; i < stones; i++) {
    // Skip the opponent's mancala
    if (nextPit == (player ^ 1) * 6 + 6) {
        nextPit++;
    }

    // Place a stone in the pit
    board[nextPit]++;
    nextPit++;  // Move to the next pit

    // Wrap around to to the beginning of the board
    if (nextPit == BOARD_SIZE) {
        nextPit = 0;
    }
}
</code>```

so this function takes all the stones from the chosen pit and puts the stones one by one on to the next pits
example : 4 4 4 4 4 if you choose the first pit it goes like 0 5 5 5 5 but i want it to be 1 5 5 5 4
i want this function to take all the stones from the chosen pit and put one back to the chosen pit and then start to put next pits

i am a 2 month computer engineering student im new to this i didnt try much if you can explain this code to me it would mean the world

Body:
void makeMove(int player, int move) {
int i, stones, nextPit;

// Get the number of stones in the selected pit
stones = board[player * 6 + move];
board[player * 6 + move] = 0;  // Clear the pit

// Distribute the stones
nextPit = player * 6 + move + 1;  // Start at the next pit
for (i = 0; i < stones; i++) {
    // Skip the opponent's mancala
    if (nextPit == (player ^ 1) * 6 + 6) {
        nextPit++;
    }

    // Place a stone in the pit
    board[nextPit]++;
    nextPit++;  // Move to the next pit

    // Wrap around to to the beginning of the board
    if (nextPit == BOARD_SIZE) {
        nextPit = 0;
    }
}

so this function takes all the stones from the chosen pit and puts the stones one by one on to the next pits
example : 4 4 4 4 4 if you choose the first pit it goes like 0 5 5 5 5 but i want it to be 1 5 5 5 4
i want this function to take all the stones from the chosen pit and put one back to the chosen pit and then start to put next pits

i am a 2 month computer engineering student im new to this i didnt try much if you can explain this code to me it would mean the world