问:
I have a question on Nio's selector and threads part
Please help .

When you first start the server, create a thread pool in advance (5 threads) and create 5 selectors to read, pass one selector to each Runnable, and immediately send the submit function to the thread pool.

Then, create a selector that accepts the user and run it on the main thread.

The problem here is that the Selector in the main thread detects the user's request and registers the returned SocketChannel in one of the 5 Read Selectors.

And when the connection is successful, the user sends text data every second, but there is no response from the Read Selector.

I don't know why this problem occurs.. ㅜㅜ

Main.java

```<code>public class Main {

    public static void main(String[] args) {

        Server server = new Quarter();

    }

}
</code>```

Server.java

```<code>import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AlreadyBoundException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class Server {

    protected volatile boolean isStart = true;

    // 192.168.0.11 company
    // 192.168.75.35 house
    // 192.168.75.97 my notebook
    private static final String ADDRESS = "192.168.75.35";
    private static final int    PORT    = 1111;
    private static final int    BACKLOG = 1024;

    protected Selector acceptSelector = null;

    /** 하나의 스레드에서만 접근 할것이기 때문에 동기화 처리는 필요 없음. */
    protected List<Selector> readSelectors = new ArrayList<Selector>();

    protected ServerSocketChannel serverSocketChannel = null;
    protected InetSocketAddress inetSocketAddress = null;

    private final int nThreads = 5;
    protected ExecutorService threadpool = null;

    /** 현재 연결된 클라이언트 수 */
    protected static int connectionCount = 0;
    // volatile 캐시 메모리 문제는 아닌가?
    // 뭐가 문제지?

    protected void init() {
        try {

            this.threadpool = Executors.newFixedThreadPool(this.nThreads);

            for (int i = 1; i <= this.nThreads; i++) {
                Selector sel = Selector.open();
                this.readSelectors.add(sel);
                threadpool.submit(new SubSelector(sel));
            }

            this.acceptSelector = Selector.open();
            this.inetSocketAddress = new InetSocketAddress(ADDRESS, PORT);

            this.serverSocketChannel = ServerSocketChannel.open();

            // non - blocking 으로 설정.
            this.serverSocketChannel.configureBlocking(false);
            System.out.println("serverSocketChannel is non-blocking.");

            this.serverSocketChannel.bind(this.inetSocketAddress, BACKLOG);
            System.out.println("binding is success.");

            this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);

            System.out.println("initing is success.");

        } catch (AlreadyBoundException abe) {
            // 이미 사용중인 포트에 바인딩하려면 에러
            System.err.println(abe.getMessage());
            this.exit();
        } catch (IOException e) {
            System.err.println(e.getMessage());
            this.exit();
        }

    }

    protected synchronized void exit() {

        try {
            this.isStart = false;
            this.serverSocketChannel.close();
            this.acceptSelector.close();
            this.threadpool.shutdown();
            for (int i = 0; i < this.readSelectors.size(); i++) {
                this.readSelectors.get(i).close();
            }
        } catch (IOException e) {
            System.err.print(e.getMessage());
        }

    }

    protected synchronized void connectCountAdd() {
        connectionCount++;
    }

    protected synchronized void connectCountMinus() {
        connectionCount--;
    }
}
</code>```

Quarter.java

```<code>import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Quarter extends Server {

    public Quarter() {
        init();
        this.initQuarter();
    }

    private void initQuarter() {

        while (isStart) {
            try {

                int ready = acceptSelector.select();
                if (ready <= 0) continue;

                Set<SelectionKey> set = acceptSelector.selectedKeys();
                Iterator<SelectionKey> selected = set.iterator();

                while (selected.hasNext()) {
                    SelectionKey key = selected.next();
                    selected.remove();

                    if (!key.isValid()) continue;

                    if (key.isAcceptable()) this.accept(key);

                }
            }
            catch (ClosedSelectorException cse) {

                System.err.println(cse.getMessage());
            }
            catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }

    }

    private void accept(SelectionKey key) {

        try {
            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();

            SocketChannel channel = serverChannel.accept();
            if (channel == null) return;

            channel.configureBlocking(false);

            int targetIndex = connectionCount % readSelectors.size();
            Selector tarSel = readSelectors.get(targetIndex);

            channel.register(tarSel, SelectionKey.OP_READ);

            connectCountAdd();

            System.out.println("Connected to: " + channel.getRemoteAddress());
            System.out.println("Current Connection Count: " + connectionCount);

        }
        catch (ClosedChannelException cce) {
            // 채널이 닫힌 경우
            System.err.println(cce.getMessage());
            key.cancel();
        }
        catch (ClosedSelectorException cse) {
            // 셀렉터가 닫힌 경우
            System.err.println(cse.getMessage());
            key.cancel();
            exit();
        }
        catch (IOException e) {
            System.err.println(e.getMessage());
            key.cancel();
            exit();
        }
    }
}
</code>```

SubSelector.java

```<code>import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class SubSelector extends Server implements Runnable {

   private Selector selector = null;
   Charset charset = Charset.forName("UTF-8");

   public SubSelector(Selector selector) {
      this.selector = selector;
   }

   @Override
   public void run() {

      while (isStart) {

         try {

            int ready = selector.select();
            if (ready <= 0) return;

            Set<SelectionKey> set = this.selector.selectedKeys();
            Iterator<SelectionKey> selected = set.iterator();

            while (selected.hasNext()) {

               SelectionKey key = selected.next();
               selected.remove();

               if (!key.isValid()) continue;

               if (key.isReadable()) this.read(key);
            }

         }
         catch (ClosedSelectorException cse) {
            System.err.println(cse.getMessage());
         }
         catch (IOException e) {
            System.err.println(e.getMessage());
         }
      }
   }

   private void read(SelectionKey key) {

      try {

         SocketChannel channel = (SocketChannel) key.channel();
         ByteBuffer buffer = ByteBuffer.allocate(100);
         int readCount = channel.read(buffer);

         if (readCount <= 0) return;

         buffer.flip();
         String result = charset.decode(buffer).toString();

         System.out.println("client ip address: " + channel.getRemoteAddress());
         System.out.println("client send message: " + result);
      }
      catch (NotYetConnectedException nyce) {
         // 채널이 아직 연결되지 않은 경우
         System.err.println(nyce.getMessage());
      }
      catch (SocketException se) {
          System.err.println(se.getMessage());
          this.disConnect(key);
      }
      catch (IOException e) {
         // 기타 에러
         System.err.println(e.getMessage());
      }
   }

   private void disConnect(SelectionKey key) {
       key.cancel();
       selector.wakeup();
       connectCountMinus();
       System.out.println("Current Connection Count: " + connectionCount);
   }
}
</code>```

Client.java

```<code>import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) throws Exception {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress("192.168.75.35", 1111));
            System.out.println("is Connected: " + socket.isConnected());

            while (true) {

                OutputStream os = socket.getOutputStream();
                os.write(Thread.currentThread().getName().getBytes());
                os.flush();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
Please help .

When you first start the server, create a thread pool in advance (5 threads) and create 5 selectors to read, pass one selector to each Runnable, and immediately send the submit function to the thread pool.

Then, create a selector that accepts the user and run it on the main thread.

The problem here is that the Selector in the main thread detects the user's request and registers the returned SocketChannel in one of the 5 Read Selectors.

And when the connection is successful, the user sends text data every second, but there is no response from the Read Selector.

I don't know why this problem occurs.. ㅜㅜ

Main.java

public class Main {

    public static void main(String[] args) {

        Server server = new Quarter();

    }

}

Server.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AlreadyBoundException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class Server {

    protected volatile boolean isStart = true;

    // 192.168.0.11 company
    // 192.168.75.35 house
    // 192.168.75.97 my notebook
    private static final String ADDRESS = "192.168.75.35";
    private static final int    PORT    = 1111;
    private static final int    BACKLOG = 1024;

    protected Selector acceptSelector = null;

    /** 하나의 스레드에서만 접근 할것이기 때문에 동기화 처리는 필요 없음. */
    protected List<Selector> readSelectors = new ArrayList<Selector>();

    protected ServerSocketChannel serverSocketChannel = null;
    protected InetSocketAddress inetSocketAddress = null;

    private final int nThreads = 5;
    protected ExecutorService threadpool = null;

    /** 현재 연결된 클라이언트 수 */
    protected static int connectionCount = 0;
    // volatile 캐시 메모리 문제는 아닌가?
    // 뭐가 문제지?

    protected void init() {
        try {

            this.threadpool = Executors.newFixedThreadPool(this.nThreads);

            for (int i = 1; i <= this.nThreads; i++) {
                Selector sel = Selector.open();
                this.readSelectors.add(sel);
                threadpool.submit(new SubSelector(sel));
            }

            this.acceptSelector = Selector.open();
            this.inetSocketAddress = new InetSocketAddress(ADDRESS, PORT);

            this.serverSocketChannel = ServerSocketChannel.open();

            // non - blocking 으로 설정.
            this.serverSocketChannel.configureBlocking(false);
            System.out.println("serverSocketChannel is non-blocking.");

            this.serverSocketChannel.bind(this.inetSocketAddress, BACKLOG);
            System.out.println("binding is success.");

            this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);

            System.out.println("initing is success.");

        } catch (AlreadyBoundException abe) {
            // 이미 사용중인 포트에 바인딩하려면 에러
            System.err.println(abe.getMessage());
            this.exit();
        } catch (IOException e) {
            System.err.println(e.getMessage());
            this.exit();
        }

    }

    protected synchronized void exit() {

        try {
            this.isStart = false;
            this.serverSocketChannel.close();
            this.acceptSelector.close();
            this.threadpool.shutdown();
            for (int i = 0; i < this.readSelectors.size(); i++) {
                this.readSelectors.get(i).close();
            }
        } catch (IOException e) {
            System.err.print(e.getMessage());
        }

    }

    protected synchronized void connectCountAdd() {
        connectionCount++;
    }

    protected synchronized void connectCountMinus() {
        connectionCount--;
    }
}

Quarter.java

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Quarter extends Server {

    public Quarter() {
        init();
        this.initQuarter();
    }

    private void initQuarter() {

        while (isStart) {
            try {

                int ready = acceptSelector.select();
                if (ready <= 0) continue;

                Set<SelectionKey> set = acceptSelector.selectedKeys();
                Iterator<SelectionKey> selected = set.iterator();

                while (selected.hasNext()) {
                    SelectionKey key = selected.next();
                    selected.remove();

                    if (!key.isValid()) continue;

                    if (key.isAcceptable()) this.accept(key);

                }
            }
            catch (ClosedSelectorException cse) {

                System.err.println(cse.getMessage());
            }
            catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }

    }

    private void accept(SelectionKey key) {

        try {
            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();

            SocketChannel channel = serverChannel.accept();
            if (channel == null) return;

            channel.configureBlocking(false);

            int targetIndex = connectionCount % readSelectors.size();
            Selector tarSel = readSelectors.get(targetIndex);

            channel.register(tarSel, SelectionKey.OP_READ);

            connectCountAdd();

            System.out.println("Connected to: " + channel.getRemoteAddress());
            System.out.println("Current Connection Count: " + connectionCount);

        }
        catch (ClosedChannelException cce) {
            // 채널이 닫힌 경우
            System.err.println(cce.getMessage());
            key.cancel();
        }
        catch (ClosedSelectorException cse) {
            // 셀렉터가 닫힌 경우
            System.err.println(cse.getMessage());
            key.cancel();
            exit();
        }
        catch (IOException e) {
            System.err.println(e.getMessage());
            key.cancel();
            exit();
        }
    }
}

SubSelector.java

import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class SubSelector extends Server implements Runnable {

   private Selector selector = null;
   Charset charset = Charset.forName("UTF-8");

   public SubSelector(Selector selector) {
      this.selector = selector;
   }

   @Override
   public void run() {

      while (isStart) {

         try {

            int ready = selector.select();
            if (ready <= 0) return;

            Set<SelectionKey> set = this.selector.selectedKeys();
            Iterator<SelectionKey> selected = set.iterator();

            while (selected.hasNext()) {

               SelectionKey key = selected.next();
               selected.remove();

               if (!key.isValid()) continue;

               if (key.isReadable()) this.read(key);
            }

         }
         catch (ClosedSelectorException cse) {
            System.err.println(cse.getMessage());
         }
         catch (IOException e) {
            System.err.println(e.getMessage());
         }
      }
   }

   private void read(SelectionKey key) {

      try {

         SocketChannel channel = (SocketChannel) key.channel();
         ByteBuffer buffer = ByteBuffer.allocate(100);
         int readCount = channel.read(buffer);

         if (readCount <= 0) return;

         buffer.flip();
         String result = charset.decode(buffer).toString();

         System.out.println("client ip address: " + channel.getRemoteAddress());
         System.out.println("client send message: " + result);
      }
      catch (NotYetConnectedException nyce) {
         // 채널이 아직 연결되지 않은 경우
         System.err.println(nyce.getMessage());
      }
      catch (SocketException se) {
          System.err.println(se.getMessage());
          this.disConnect(key);
      }
      catch (IOException e) {
         // 기타 에러
         System.err.println(e.getMessage());
      }
   }

   private void disConnect(SelectionKey key) {
       key.cancel();
       selector.wakeup();
       connectCountMinus();
       System.out.println("Current Connection Count: " + connectionCount);
   }
}

Client.java

import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) throws Exception {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress("192.168.75.35", 1111));
            System.out.println("is Connected: " + socket.isConnected());

            while (true) {

                OutputStream os = socket.getOutputStream();
                os.write(Thread.currentThread().getName().getBytes());
                os.flush();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


来源: stackexchange

问:
POST request returns "414 URI too long" - mwn (axios might be involved)
I'm maintaining a bot for Wikipedia using npm mwbot, but now I'm migrating to mwn. I'm experiencing some strange behaviour of mwn; that is, a POST request fails because of a 414 error.

Let's say you have some list of usernames from a wiki project and you want to check if any of the users is blocked from editing. This can be done by mediawiki action API list=blocks with the "bkusers" parameter specified with a pipe- (or "|"-) separated list of usernames, and bots can query 500 usernames with one API call. The following TypeScript code should do the job, but the relevant query fails because of 414. (Since it's a POST request, I have absolutely no idea why.)

```<code>import { mwn } from "mwn";

(async () => {

    const mw: mwn = await mwn.init({
        apiUrl: 'https://en.wikipedia.org/w/api.php',
        username: 'YourBotUsername',
        password: 'YourBotPassword',
        userAgent: 'myCoolToolName 1.0 ([[link to bot user page or tool documentation]])'
    });

    interface DynamicObject {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        [key: string]: any
    }
    interface ApiResponseListLogeventsItem {
        logid: number,
        ns: number,
        title: string,
        pageid: number,
        logpage: number,
        params: DynamicObject,
        type: string,
        action: string,
        user: string,
        anon?: boolean,
        timestamp: string,
        comment: string
    }
    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    interface ApiResponseListLogevents extends Array<ApiResponseListLogeventsItem> {}

    // Get 500 (5000 if you're a bot) usernames from the latest logs of account creation
    const response = await mw.continuedQuery({
        action: 'query',
        list: 'logevents',
        leprop: 'ids|title|timestamp',
        letype: 'newusers',
        lelimit: 'max',
    }, 1).then(res => res).catch(err => console.log(err.info));
    if (!response) return;
    const resLgev: ApiResponseListLogevents = response.filter((obj: DynamicObject) => obj && obj.query && obj.query.logevents).map(obj => obj.query && obj.query.logevents).flat();
    const users = resLgev.filter(obj => obj.title).map(obj => obj.title.replace(/^User:/, ''));
    console.log(users.length);

    // Check if any of the users is blocked
    const r = await mw.request({ // => Returns 414 'URI Too Long' although this is a POST request
        action: 'query',
        list: 'blocks',
        bklimit: 'max',
        bkusers: users.slice(0, 500).join('|'), // Pipe-separated list of users
        bkprop: 'user|timestamp|expiry|restrictions|flags',
        formatversion: '2'
    }, {method: 'POST'}).then(res => res).catch(err => console.log(err));

    if (!r || !r.query || !r.query.blocks) return console.log('!');
    console.log(r.query.blocks.length);

})();
</code>```

The first half of the code isn't that important because it's just there to fetch some random usernames from the API. The problem is with mw.request(). An equivalent code with the mwbot framework works so this doesn't seem to be a server-side issue. I would appreciate any comments on what'd be wrong.

I don't know if this is relevant but the issue might come from axios, which mwn uses for HTTP requests. Yesterday I wrote a function to scrape a webpage, and at first used axios. But it constantly spit "Package subpath './lib/defaults' is not defined by 'exports'" error so I uninstalled it and am now using node:https to fetch a website's html. But as I just said above, I don't know if this is relevant in any way.

ContentLicense: CC BY-SA 4.0

Body:
I'm maintaining a bot for Wikipedia using npm mwbot, but now I'm migrating to mwn. I'm experiencing some strange behaviour of mwn; that is, a POST request fails because of a 414 error.

Let's say you have some list of usernames from a wiki project and you want to check if any of the users is blocked from editing. This can be done by mediawiki action API list=blocks with the "bkusers" parameter specified with a pipe- (or "|"-) separated list of usernames, and bots can query 500 usernames with one API call. The following TypeScript code should do the job, but the relevant query fails because of 414. (Since it's a POST request, I have absolutely no idea why.)

import { mwn } from "mwn";

(async () => {

    const mw: mwn = await mwn.init({
        apiUrl: 'https://en.wikipedia.org/w/api.php',
        username: 'YourBotUsername',
        password: 'YourBotPassword',
        userAgent: 'myCoolToolName 1.0 ([[link to bot user page or tool documentation]])'
    });

    interface DynamicObject {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        [key: string]: any
    }
    interface ApiResponseListLogeventsItem {
        logid: number,
        ns: number,
        title: string,
        pageid: number,
        logpage: number,
        params: DynamicObject,
        type: string,
        action: string,
        user: string,
        anon?: boolean,
        timestamp: string,
        comment: string
    }
    // eslint-disable-next-line @typescript-eslint/no-empty-interface
    interface ApiResponseListLogevents extends Array<ApiResponseListLogeventsItem> {}

    // Get 500 (5000 if you're a bot) usernames from the latest logs of account creation
    const response = await mw.continuedQuery({
        action: 'query',
        list: 'logevents',
        leprop: 'ids|title|timestamp',
        letype: 'newusers',
        lelimit: 'max',
    }, 1).then(res => res).catch(err => console.log(err.info));
    if (!response) return;
    const resLgev: ApiResponseListLogevents = response.filter((obj: DynamicObject) => obj && obj.query && obj.query.logevents).map(obj => obj.query && obj.query.logevents).flat();
    const users = resLgev.filter(obj => obj.title).map(obj => obj.title.replace(/^User:/, ''));
    console.log(users.length);

    // Check if any of the users is blocked
    const r = await mw.request({ // => Returns 414 'URI Too Long' although this is a POST request
        action: 'query',
        list: 'blocks',
        bklimit: 'max',
        bkusers: users.slice(0, 500).join('|'), // Pipe-separated list of users
        bkprop: 'user|timestamp|expiry|restrictions|flags',
        formatversion: '2'
    }, {method: 'POST'}).then(res => res).catch(err => console.log(err));

    if (!r || !r.query || !r.query.blocks) return console.log('!');
    console.log(r.query.blocks.length);

})();

The first half of the code isn't that important because it's just there to fetch some random usernames from the API. The problem is with mw.request(). An equivalent code with the mwbot framework works so this doesn't seem to be a server-side issue. I would appreciate any comments on what'd be wrong.

I don't know if this is relevant but the issue might come from axios, which mwn uses for HTTP requests. Yesterday I wrote a function to scrape a webpage, and at first used axios. But it constantly spit "Package subpath './lib/defaults' is not defined by 'exports'" error so I uninstalled it and am now using node:https to fetch a website's html. But as I just said above, I don't know if this is relevant in any way.


问:
Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
I am using geoapify to generate address from latitude and longitude. Api Is working fine in
postman, but when I am using it into my app. It is giving be cors policy error when I login into my website and without login it is also working fine in my app too.
I have found my similar question but most of them are using backend api not any 3rd party api.But after reading so many question I found that adding Authorization token in header my may work. but it didn't worked. Anyone can please what should i do in my case.

gymservice.ts

```<code>getaddress(lat:any,long:any){

      return this.http.get(`https://api.geoapify.com/v1/geocode/reverse?lat=${lat}&lon=${long}&apiKey=myapikey`);
  }
</code>```

gymlist.ts

```<code>generateAddress(latitude:any,longitude:any){
       this.toolservice.getaddress(latitude,longitude).subscribe((res:any)=>{
            this.userState = res.features[0].properties.state;
            this.userCity = res.features[0].properties.state_district;
            console.log(this.userCity);
            console.log(this.userState);
            this.getGymByStateCity();
       });
  }
</code>```

Body:
I am using geoapify to generate address from latitude and longitude. Api Is working fine in
postman, but when I am using it into my app. It is giving be cors policy error when I login into my website and without login it is also working fine in my app too.
I have found my similar question but most of them are using backend api not any 3rd party api.But after reading so many question I found that adding Authorization token in header my may work. but it didn't worked. Anyone can please what should i do in my case.

gymservice.ts

getaddress(lat:any,long:any){

      return this.http.get(`https://api.geoapify.com/v1/geocode/reverse?lat=${lat}&lon=${long}&apiKey=myapikey`);
  }

gymlist.ts

generateAddress(latitude:any,longitude:any){
       this.toolservice.getaddress(latitude,longitude).subscribe((res:any)=>{
            this.userState = res.features[0].properties.state;
            this.userCity = res.features[0].properties.state_district;
            console.log(this.userCity);
            console.log(this.userState);
            this.getGymByStateCity();
       });
  }


问:
Categorizing different types of likes on a post and displaying it using AJAX php
I want to create a LIKE BUTTON for 3 separate columns in my table, which I have created using Handsontable. On clicking any of these like buttons the response should be taken and sent to a PHP file. The PHP file, fetches the data and processes the SQL query to update the number of likes on the post. The required system is exactly like any other LIKE BUTTON feature (For Ex: Instagram).

Columns in the table:

Employee Name

Employee ID

Rank (For the top 3 best targets)

Goal Comment

Goal Commit

Result (target reached: O/X)

Reply Comment

Goal Comment Like (like button corresponding to 4. Goal Comment)

Goal Commit Like (like button corresponding to 5. Goal Commit)

Reply Comment Like (like button corresponding to 7. Reply Comment)

Column 8,9 and 10 are displayed within column 4,5 and 7 respectively since they represent like button using innerHtml and a custom Renderer like this:

```<code>function detailRenderer(instance, td, row, col, prop, value, cellProperties) {
    if (col == 4) {
        if (value != null && instance.getDataAtCell(row, 8) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            cellProperties.readOnly = false;
            td.innerHTML =   '<div class="like">'+value+'<div class="in-like" style="color:red;"><i class="far fa-heart"></i>' + instance.getDataAtCell(row, 9) + '</div</div>';
            console.log(instance.getDataAtCell(row, 8));
        }
        else if(value != null && instance.getDataAtCell(row, 8) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML =   '<div class="like">'+value+'<i class="far fa-heart" style="color:red;"></i></div>';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else if (col == 6) {
        if (value != null && instance.getDataAtCell(row, 9) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value + '<div class="in-like" style="color:red;"><i class="far fa-heart"></i>' + instance.getDataAtCell(row, 9) + '</div></div>';
        }
        else if(value != null && instance.getDataAtCell(row, 10) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value+'<i class="far fa-heart" style="color:red;"></i></div>';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else if (col == 8) {
        if (value != null && instance.getDataAtCell(row, 10) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value + '<div class="in-like" style="color:red;"><i class="far fa-heart"></i>' + instance.getDataAtCell(row, 11) + '</div></div>';
        }
        else if(value != null && instance.getDataAtCell(row, 10) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '<div class="like">'+value+'<i class="far fa-heart" style="color:red;"></i></div>';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else{
        Handsontable.renderers.TextRenderer.apply(this, arguments);
    }
}
</code>```

This is my AJAX function which I know is definitely wrong since I am new to AJAX:

```<code>$(document).on("click", ".in-like", function(e) {
        e.preventDefault();
        var likesCounter = hot.getDataAtRowProp(row, 9);
        $.ajax({
            url: '/mycommit/like.php',
            type: 'POST',
            data: {
                'challengeId': '{{challengeId}}',
                'userId': '{{SYANM}}',
                'likesCounter': '{{likesCounter}}',
                type: 'POST',
            },
            success: function(data) {
                likesCounter = data;
                console.log(likesCounter);
            },
        });
    });
</code>```

My PHP file is:

```<code><?php
use service\LoginService;
use util\TwigCommon;
use util\DbUtil;

$out = array();
$challengeID = $_GET['challengeID'];
$userID = $_GET['userID'];
$likesCounter = getLikesCounter($challengeID, $userID);

$out['SYANM'] = $_SESSION["login"]["SYANM"];
if(LoginService::hasRole(['system'])){
    $out["systemUser"] = 1;
}
else {
    $out["systemUser"] = 0;
}
$out['challengeID'] = $challengeID;
$out['userID'] = $userID;
$out['likesCounter'] = $likesCounter;

function getLikesCounter($challengeID, $userID){
    $params = array();
    $params['challengeID'] = $challengeID;
    $params['userID'] = $userID;

    $sql = <<<SQL
    SELECT COUNT(*) as likesCounter from HB_MYC_LIKES
    WHERE CHALLENGE_ID = :challengeID
    SQL;
    $result = DbUtil::query($sql, $params);
    $list = array_values($result);
    foreach ($list as $key => $value) {
        $list[$key]['GOAL_COMMIT_LIKES'] = count($list[$key]['GOAL_COMMIT_LIKES']);
        $list[$key]['GOAL_COMMENT_LIKES'] = count($list[$key]['GOAL_COMMENT_LIKES']);
        $list[$key]['REPLY_COMMENT_LIKES'] = count($list[$key]['REPLY_COMMENT_LIKES']);
    }
    return $list;
}
//-----------------------------------------------//
/*This is just an attempt for different approach*/
//-----------------------------------------------//

if(isset($_GET('challengeID'))) {
    $challengeID = $_GET['challengeID'];
    $likesCounter = getLikesCounter($challengeID, $userID);
    echo json_encode($likesCounter);
}

</code>```

I am unable to understand how to get categorized LIKES data, currently this code is taking just likes if it exists without categorizing and I do not want to assign separate value to each like column in the frontend. Instead I want to do it in the backend with the PHP file. Since I am a beginner to this, any help would be appreciated.

Body:
I want to create a LIKE BUTTON for 3 separate columns in my table, which I have created using Handsontable. On clicking any of these like buttons the response should be taken and sent to a PHP file. The PHP file, fetches the data and processes the SQL query to update the number of likes on the post. The required system is exactly like any other LIKE BUTTON feature (For Ex: Instagram).

Columns in the table:

Employee Name

Employee ID

Rank (For the top 3 best targets)

Goal Comment

Goal Commit

Result (target reached: O/X)

Reply Comment

Goal Comment Like (like button corresponding to 4. Goal Comment)

Goal Commit Like (like button corresponding to 5. Goal Commit)

Reply Comment Like (like button corresponding to 7. Reply Comment)

Column 8,9 and 10 are displayed within column 4,5 and 7 respectively since they represent like button using innerHtml and a custom Renderer like this:

function detailRenderer(instance, td, row, col, prop, value, cellProperties) {
    if (col == 4) {
        if (value != null && instance.getDataAtCell(row, 8) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            cellProperties.readOnly = false;
            td.innerHTML =   '
'+value+'
' + instance.getDataAtCell(row, 9) + '</div
';
            console.log(instance.getDataAtCell(row, 8));
        }
        else if(value != null && instance.getDataAtCell(row, 8) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML =   '
'+value+'
';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else if (col == 6) {
        if (value != null && instance.getDataAtCell(row, 9) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '
'+value + '
' + instance.getDataAtCell(row, 9) + '

';
        }
        else if(value != null && instance.getDataAtCell(row, 10) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '
'+value+'
';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else if (col == 8) {
        if (value != null && instance.getDataAtCell(row, 10) != null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '
'+value + '
' + instance.getDataAtCell(row, 11) + '

';
        }
        else if(value != null && instance.getDataAtCell(row, 10) == null){
            Handsontable.renderers.TextRenderer.apply(this, arguments);
            td.innerHTML = '
'+value+'
';
        }
        else{
            Handsontable.renderers.TextRenderer.apply(this, arguments);
        }
    }
    else{
        Handsontable.renderers.TextRenderer.apply(this, arguments);
    }
}

This is my AJAX function which I know is definitely wrong since I am new to AJAX:

$(document).on("click", ".in-like", function(e) {
        e.preventDefault();
        var likesCounter = hot.getDataAtRowProp(row, 9);
        $.ajax({
            url: '/mycommit/like.php',
            type: 'POST',
            data: {
                'challengeId': '{{challengeId}}',
                'userId': '{{SYANM}}',
                'likesCounter': '{{likesCounter}}',
                type: 'POST',
            },
            success: function(data) {
                likesCounter = data;
                console.log(likesCounter);
            },
        });
    });

My PHP file is:

<?php
use service\LoginService;
use util\TwigCommon;
use util\DbUtil;

$out = array();
$challengeID = $_GET['challengeID'];
$userID = $_GET['userID'];
$likesCounter = getLikesCounter($challengeID, $userID);

$out['SYANM'] = $_SESSION["login"]["SYANM"];
if(LoginService::hasRole(['system'])){
    $out["systemUser"] = 1;
}
else {
    $out["systemUser"] = 0;
}
$out['challengeID'] = $challengeID;
$out['userID'] = $userID;
$out['likesCounter'] = $likesCounter;

function getLikesCounter($challengeID, $userID){
    $params = array();
    $params['challengeID'] = $challengeID;
    $params['userID'] = $userID;

    $sql = <<<SQL
    SELECT COUNT(*) as likesCounter from HB_MYC_LIKES
    WHERE CHALLENGE_ID = :challengeID
    SQL;
    $result = DbUtil::query($sql, $params);
    $list = array_values($result);
    foreach ($list as $key => $value) {
        $list[$key]['GOAL_COMMIT_LIKES'] = count($list[$key]['GOAL_COMMIT_LIKES']);
        $list[$key]['GOAL_COMMENT_LIKES'] = count($list[$key]['GOAL_COMMENT_LIKES']);
        $list[$key]['REPLY_COMMENT_LIKES'] = count($list[$key]['REPLY_COMMENT_LIKES']);
    }
    return $list;
}
//-----------------------------------------------//
/*This is just an attempt for different approach*/
//-----------------------------------------------//

if(isset($_GET('challengeID'))) {
    $challengeID = $_GET['challengeID'];
    $likesCounter = getLikesCounter($challengeID, $userID);
    echo json_encode($likesCounter);
}

I am unable to understand how to get categorized LIKES data, currently this code is taking just likes if it exists without categorizing and I do not want to assign separate value to each like column in the frontend. Instead I want to do it in the backend with the PHP file. Since I am a beginner to this, any help would be appreciated.


问:
Google Script in Google Forms: how to get the Id of the uploaded file?
First of all, my context:

I have a google form questionary, whose first question asks to upload a Google Drive doc, which has inside some spaces with {{}} to be modfied automatically.

I want these modifications to be made by the further answers submitted in the questionary. Example:

1St question: "Upload the doc"-> doc is uploaded

2nd question: "Type your age" -> the age should be automatically wrtitten in the uploaded doc, in the space maked as {{age}}

3rd question: "Type your name" -> the name should be automatically wrtitten in the uploaded doc, in the space maked as {{name}}

So my question is: how to get in google Script the Id of the uploaded file?

I guess that I can open the document in the process it with

```<code>DocumentApp.openById
</code>```

but first I need to get the file Id.

Thanks!

Body:
First of all, my context:

I have a google form questionary, whose first question asks to upload a Google Drive doc, which has inside some spaces with {{}} to be modfied automatically.

I want these modifications to be made by the further answers submitted in the questionary. Example:

1St question: "Upload the doc"-> doc is uploaded

2nd question: "Type your age" -> the age should be automatically wrtitten in the uploaded doc, in the space maked as {{age}}

3rd question: "Type your name" -> the name should be automatically wrtitten in the uploaded doc, in the space maked as {{name}}

So my question is: how to get in google Script the Id of the uploaded file?

I guess that I can open the document in the process it with

DocumentApp.openById

but first I need to get the file Id.

Thanks!


问:
A global templated extern variable without definition
I am reviewing a large project that has a header file that is declaring a templated extern variable. Roughly speaking, there is a single header foo.hpp that looks like this:

```<code>#pragma once
#include <cstdio>

namespace bar {

template <bool ndebug>
struct Foo {
    template <typename T>
    Foo &operator<<(T &&t) {
        if constexpr (ndebug) {
            puts(t);
        } else {
            puts("debug");
        }
        return *this;
    }
};

extern Foo<true> global_foo;

}  // namespace bar
</code>```

This header is included in multiple translation units and other headers.

The issue that I am struggling with is the extern declaration of the variable at the bottom:

```<code>extern Foo<true> global_foo;
</code>```

I can not find an instance in the codebase where the variable global_foo is defined. Specifically, I am expecting to find a translation unit with the statement

```<code>Foo<true> global_foo;
</code>```

but grepping the codebase reveals no such usage. Every usage is of the form

```<code>global_foo << something;
</code>```

This suggests to me that global_foo is never defined.

Is there some special rule or scenario in which this is allowed?

The project involves building several libraries and then linking them into the main binary. I have tried deleting the build folder to make sure that there are no artifacts. I tried changing the libraries between static and shared. In every scenario, the project is building.

This suggests to me that there must be some rule I am not aware of, or some build feature being employed to allow this.

Body:
I am reviewing a large project that has a header file that is declaring a templated extern variable. Roughly speaking, there is a single header foo.hpp that looks like this:

#pragma once
#include <cstdio>

namespace bar {

template <bool ndebug>
struct Foo {
    template <typename T>
    Foo &operator<<(T &&t) {
        if constexpr (ndebug) {
            puts(t);
        } else {
            puts("debug");
        }
        return *this;
    }
};

extern Foo<true> global_foo;

}  // namespace bar

This header is included in multiple translation units and other headers.

The issue that I am struggling with is the extern declaration of the variable at the bottom:

extern Foo<true> global_foo;

I can not find an instance in the codebase where the variable global_foo is defined. Specifically, I am expecting to find a translation unit with the statement

Foo<true> global_foo;

but grepping the codebase reveals no such usage. Every usage is of the form

global_foo << something;

This suggests to me that global_foo is never defined.

Is there some special rule or scenario in which this is allowed?

The project involves building several libraries and then linking them into the main binary. I have tried deleting the build folder to make sure that there are no artifacts. I tried changing the libraries between static and shared. In every scenario, the project is building.

This suggests to me that there must be some rule I am not aware of, or some build feature being employed to allow this.


问:
Flutter Google Map rounded image marker not align in the center
I recently worked the the google maps with flutter.

i created the marker to indicate the users current location. and added three circles in to indicate the accuracy of the Google map. And the marker image is round shaped. and it is bottom aligned.

But i need the center alignment of the marker.
Like this

The Output of my code

The function for getting user location and set marker and circles

```<code>  onInitFunc() async {
    locationicon = BitmapDescriptor.fromBytes(
        await getBytesFromAsset('assets/icons/map-store.png'));
    mylocationicon = BitmapDescriptor.fromBytes(
      await getBytesFromAsset('assets/images/avatar.png'),
    );
    setState(() {
      isIconsUpdated = true;
    });
    var _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }
    currentLocation = await location.getLocation();
    await setMarketsOfMyLocation();
    locationSubscription = location.onLocationChanged.listen((location) async {
      currentLocation = location;
      await setMarketsOfMyLocation();
      setState(() {});
    });
    setState(() {});
  }

  setMarketsOfMyLocation() async {
    markers.add(
      Marker(
        markerId: const MarkerId('myPosition'),
        position: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        flat: true,
        icon: mylocationicon,
        onTap: () {
          mapController.animateCamera(
            CameraUpdate.newCameraPosition(
              CameraPosition(
                target: LatLng(
                  currentLocation!.latitude!,
                  currentLocation!.longitude!,
                ),
                zoom: 15,
              ),
            ),
          );
          setState(() {});
        },
      ),
    );
    circles = {
      Circle(
        circleId: const CircleId('myPosition1'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 100,
        fillColor: Colors.white.withOpacity(0.5),
        strokeWidth: 0,
      ),
      Circle(
        circleId: const CircleId('myPosition2'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 200,
        fillColor: const Color(0xFFFAAB1B).withOpacity(0.1),
        strokeWidth: 0,
      ),
      Circle(
        circleId: const CircleId('myPosition3'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 300,
        fillColor: const Color(0xFFFAAB1B).withOpacity(0.05),
        strokeWidth: 0,
      ),
    };
    setState(() {});
  }

</code>```

The widget code of google map

```<code>SizedBox(
  width: MediaQuery.of(context).size.width,
  height: MediaQuery.of(context).size.height,
  child: GoogleMap(
    circles: circles,
    mapToolbarEnabled: false,
    myLocationButtonEnabled: false,
    myLocationEnabled: false,
    initialCameraPosition: CameraPosition(
      zoom: 10,
      target: LatLng(
        // bangalore
        currentLocation.runtimeType == Null
            ? 12.9716
            : currentLocation!.latitude!,
        currentLocation.runtimeType == Null
            ? 77.5946
            : currentLocation!.longitude!,
      ),
    ),
    onTap: (position) {
      _customInfoWindowController.hideInfoWindow();
      setState(() {
        currentStore = null;
      });
      mapController.animateCamera(
        CameraUpdate.newLatLngBounds(bounds(markers)!, 50),
      );
    },
    onCameraMove: (position) {
      _customInfoWindowController.onCameraMove();
    },
    mapType: MapType.normal,
    markers: markers,
    onMapCreated: onMapcreated,
    compassEnabled: true,
    zoomControlsEnabled: false,
  ),
),

</code>```

Body:
I recently worked the the google maps with flutter.

i created the marker to indicate the users current location. and added three circles in to indicate the accuracy of the Google map. And the marker image is round shaped. and it is bottom aligned.

But i need the center alignment of the marker.
Like this

The Output of my code

The function for getting user location and set marker and circles

  onInitFunc() async {
    locationicon = BitmapDescriptor.fromBytes(
        await getBytesFromAsset('assets/icons/map-store.png'));
    mylocationicon = BitmapDescriptor.fromBytes(
      await getBytesFromAsset('assets/images/avatar.png'),
    );
    setState(() {
      isIconsUpdated = true;
    });
    var _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }
    currentLocation = await location.getLocation();
    await setMarketsOfMyLocation();
    locationSubscription = location.onLocationChanged.listen((location) async {
      currentLocation = location;
      await setMarketsOfMyLocation();
      setState(() {});
    });
    setState(() {});
  }

  setMarketsOfMyLocation() async {
    markers.add(
      Marker(
        markerId: const MarkerId('myPosition'),
        position: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        flat: true,
        icon: mylocationicon,
        onTap: () {
          mapController.animateCamera(
            CameraUpdate.newCameraPosition(
              CameraPosition(
                target: LatLng(
                  currentLocation!.latitude!,
                  currentLocation!.longitude!,
                ),
                zoom: 15,
              ),
            ),
          );
          setState(() {});
        },
      ),
    );
    circles = {
      Circle(
        circleId: const CircleId('myPosition1'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 100,
        fillColor: Colors.white.withOpacity(0.5),
        strokeWidth: 0,
      ),
      Circle(
        circleId: const CircleId('myPosition2'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 200,
        fillColor: const Color(0xFFFAAB1B).withOpacity(0.1),
        strokeWidth: 0,
      ),
      Circle(
        circleId: const CircleId('myPosition3'),
        center: LatLng(
          currentLocation!.latitude!,
          currentLocation!.longitude!,
        ),
        radius: 300,
        fillColor: const Color(0xFFFAAB1B).withOpacity(0.05),
        strokeWidth: 0,
      ),
    };
    setState(() {});
  }

The widget code of google map

SizedBox(
  width: MediaQuery.of(context).size.width,
  height: MediaQuery.of(context).size.height,
  child: GoogleMap(
    circles: circles,
    mapToolbarEnabled: false,
    myLocationButtonEnabled: false,
    myLocationEnabled: false,
    initialCameraPosition: CameraPosition(
      zoom: 10,
      target: LatLng(
        // bangalore
        currentLocation.runtimeType == Null
            ? 12.9716
            : currentLocation!.latitude!,
        currentLocation.runtimeType == Null
            ? 77.5946
            : currentLocation!.longitude!,
      ),
    ),
    onTap: (position) {
      _customInfoWindowController.hideInfoWindow();
      setState(() {
        currentStore = null;
      });
      mapController.animateCamera(
        CameraUpdate.newLatLngBounds(bounds(markers)!, 50),
      );
    },
    onCameraMove: (position) {
      _customInfoWindowController.onCameraMove();
    },
    mapType: MapType.normal,
    markers: markers,
    onMapCreated: onMapcreated,
    compassEnabled: true,
    zoomControlsEnabled: false,
  ),
),


问:
The data is already loaded from disk issue from mne
i am following this tutorial
M/EEG analysis with MNE Python

and i  have  a little errors in this fragment : 01:35:57 Working with BIDS data

i followed  all the steps before and also implemented code :

```<code>import matplotlib.pyplot as plt
import pathlib
import matplotlib
import mne
import mne_bids
matplotlib.use('Qt5Agg')
directory ='C:/Users/User/mne_data/MNE-sample-data/MEG\sample/sample_audvis_raw.fif'
raw =mne.io.read_raw(directory)
#raw.plot()
#plt.show()
events =mne.find_events(raw)
#print(events)
event_id ={
    "Auditory/Left":1,
    "Auditory/Right":2,
    "Visual/Left":3,
    "Visual/Right":4,
    "Smiley":5,
    "Button":32
}
raw.info['line_freq']=60
raw.load_data()
out_path =pathlib.Path("out_data/sample_bids")
bids_path =mne_bids.BIDSPath(subject='01',session='01',task='audiovisual',run='01',root=out_path)
mne_bids.write_raw_bids(raw,bids_path=bids_path,events_data=events,event_id=event_id,overwrite=True)
</code>```

but when i am running this code, i am getting issue :

```<code>ValueError: The data is already loaded from disk and may be altered. See warning for "allow_preload".
</code>```

i can't understand reason of this  error, how can i fix it?please helo me

Body:
i am following this tutorial
M/EEG analysis with MNE Python

and i  have  a little errors in this fragment : 01:35:57 Working with BIDS data

i followed  all the steps before and also implemented code :

import matplotlib.pyplot as plt
import pathlib
import matplotlib
import mne
import mne_bids
matplotlib.use('Qt5Agg')
directory ='C:/Users/User/mne_data/MNE-sample-data/MEG\sample/sample_audvis_raw.fif'
raw =mne.io.read_raw(directory)
#raw.plot()
#plt.show()
events =mne.find_events(raw)
#print(events)
event_id ={
    "Auditory/Left":1,
    "Auditory/Right":2,
    "Visual/Left":3,
    "Visual/Right":4,
    "Smiley":5,
    "Button":32
}
raw.info['line_freq']=60
raw.load_data()
out_path =pathlib.Path("out_data/sample_bids")
bids_path =mne_bids.BIDSPath(subject='01',session='01',task='audiovisual',run='01',root=out_path)
mne_bids.write_raw_bids(raw,bids_path=bids_path,events_data=events,event_id=event_id,overwrite=True)

but when i am running this code, i am getting issue :

ValueError: The data is already loaded from disk and may be altered. See warning for "allow_preload".

i can't understand reason of this  error, how can i fix it?please helo me


问:
In APEX zoomable Timeseries graph while selecting particular date , its showing last day data and and from selected date , only 10 hrs,
U can see in this image , i have selected 7th but its shows 6th date days hours anf 7th also, Im expecting 24hrs from same date , can anyone help me in this, I'm very new in apex library

U can see in this image , i have selected 7th but its shows 6th date days hours anf 7th also, Im expecting 24hrs from same date , can anyone help me in this, I'm very new in apex library

```<code>let options1 = {
      chart: {
        id: "chart2",
        type: "line",
        height: 230,
        stacked: true,
      },
      colors: ["#EE4B2B", "#e1ad01", "#027bc7"],

      stroke: {
        width: 3,
      },
      dataLabels: {
        enabled: false,
      },
      fill: {
        opacity: 1,
      },
      markers: {
        size: 0,
      },
      series: [
        {
          name: "Current_R",
          data: currentR,
        },
        {
          name: "Current_Y",
          data: currentY,
        },
        {
          name: "Current_B",
          data: currentB,
        },
      ],

      xaxis: {
        type: "datetime",
        tickPlacement: "on",

      },
      yaxis: {
        min: 0,
        tickAmount: 2,
      },
    };
    var chart1 = new ApexCharts(
      document.querySelector("#chart-area"),
      options1
    );

    chart1.render();
  }, [currentR]);

</code>```

Body:
U can see in this image , i have selected 7th but its shows 6th date days hours anf 7th also, Im expecting 24hrs from same date , can anyone help me in this, I'm very new in apex library

U can see in this image , i have selected 7th but its shows 6th date days hours anf 7th also, Im expecting 24hrs from same date , can anyone help me in this, I'm very new in apex library

let options1 = {
      chart: {
        id: "chart2",
        type: "line",
        height: 230,
        stacked: true,
      },
      colors: ["#EE4B2B", "#e1ad01", "#027bc7"],

      stroke: {
        width: 3,
      },
      dataLabels: {
        enabled: false,
      },
      fill: {
        opacity: 1,
      },
      markers: {
        size: 0,
      },
      series: [
        {
          name: "Current_R",
          data: currentR,
        },
        {
          name: "Current_Y",
          data: currentY,
        },
        {
          name: "Current_B",
          data: currentB,
        },
      ],

      xaxis: {
        type: "datetime",
        tickPlacement: "on",

      },
      yaxis: {
        min: 0,
        tickAmount: 2,
      },
    };
    var chart1 = new ApexCharts(
      document.querySelector("#chart-area"),
      options1
    );

    chart1.render();
  }, [currentR]);


问:
why observedLargestContentFullPaint is always GREATER thanLargestContentFullPaint when using LHCI?
I'm currently using LHCI integrated with Gitlab CICD pipeline and I need to do the following:-

Add Assertion for ObservedDomContent Load value generated from the LightHouse json report, is it possible?

I'm using type Simulated type "Simulated" I have noticed that the observedLargestContentFullPaint is always larger than the LargestContentFullPaint although I expected that it will be less, can anyone explain and which one should I rely on during my page assessment


问:
"System.Net.WebException: Connection reset" error in .NET MAUI
```<code>{System.Net.WebException: Connection reset
 ---> Java.Net.SocketException: Connection reset
   at Java.Interop.JniEnvironment.InstanceMethods.CallIntMethod(JniObjectReference instance, JniMethodInfo method, JniArgumentValue* args) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/obj/Release/net7.0/JniEnvironment.g.cs:line 11725
   at Java.Interop.JniPeerMembers.JniInstanceMethods.InvokeVirtualInt32Method(String encodedMember, IJavaPeerable self, JniArgumentValue* parameters) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:line 511
   at Java.Net.HttpURLConnection.get_ResponseCode() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net7.0/android-33/mcw/Java.Net.HttpURLConnection.cs:line 511
   at Xamarin.Android.Net.AndroidMessageHandler.<>c__DisplayClass132_0.<DoProcessRequest>b__2() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 577
   at System.Threading.Tasks.Task`1[[System.Net.HttpStatusCode, System.Net.Primitives, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]].InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__273_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Xamarin.Android.Net.AndroidMessageHandler.DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 577
   at Xamarin.Android.Net.AndroidMessageHandler.DoSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 417
  --- End of managed Java.Net.SocketException stack trace ---
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:215)
    at java.net.SocketInputStream.read(SocketInputStream.java:144)
    at com.android.okhttp.okio.Okio$2.read(Okio.java:138)
    at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:307)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:301)
    at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:197)
    at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:188)
    at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:129)
    at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:750)
    at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:622)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:475)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)

  --- End of managed Java.Net.SocketException stack trace ---
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:215)
    at java.net.SocketInputStream.read(SocketInputStream.java:144)
    at com.android.okhttp.okio.Okio$2.read(Okio.java:138)
    at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:307)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:301)
    at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:197)
    at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:188)
    at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:129)
    at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:750)
    at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:622)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:475)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)

   --- End of inner exception stack trace ---
   at Xamarin.Android.Net.AndroidMessageHandler.DoSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 431
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at Kuber.UI.Services.HttpClientService.<SendAsync>d__2`1[[System.String, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() in C:\Github\Kuber.UI\Kuber.UI\Services\Concrete\HttpClientService.cs:line 32}
</code>```

enter image description here

I am sending "JsonCryption.Encryption" and "JsonCryption.Decryption" encryption algorithms in encrypted json model.

When I tested my api published on win server, it was working without any problems. But after the server was shut down, I republished it with the domain over local IIS. But I can't send requests anymore because it gives this error. It was giving an error when I raised the api locally via visual studio. later i tried this method and i started getting this error.

```<code>public async Task<ResponseModel<TEntity>> SendAsync<TEntity>(HttpMethod method, string requestUri, object content)
{
    try
    {
        var url = new Uri(App.KuberURL + requestUri);
        var request = new RequestModel
        {
            model = JsonCryption.Encryption(JsonConvert.SerializeObject(content))
        };
        var cryptionContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
        HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);
        httpRequestMessage.Content = cryptionContent;
        var response = await _httpClient.SendAsync(httpRequestMessage);
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        var responseModel = JsonConvert.DeserializeObject<ResponseModel<TEntity>>(JsonCryption.Decryption(json));

        return responseModel;
    }
    catch(TimeoutException ex)
    {
        return null;
    }
    catch (WebException ex)
    {
        return null;
    }
    catch (Exception ex)
    {
        return null;
        //throw new Exception();
    }
}
public class ResponseModel<TEntity>
{
    public TEntity Value { get; set; }
    public int ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}
</code>```

Body:
{System.Net.WebException: Connection reset
 ---> Java.Net.SocketException: Connection reset
   at Java.Interop.JniEnvironment.InstanceMethods.CallIntMethod(JniObjectReference instance, JniMethodInfo method, JniArgumentValue* args) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/obj/Release/net7.0/JniEnvironment.g.cs:line 11725
   at Java.Interop.JniPeerMembers.JniInstanceMethods.InvokeVirtualInt32Method(String encodedMember, IJavaPeerable self, JniArgumentValue* parameters) in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:line 511
   at Java.Net.HttpURLConnection.get_ResponseCode() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net7.0/android-33/mcw/Java.Net.HttpURLConnection.cs:line 511
   at Xamarin.Android.Net.AndroidMessageHandler.<>c__DisplayClass132_0.<DoProcessRequest>b__2() in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 577
   at System.Threading.Tasks.Task`1[[System.Net.HttpStatusCode, System.Net.Primitives, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]].InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__273_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Xamarin.Android.Net.AndroidMessageHandler.DoProcessRequest(HttpRequestMessage request, URL javaUrl, HttpURLConnection httpConnection, CancellationToken cancellationToken, RequestRedirectionState redirectState) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 577
   at Xamarin.Android.Net.AndroidMessageHandler.DoSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 417
  --- End of managed Java.Net.SocketException stack trace ---
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:215)
    at java.net.SocketInputStream.read(SocketInputStream.java:144)
    at com.android.okhttp.okio.Okio$2.read(Okio.java:138)
    at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:307)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:301)
    at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:197)
    at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:188)
    at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:129)
    at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:750)
    at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:622)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:475)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)

  --- End of managed Java.Net.SocketException stack trace ---
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:215)
    at java.net.SocketInputStream.read(SocketInputStream.java:144)
    at com.android.okhttp.okio.Okio$2.read(Okio.java:138)
    at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:213)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:307)
    at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:301)
    at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:197)
    at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:188)
    at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:129)
    at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:750)
    at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:622)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:475)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)

   --- End of inner exception stack trace ---
   at Xamarin.Android.Net.AndroidMessageHandler.DoSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidMessageHandler.cs:line 431
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at Kuber.UI.Services.HttpClientService.<SendAsync>d__2`1[[System.String, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext() in C:\Github\Kuber.UI\Kuber.UI\Services\Concrete\HttpClientService.cs:line 32}

enter image description here

I am sending "JsonCryption.Encryption" and "JsonCryption.Decryption" encryption algorithms in encrypted json model.

When I tested my api published on win server, it was working without any problems. But after the server was shut down, I republished it with the domain over local IIS. But I can't send requests anymore because it gives this error. It was giving an error when I raised the api locally via visual studio. later i tried this method and i started getting this error.

public async Task<ResponseModel<TEntity>> SendAsync<TEntity>(HttpMethod method, string requestUri, object content)
{
    try
    {
        var url = new Uri(App.KuberURL + requestUri);
        var request = new RequestModel
        {
            model = JsonCryption.Encryption(JsonConvert.SerializeObject(content))
        };
        var cryptionContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
        HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);
        httpRequestMessage.Content = cryptionContent;
        var response = await _httpClient.SendAsync(httpRequestMessage);
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        var responseModel = JsonConvert.DeserializeObject<ResponseModel<TEntity>>(JsonCryption.Decryption(json));

        return responseModel;
    }
    catch(TimeoutException ex)
    {
        return null;
    }
    catch (WebException ex)
    {
        return null;
    }
    catch (Exception ex)
    {
        return null;
        //throw new Exception();
    }
}
public class ResponseModel<TEntity>
{
    public TEntity Value { get; set; }
    public int ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}


问:
How to use xmltodict.parse with non-printable data
I tried to convert xml to dict with Python

```<code>import xmltodict
xmltodict.parse('<a>as\x08</a>')
</code>```

But I got an exception

```<code>ExpatError                                Traceback (most recent call last)
<ipython-input-8-XXXXXX> in <module>
----> 1 xmltodict.parse('<a>as\x08</a>')

~\AppData\Local\Programs\Python\Python37\lib\site-packages\xmltodict.py in parse(xml_input, encoding, expat, process_namespaces, namespace_separator, disable_entities, process_comments, **kwargs)
    376         parser.Parse(b'',True)
    377     else:
--> 378         parser.Parse(xml_input, True)
    379     return handler.item
    380

ExpatError: not well-formed (invalid token): line 1, column 5
</code>```

How can I use xmltodict library with non-printable char

Body:
I tried to convert xml to dict with Python

import xmltodict
xmltodict.parse('as\x08')

But I got an exception

ExpatError                                Traceback (most recent call last)
<ipython-input-8-XXXXXX> in <module>
----> 1 xmltodict.parse('as\x08')

~\AppData\Local\Programs\Python\Python37\lib\site-packages\xmltodict.py in parse(xml_input, encoding, expat, process_namespaces, namespace_separator, disable_entities, process_comments, **kwargs)
    376         parser.Parse(b'',True)
    377     else:
--> 378         parser.Parse(xml_input, True)
    379     return handler.item
    380

ExpatError: not well-formed (invalid token): line 1, column 5

How can I use xmltodict library with non-printable char


问:
Filter ApplyConfigurationsFromAssembly
I have a requirement to create db context with a specific type of entity since i have multiple Db context on the solution.my problem is OnModelCreating we apply Configuration from the assembly builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()). So i want to apply configuration with only BaseEntityConfig that inheritance from IEntityTypeConfiguration

this is one of my Config class

```<code>public class UnitEntityConfig : BaseEntityConfig<Unit,long>
{
    public override void Configure(EntityTypeBuilder<Unit> builder)
    {
        base.Configure(builder);

        builder.ToTable("TB_UNIT");

        builder.Property(a => a.Name)
            .HasColumnName("NAME")
            .HasMaxLength(300)
            .IsRequired();
    }
}
</code>```

and this my BaseEntityConfig

```<code>public class BaseEntityConfig<T,TId> : IEntityTypeConfiguration<T> where T : BaseEntity<TId>
{

    public virtual void Configure(EntityTypeBuilder<T> builder)
    {
       // some code
    }
}
</code>```

Title: Filter ApplyConfigurationsFromAssembly

Body:
I have a requirement to create db context with a specific type of entity since i have multiple Db context on the solution.my problem is OnModelCreating we apply Configuration from the assembly builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()). So i want to apply configuration with only BaseEntityConfig that inheritance from IEntityTypeConfiguration

this is one of my Config class

public class UnitEntityConfig : BaseEntityConfig<Unit,long>
{
    public override void Configure(EntityTypeBuilder<Unit> builder)
    {
        base.Configure(builder);

        builder.ToTable("TB_UNIT");

        builder.Property(a => a.Name)
            .HasColumnName("NAME")
            .HasMaxLength(300)
            .IsRequired();
    }
}

and this my BaseEntityConfig

public class BaseEntityConfig<T,TId> : IEntityTypeConfiguration<T> where T : BaseEntity<TId>
{

    public virtual void Configure(EntityTypeBuilder<T> builder)
    {
       // some code
    }
}


问:
Problem mobile Links do not have a discernible name
Problem mobile : Links do not have a discernible name
Link text (and alternate text for images, when used as links) that is discernible, unique, and focusable improves the navigation experience for screen reader user                                                    div#primary > main#main > section#widget_videos_block-1 > a.more-videos
\                class="more-videos label" href="https://example.com/?filter=latest "></p>
```<code>Hi I would like to know how to solve this problem :Links do not have a discernible name , but I don't know how to do it given my inexperience thanks
</code>```

Body:
Problem mobile : Links do not have a discernible name
Link text (and alternate text for images, when used as links) that is discernible, unique, and focusable improves the navigation experience for screen reader user                                                    div#primary > main#main > section#widget_videos_block-1 > a.more-videos
\

Hi I would like to know how to solve this problem :Links do not have a discernible name , but I don't know how to do it given my inexperience thanks


问:
How to sort gunichar in Glib::ustring?
I am trying to sort characters in Glib::ustring by their Unicode position. The following code:

```<code>Glib::ustring str("hello");
std::sort(str.begin(), str.end());
</code>```

produces the following error at compile time:

```<code>/usr/include/c++/10/bits/stl_algo.h:1975:22: error: no match for ‘operator-’ (operand types are ‘Glib::ustring_Iterator<__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> > >’ and ‘Glib::ustring_Iterator<__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> > >’)
 1975 |     std::__lg(__last - __first) * 2,
</code>```

My understanding is that sort is trying to get the difference between the first and last characters (i.e. the length of the container), but it is not defined by Glib::ustring_Iterator.

I can get around the problem by copying into some other container, and the putting it back:

```<code>Glib::ustring str("hello");
std::vector<gunichar> vec(str.begin(), str.end());
std::sort(vec.begin(), vec.end());
str.assign(Glib::ustring{vec.begin(), vec.end()});
</code>```

But this code feels like an ugly hack for a feature that i would expect to see in the library, but perhaps just not looking in the right place. Is this wheel already implemented?

Title: How to sort gunichar in Glib::ustring?

Body:
I am trying to sort characters in Glib::ustring by their Unicode position. The following code:

Glib::ustring str("hello");
std::sort(str.begin(), str.end());

produces the following error at compile time:

/usr/include/c++/10/bits/stl_algo.h:1975:22: error: no match for ‘operator-’ (operand types are ‘Glib::ustring_Iterator<__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> > >’ and ‘Glib::ustring_Iterator<__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> > >’)
 1975 |     std::__lg(__last - __first) * 2,

My understanding is that sort is trying to get the difference between the first and last characters (i.e. the length of the container), but it is not defined by Glib::ustring_Iterator.

I can get around the problem by copying into some other container, and the putting it back:

Glib::ustring str("hello");
std::vector<gunichar> vec(str.begin(), str.end());
std::sort(vec.begin(), vec.end());
str.assign(Glib::ustring{vec.begin(), vec.end()});

But this code feels like an ugly hack for a feature that i would expect to see in the library, but perhaps just not looking in the right place. Is this wheel already implemented?


问:
Have multiple Python IDEs, have problems with all of them, can't get any of them to recognise pygame
I am brand new to programming with Python.  I downloaded Spyder first since I was interested in data visualization, (since I am doing a lot of solving math problems) but soon found out I needed Anaconda to run any modules.  I got Anaconda, but am still confused by it.  I wanted to find something that could just run the modules matplotlib and pygame and... another one for drawing things in color whose name escapes me at the moment.

I got VSCode next but again I was confused by how to like package modules for use. I am confused enough trying to learn the basics of coding.  The gap between "beginner's Python tutorial" and "anything I actually want to do" seems mountainous.

I got PyCharm and it again refuses to acknowledge pygame.  I put a copy in the PyCharm directory, the Python director, the C:\Users\AppData\Local directory. I used the python -m pip install commands, I manually copied and moves files, I tried everything.

So I can't test any of my code because I can't get any of these IDEs to run modules and I can't figure out why.

I tried downloading and running multiple different IDEs, googled problems installing pygame, tried adding the folder in Settings\Project Structure


问:
How to force pytest to read options from commandline only, and ignore config files?
Suppose the pytest config file pyproject.toml is in the project directory:

```<code>[tool.pytest.ini_options]
addopts = "-rap --capture=tee-sys"
</code>```

I usually use the options in this file when running the command pytest. And the options are automatically read from the file.

However, sometimes I want to run pytest with -rA only:

```<code>pytest -rA    # it becomes: pytest -rA --capture=tee-sys
</code>```

I have to run it with: pytest -rA --capture=fd to override the option --capture=tee-sys in the config file.

Is there any way to force pytest to read options from commandline only?

What I've tried:

In @Andrei 's answer of this question: Is there an option for pytest to ignore the setup.cfg file?

Use -c /dev/null will prevent pytest from finding the config file. I also find that set -c any-non-exist-path is ok.

However, I'm afraid if -c /dev/null has side effects. In pytest docs (https://docs.pytest.org/en/latest/reference/customize.html#finding-the-rootdir), it says If -c is passed in the command-line, use that as configuration file, and its directory as rootdir. I don't know what will happen if rootdir is set as a non exist dir.

Body:
Suppose the pytest config file pyproject.toml is in the project directory:

[tool.pytest.ini_options]
addopts = "-rap --capture=tee-sys"

I usually use the options in this file when running the command pytest. And the options are automatically read from the file.

However, sometimes I want to run pytest with -rA only:

pytest -rA    # it becomes: pytest -rA --capture=tee-sys

I have to run it with: pytest -rA --capture=fd to override the option --capture=tee-sys in the config file.

Is there any way to force pytest to read options from commandline only?

What I've tried:

In @Andrei 's answer of this question: Is there an option for pytest to ignore the setup.cfg file?

Use -c /dev/null will prevent pytest from finding the config file. I also find that set -c any-non-exist-path is ok.

However, I'm afraid if -c /dev/null has side effects. In pytest docs (https://docs.pytest.org/en/latest/reference/customize.html#finding-the-rootdir), it says If -c is passed in the command-line, use that as configuration file, and its directory as rootdir. I don't know what will happen if rootdir is set as a non exist dir.


问:
how to iterate the input field in jsp page
In my question is, I am working on library management system.

going to add new book one book have many authors, I have 2 athours but field is one in jsp page.

I think on that field I am going to take how many author write a book like(1 or 2).
getting that value I am going to loop the author input field but how to do it i don't know can you help me.
THIS IS MY JSP CODE.....

```<code>        <form method="post">
            <label>Name</label>
            <br/>
            <input type="text" id="name" name="name"><br/>
            <br/>
            <label>how many authors write this book</label>
            <br/>
            <!--in this line i am getting number of author -->
            <input type="text" id="numberofauthor" name="numberofauthor"/>

            <!--then how to iterate the author field-->
            <c:forEach items="${numberofauthor}" var="numberofauthor">
                <input type="text" id="author" name="author"><br/>
                <br/>
            </c:forEach>

            <button class="btn btn-primary">Register</button>
        </form>
</code>```

Body:
In my question is, I am working on library management system.

going to add new book one book have many authors, I have 2 athours but field is one in jsp page.

I think on that field I am going to take how many author write a book like(1 or 2).
getting that value I am going to loop the author input field but how to do it i don't know can you help me.
THIS IS MY JSP CODE.....

        <form method="post">
            Name

            <input type="text" id="name" name="name">

            how many authors write this book

            <input type="text" id="numberofauthor" name="numberofauthor"/>

            <c:forEach items="${numberofauthor}" var="numberofauthor">
                <input type="text" id="author" name="author">

            </c:forEach>

            <button class="btn btn-primary">Register</button>
        </form>