问:
Beautifulsoup doesn't reach a child element
I wrote the following code trying to scrape a google scholar page

```<code>import requests as req
from bs4 import BeautifulSoup as soup

url = r'https://scholar.google.com/scholar?hl=en&q=Sustainability and the measurement of wealth: further reflections'

session = req.Session()
content = session.get(url)
html2bs = soup(content.content, 'lxml')
gs_cit = html2bs.select('#gs_cit')
gs_citd = html2bs.find('div', {'id':"gs_citd"})
gs_cit1 =  html2bs.find('div', {'id':"gs_cit1"})
</code>```

but the gs_citd gives me only this line

 and doesn't reach any level beneath it. Also gs_cit1 returns a None.

As appearing in this image

I want to reach the highlighted class to be able to grab the BibTeX citation.

Can you help, please!

答:
You can parse BibTeX data using beautifulsoup and requests by parsing data-cid attribute which is a unique publication ID. Then you need to temporarily store those IDs to a list, iterate over them, and make a request to every ID to parse BibTeX publication citation.

Example below will work for ~10-20 requests then Google will throw a CAPTCHA or you'll hit the rate limit. The ideal solution is to have a CAPTCHA solving service as well as proxies.

Code and full example in the online IDE:

from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "samsung",
    "hl": "en"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
    "server": "scholar",
    "referer": f"https://scholar.google.com/scholar?hl={params['hl']}&q={params['q']}",
}

def cite_ids() -> list:
    response = requests.get("https://scholar.google.com/scholar", params=params, headers=headers, timeout=10)
    soup = BeautifulSoup(response.text, "lxml")

    # returns a list of publication ID's -> U8bh6Ca9uwQJ
    return [result["data-cid"] for result in soup.select(".gs_or")]

def scrape_cite_results() -> list:

    bibtex_data = []

    for cite_id in cite_ids():
        response = requests.get(f"https://scholar.google.com/scholar?output=cite&q=info:{cite_id}:scholar.google.com", headers=headers, timeout=10)
        soup = BeautifulSoup(response.text, "lxml")

        # selects first matched element which in this case always will be BibTeX
        # if Google will not switch BibTeX position.
        bibtex_data.append(soup.select_one(".gs_citi")["href"])

    # returns a list of BibTex URLs, for example: https://scholar.googleusercontent.com/scholar.bib?q=info:ifd-RAVUVasJ:scholar.google.com/&output=citation&scisdr=CgVDYtsfELLGwov-iJo:AAGBfm0AAAAAYgD4kJr6XdMvDPuv7R8SGODak6AxcJxi&scisig=AAGBfm0AAAAAYgD4kHUUPiUnYgcIY1Vo56muYZpFkG5m&scisf=4&ct=citation&cd=-1&hl=en
    return bibtex_data
```
<hr />
<p>Alternatively, you can achieve the same thing using Google Scholar API from SerpApi without the need to figure out what proxy provider provides good proxies as well as with the CAPTCHA solving service, besides figuring out how to scrape the data from the JavaScript without using browser automation.</p>
<p>Example to integrate:</p>
<pre class="lang-py prettyprint-override"><code>import os
from serpapi import GoogleSearch

def organic_results() -> list:
    params = {
        "api_key": os.getenv("API_KEY"),
        "engine": "google_scholar",
        "q": "samsung",  # search query
        "hl": "en",      # language
    }

    search = GoogleSearch(params)
    results = search.get_dict()

    return [result["result_id"] for result in results["organic_results"]]

def cite_results() -> list:

    citation_results = []

    for citation in organic_results():
        params = {
            "api_key": os.getenv("API_KEY"),
            "engine": "google_scholar_cite",
            "q": citation
        }

        search = GoogleSearch(params)
        results = search.get_dict()

        for result in results["links"]:
            if "BibTeX" in result["name"]:
                citation_results.append(result["link"])

    return citation_results
</code>```

If you would like to parse the data from all available pages, there's a dedicated blog post Scrape historic Google Scholar results using Python at SerpApi which is all about scraping historic 2017-2021 Organic, Cite results to CSV and SQLite using pagination.

Disclaimer, I work for SerpApi.

Body:
I wrote the following code trying to scrape a google scholar page

import requests as req
from bs4 import BeautifulSoup as soup

url = r'https://scholar.google.com/scholar?hl=en&q=Sustainability and the measurement of wealth: further reflections'

session = req.Session()
content = session.get(url)
html2bs = soup(content.content, 'lxml')
gs_cit = html2bs.select('#gs_cit')
gs_citd = html2bs.find('div', {'id':"gs_citd"})
gs_cit1 =  html2bs.find('div', {'id':"gs_cit1"})

but the gs_citd gives me only this line

 and doesn't reach any level beneath it. Also gs_cit1 returns a None.

As appearing in this image

I want to reach the highlighted class to be able to grab the BibTeX citation.

Can you help, please!

Body:
You can parse BibTeX data using beautifulsoup and requests by parsing data-cid attribute which is a unique publication ID. Then you need to temporarily store those IDs to a list, iterate over them, and make a request to every ID to parse BibTeX publication citation.

Example below will work for ~10-20 requests then Google will throw a CAPTCHA or you'll hit the rate limit. The ideal solution is to have a CAPTCHA solving service as well as proxies.

Code and full example in the online IDE:

from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "samsung",
    "hl": "en"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
    "server": "scholar",
    "referer": f"https://scholar.google.com/scholar?hl={params['hl']}&q={params['q']}",
}

def cite_ids() -> list:
    response = requests.get("https://scholar.google.com/scholar", params=params, headers=headers, timeout=10)
    soup = BeautifulSoup(response.text, "lxml")

    # returns a list of publication ID's -> U8bh6Ca9uwQJ
    return [result["data-cid"] for result in soup.select(".gs_or")]

def scrape_cite_results() -> list:

    bibtex_data = []

    for cite_id in cite_ids():
        response = requests.get(f"https://scholar.google.com/scholar?output=cite&q=info:{cite_id}:scholar.google.com", headers=headers, timeout=10)
        soup = BeautifulSoup(response.text, "lxml")

        # selects first matched element which in this case always will be BibTeX
        # if Google will not switch BibTeX position.
        bibtex_data.append(soup.select_one(".gs_citi")["href"])

    # returns a list of BibTex URLs, for example: https://scholar.googleusercontent.com/scholar.bib?q=info:ifd-RAVUVasJ:scholar.google.com/&output=citation&scisdr=CgVDYtsfELLGwov-iJo:AAGBfm0AAAAAYgD4kJr6XdMvDPuv7R8SGODak6AxcJxi&scisig=AAGBfm0AAAAAYgD4kHUUPiUnYgcIY1Vo56muYZpFkG5m&scisf=4&ct=citation&cd=-1&hl=en
    return bibtex_data

Alternatively, you can achieve the same thing using Google Scholar API from SerpApi without the need to figure out what proxy provider provides good proxies as well as with the CAPTCHA solving service, besides figuring out how to scrape the data from the JavaScript without using browser automation.

Example to integrate:

import os
from serpapi import GoogleSearch

def organic_results() -> list:
    params = {
        "api_key": os.getenv("API_KEY"),
        "engine": "google_scholar",
        "q": "samsung",  # search query
        "hl": "en",      # language
    }

    search = GoogleSearch(params)
    results = search.get_dict()

    return [result["result_id"] for result in results["organic_results"]]

def cite_results() -> list:

    citation_results = []

    for citation in organic_results():
        params = {
            "api_key": os.getenv("API_KEY"),
            "engine": "google_scholar_cite",
            "q": citation
        }

        search = GoogleSearch(params)
        results = search.get_dict()

        for result in results["links"]:
            if "BibTeX" in result["name"]:
                citation_results.append(result["link"])

    return citation_results

If you would like to parse the data from all available pages, there's a dedicated blog post Scrape historic Google Scholar results using Python at SerpApi which is all about scraping historic 2017-2021 Organic, Cite results to CSV and SQLite using pagination.

Disclaimer, I work for SerpApi.


来源: stackexchange

问:
Find one character in a string of any number of characters and return True or False
I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.</p>
```<code>def contains_char(any_length: str, single_character: str) -> bool:
    """A way to find one character in a word of any length."""
    assert len(single_character) == 1
    any_length = ""
    single_character = ""
    check_character: bool = False
    i: int = 0
    while i < len(any_length):
        if any_length[i] == single_character[0]:
            check_character is True
        else:
            i += 1
            alternative_char: int = 0
            while check_character is not True and i < len(any_length):
                if any_length[alternative_char] == single_character[0]:
                    check_character == True
                else:
                    alternative_char += 1
    if check_character is not False:
        return False
    else:
        return True
</code>```

答:
you are making another mistake in the start of the function:

any_length = ""

after you change the value of any_length your function will never work

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.

def contains_char(any_length: str, single_character: str) -> bool:
    """A way to find one character in a word of any length."""
    assert len(single_character) == 1
    any_length = ""
    single_character = ""
    check_character: bool = False
    i: int = 0
    while i < len(any_length):
        if any_length[i] == single_character[0]:
            check_character is True
        else:
            i += 1
            alternative_char: int = 0
            while check_character is not True and i < len(any_length):
                if any_length[alternative_char] == single_character[0]:
                    check_character == True
                else:
                    alternative_char += 1
    if check_character is not False:
        return False
    else:
        return True


问:
How to import .xlsx to InDesign
With following code I am trying to import excel file to indesign. I can get data but if in table is more then 3 rows it just continue in line and doesn't create new line.

```<code>var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// make a table from the text
text = text.split('\r');

var table = [];
for (var row = 1; row < text.length; row++) {
    table.push(text[row].split('\t'));
}

// loop through the table and make the cards
for (var i = 0; i < table.length; i++) {

    var title       = table[i][0];
    var description = table[i][1];
    var price       = table[i][2];

    var card = make_card(title, description, price);

    // move card to some place
    card.move([10,10]);
    card.move(undefined, [i*75, 0]);

     if(i > 2){
        card.move([20,10]);
        card.move(undefined, [i*75, 20]);
    }
}

// the function to create and return a card
function make_card(title, description, price) {
    var doc = app.activeDocument;

    var title_frame = doc.textFrames.add();
    title_frame.geometricBounds = [20, 80, 30, 150];
    title_frame.contents = title;

    var description_frame = doc.textFrames.add();
    description_frame.geometricBounds = [30, 80, 80, 150];
    description_frame.contents = description;

    var price_frame = doc.textFrames.add();
    price_frame.geometricBounds = [80, 80, 100, 150];
    price_frame.contents = price;

    var group = doc.groups.add([title_frame, description_frame, price_frame]);
    return group;
}
</code>```

My question is how to write code that card doesn't go out of the document but follow on next line and as well as how to add new page automatically when current document is already full.

I tried do do it with following code in loop if index is heigher than 2 move card down. It move it down but it follow in the same line (out of the document) and I also think there is better way how to write it because if excel has 1000 rors and I have to set up this if index condition for every third element ... code will be one mash

```<code>     if(i > 2){
        card.move([20,10]);
        card.move(undefined, [i*75, 20]);
    }
</code>```

答:
For this case the simplest straightforward implementation could be like this:</p>
```<code>var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// make a table from the text
var rows = text.split('\r');
var table = [];
for (var i = 1; i < rows.length; i++) table.push(rows[i].split('\t'));

// width and height of cards, gaps, properties of the grid
var card_width = 70;
var card_height = 80;
var gap = 5;
var cols = 2;
var rows = 3;
var cards_per_page = cols * rows;

// calculate and add pages
var cards = table.length;
var pages_to_add = Math.ceil(cards / cards_per_page) - 1;
while(pages_to_add--) doc.pages.add();

var page_num = 0; // start page
var start_point = [10,10]; // start point for a first card on a page

main_loop:
for (var i = 0; i < cards; i++) {

    for (var row = 0; row < rows; row++) {

        for (var col = 0; col < cols; col++) {

            // break the loop if there is no more rows in the table
            if (table.length == 0) break main_loop;

            var table_row   = table.shift(); // take a first row from the table
            var title       = table_row[0];
            var description = table_row[1];
            var price       = table_row[2];

            // make a card
            var card = make_card(title, description, price);

            // send the card to the some page and move at some place
            card.move(doc.pages[page_num]);
            card.move(start_point);
            card.move(undefined, [(card_width + gap)*col, (card_height + gap)*row]);
        }
    }

    if (i > (page_num-1) * cards_per_page) page_num++; // increase the page number

}

// the function to create and return a card
function make_card(title, description, price) {
    var doc = app.activeDocument;

    var title_frame = doc.textFrames.add();
    title_frame.geometricBounds = [20, 80, 30, 150];
    title_frame.contents = title;

    var description_frame = doc.textFrames.add();
    description_frame.geometricBounds = [30, 80, 80, 150];
    description_frame.contents = description;

    var price_frame = doc.textFrames.add();
    price_frame.geometricBounds = [80, 80, 100, 150];
    price_frame.contents = price;

    var group = doc.groups.add([title_frame, description_frame, price_frame]);
    return group;
}

</code>```

Title: How to import .xlsx to InDesign

Body:
With following code I am trying to import excel file to indesign. I can get data but if in table is more then 3 rows it just continue in line and doesn't create new line.

var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// make a table from the text
text = text.split('\r');

var table = [];
for (var row = 1; row < text.length; row++) {
    table.push(text[row].split('\t'));
}

// loop through the table and make the cards
for (var i = 0; i
 2){
        card.move([20,10]);
        card.move(undefined, [i*75, 20]);
    }
}

// the function to create and return a card
function make_card(title, description, price) {
    var doc = app.activeDocument;

    var title_frame = doc.textFrames.add();
    title_frame.geometricBounds = [20, 80, 30, 150];
    title_frame.contents = title;

    var description_frame = doc.textFrames.add();
    description_frame.geometricBounds = [30, 80, 80, 150];
    description_frame.contents = description;

    var price_frame = doc.textFrames.add();
    price_frame.geometricBounds = [80, 80, 100, 150];
    price_frame.contents = price;

    var group = doc.groups.add([title_frame, description_frame, price_frame]);
    return group;
}

My question is how to write code that card doesn't go out of the document but follow on next line and as well as how to add new page automatically when current document is already full.

I tried do do it with following code in loop if index is heigher than 2 move card down. It move it down but it follow in the same line (out of the document) and I also think there is better way how to write it because if excel has 1000 rors and I have to set up this if index condition for every third element ... code will be one mash

     if(i > 2){
        card.move([20,10]);
        card.move(undefined, [i*75, 20]);
    }

Body:
For this case the simplest straightforward implementation could be like this:

var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// make a table from the text
var rows = text.split('\r');
var table = [];
for (var i = 1; i < rows.length; i++) table.push(rows[i].split('\t'));

// width and height of cards, gaps, properties of the grid
var card_width = 70;
var card_height = 80;
var gap = 5;
var cols = 2;
var rows = 3;
var cards_per_page = cols * rows;

// calculate and add pages
var cards = table.length;
var pages_to_add = Math.ceil(cards / cards_per_page) - 1;
while(pages_to_add--) doc.pages.add();

var page_num = 0; // start page
var start_point = [10,10]; // start point for a first card on a page

main_loop:
for (var i = 0; i < cards; i++) {

    for (var row = 0; row < rows; row++) {

        for (var col = 0; col < cols; col++) {

            // break the loop if there is no more rows in the table
            if (table.length == 0) break main_loop;

            var table_row   = table.shift(); // take a first row from the table
            var title       = table_row[0];
            var description = table_row[1];
            var price       = table_row[2];

            // make a card
            var card = make_card(title, description, price);

            // send the card to the some page and move at some place
            card.move(doc.pages[page_num]);
            card.move(start_point);
            card.move(undefined, [(card_width + gap)*col, (card_height + gap)*row]);
        }
    }

    if (i > (page_num-1) * cards_per_page) page_num++; // increase the page number

}

// the function to create and return a card
function make_card(title, description, price) {
    var doc = app.activeDocument;

    var title_frame = doc.textFrames.add();
    title_frame.geometricBounds = [20, 80, 30, 150];
    title_frame.contents = title;

    var description_frame = doc.textFrames.add();
    description_frame.geometricBounds = [30, 80, 80, 150];
    description_frame.contents = description;

    var price_frame = doc.textFrames.add();
    price_frame.geometricBounds = [80, 80, 100, 150];
    price_frame.contents = price;

    var group = doc.groups.add([title_frame, description_frame, price_frame]);
    return group;
}


问:
"An attempt was made to load a program with an incorrect format" even when the platforms are the same
I'm calling functions from a 32-bit unmanaged DLL on a 64-bit system. What I get is:

BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

At first, I had my projects set to the Any CPU platform, so I changed them both to x86, but this error is still occurring. That's really the only fix I know for this.

The DLLs aren't corrupt or anything, because I can use them with other programs (that I don't have the source to). I thought that perhaps it wasn't finding a dependency, but I checked and they're all there. Plus, wouldn't it throw a DllNotFoundException in that case?

What else can I do? And before you say "Use a 64-bit unmanaged DLL instead," let me point out that there isn't one. ;)

答: For .net core, make sure Ijwhost.dll is in the output directory, sometimes it isn't being copied and this will cause the error. See https://github.com/dotnet/runtime/issues/38231 and also https://stackoverflow.com/a/58773266/9665729</p>

ContentLicense: CC BY-SA 2.5


问:
Node.js do action when object date match/ends
I am doing site with auctions, which has end_date parameter, and I want to finish that auction when the current date match end_date. So I wonder what is the best solution that I can use for it? I know that I can use "setInterval" to check the database every second, but is this the best solution? Maybe is there a better idea, which monitors dates without checking SQL in intervals?
I also cannot start the process with static dates (end_dates), because if the user makes an offer end_date is changing, so the node has to monitor it "live".</p>

答:
I would do it like so:

Server

When the server starts, it loads the end_date once. If the auction is already finished (and stored as such in db) then do nothing. If it is still running, you probably want to set a setTimeout which will set a flag like ended to in the database for a given auction, at the moment it is finished.

Whenever something on the auction is changed in database from any source, you will have to clear an existing timeout and reset it with the new value.

Client

The client would always receive the end_date value and show either auction finished or still running etc.. So the client correctly can end the auction in the browser if any user would have the tab open. This is backed by some setInterval OR setTimeout calls for correctly showing a countdown, or updating the auctions state or preventing the user from doing stuff etc.

API

Foreach request on a given auction you need to check against the flag set in database. Only allow a certain action for an auction if it is NOT already finished.

Pseudocode on server startup

```<code>// this assumes, that auction.end_date is a javascript date object.
// you may wanna adjust this to your envrionment.
function setAuctionEndedTrigger(auction) {
    // calculates remaining milliseconds till auction will end.
    const remaining_time = auction.end_date.getTime() - Date.now()

    setTimeout(() => {
        // store in the database that the auction has ended!
        // 1 for true and 0 for false.
        sql.execute(`update auctions set ended=1 where id = '${auction.id}'; `)

    }, remaining_time)
}

// Code ecexuted when server starts
// Pseudocode...

// load auctions from db which have not already ended:
const auctions = await sql.execute('select * from auctions where ended is null OR ended = 0;')

// for each running auction set a trigger!
for(let auction of auctions) {
    setAuctionEndedTrigger(auction)
}

</code>```

Body:
I would do it like so:

Server

When the server starts, it loads the end_date once. If the auction is already finished (and stored as such in db) then do nothing. If it is still running, you probably want to set a setTimeout which will set a flag like ended to in the database for a given auction, at the moment it is finished.

Whenever something on the auction is changed in database from any source, you will have to clear an existing timeout and reset it with the new value.

Client

The client would always receive the end_date value and show either auction finished or still running etc.. So the client correctly can end the auction in the browser if any user would have the tab open. This is backed by some setInterval OR setTimeout calls for correctly showing a countdown, or updating the auctions state or preventing the user from doing stuff etc.

API

Foreach request on a given auction you need to check against the flag set in database. Only allow a certain action for an auction if it is NOT already finished.

Pseudocode on server startup

// this assumes, that auction.end_date is a javascript date object.
// you may wanna adjust this to your envrionment.
function setAuctionEndedTrigger(auction) {
    // calculates remaining milliseconds till auction will end.
    const remaining_time = auction.end_date.getTime() - Date.now()

    setTimeout(() => {
        // store in the database that the auction has ended!
        // 1 for true and 0 for false.
        sql.execute(`update auctions set ended=1 where id = '${auction.id}'; `)

    }, remaining_time)
}

// Code ecexuted when server starts
// Pseudocode...

// load auctions from db which have not already ended:
const auctions = await sql.execute('select * from auctions where ended is null OR ended = 0;')

// for each running auction set a trigger!
for(let auction of auctions) {
    setAuctionEndedTrigger(auction)
}


答:
in Does this for you:

```<code>def char_in_word(word, char):
    return char in word
</code>```

However if you don't want to use builtin, use this:

```<code>def char_in(word, char):
    for i in word:
        if i == char:
            return True
    return False
</code>```

Title: Find one character in a string of any number of characters and return True or False

Body:
in Does this for you:

def char_in_word(word, char):
    return char in word

However if you don't want to use builtin, use this:

def char_in(word, char):
    for i in word:
        if i == char:
            return True
    return False


问:
How to add value in the second/child layer of an array
I'm trying to add a value media_type to every child of the array. The code I'm using is:

```<code>while($row = $result->fetch_assoc()) {
  $url = "example";

  $path = $this->get_url($url);

  $popular = ['media_type' => $row["type"],$path];
}

</code>```

Here's an example of the array:

.

This content in the array is from themoviedb API. And is opensource.

答:
Instead of overwrite array every time just use array_push like:

```<code>$popular[] = ['media_type' => $row["type"],$path];
</code>```

Reference:

array_push

Body:
I'm trying to add a value media_type to every child of the array. The code I'm using is:

while($row = $result->fetch_assoc()) {
  $url = "example";

  $path = $this->get_url($url);

  $popular = ['media_type' => $row["type"],$path];
}

Here's an example of the array:

.

This content in the array is from themoviedb API. And is opensource.

Body:
Instead of overwrite array every time just use array_push like:

$popular[] = ['media_type' => $row["type"],$path];

Reference:

array_push


问:
404 Failed to load resource Deploying Flutter Web App to Firebase Hosting
I am trying to deploy my Flutter app to Firebase Hosting. App runs fine with flutter run -d chrome and builds successfully using flutter build web --web-renderer html --release

In my flutter web application I have more then one page. I am using

velocity_x: ^3.3.0

for page routing because this plugin using flutter 2.0 navigation.

The issue that I'm facing when I open my web home is working fine when I go to another page by clicking the next page open but when I refresh that second page that shows 404 not found I do not Understand what I am doing wrong. That same thing is working fine in debug mode but after deploying my flutter web that 404 issue comes.
please help me I tried a lot but did understand what should I do.

my main.dart file

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Vx.setPathUrlStrategy();
  Hive.registerAdapter(MultiAccountAdapter());
  await Hive.openBox<MultiAccount>('accounts');
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

Locale locale;
void getPref() async {
  var res = await SharedPref().getStringVariable("lan");

  if (res != null) {
    if (res != null && res == "ENGLISH") {
      locale = Locale('en', 'US');
    } else if (res != null && res == "DUTCH") {
      locale = Locale('nl', 'NL');
    } else {
      locale = Locale('en', 'US');
    }
  } else {
    locale = ui.window.locale;
    // Get.updateLocale(locale);
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return OverlaySupport(
      child: GetMaterialApp.router(
        debugShowCheckedModeBanner: false,
        translations: LocaleString(),
        locale: locale,
        theme: ThemeData(
          primaryColor: green,
          primaryColorDark: greenDark,
          fontFamily: 'Montserrat-Medium',
          accentColor: Colors.grey,
          cursorColor: greenDark,
          textTheme: TextTheme(
            bodyText1: TextStyle(fontSize: 14.0),
          ),
        ),
        routeInformationParser: VxInformationParser(),
        routerDelegate: VxNavigator(
          routes: VxRoutes.instance.newMethod,
        ),
      ),
    );
  }
}
</code>```

my routing file

```<code>class VxRoutes {
  static VxRoutes instance = VxRoutes();
  Map<Pattern, VxPageBuilder> get newMethod {
    return {
      "/": (_, param) => VxRoutePage(
            child: HomeScreen(
              showSnackbar: param ?? false,
            ),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          ),
  SteplerDetailScreenRoute: (uri, params) {
        var steplerId = uri.queryParameters["steplerId"];
        if (steplerId == null || steplerId == "") {
          return VxRoutePage(
            child: CrashScreen(),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        }
        return VxRoutePage(
          child: SteplerDetailScreen(
            steplerId: int.tryParse(steplerId.toString()),
          ),
          transition: (animation, child) => FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },

   FullPhotoRoute: (uri, params) {
        var url = uri.queryParameters["url"];
        if (url == null || url == "") {
          return VxRoutePage(
            child: CrashScreen(),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        }
        return VxRoutePage(
          child: FullPhoto(
            url: url,
          ),
          transition: (animation, child) => FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },

    };
  }
}
</code>```

my index.html

```<code><!DOCTYPE html>
<html>

<head>

  <base href="/">
  <meta name="google-signin-client_id"abc">
  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="stepler_web">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png" />

  <title>Stepler</title>
  <link rel="manifest" href="manifest.json">
</head>

<body>
  <script
  async
  defer
  crossorigin="anonymous"
  src="https://connect.facebook.net/en_US/sdk.js"
></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
  <script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
      apiKey: "abc",
      authDomain: "abc",
      projectId: "abc",
      storageBucket: "abc",
      messagingSenderId: "abc",
      appId: "abc",
      measurementId: "abc"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('flutter-first-frame', function () {
        navigator.serviceWorker.register('flutter_service_worker.js');
      });
    }
  </script>
  <script src="main.dart.js" type="application/javascript"></script>
</body>

</html>
</code>```

答:
Follow these steps

Go to your firebase console (where your code is hosted)

Edit .htaccess (it doesn't exist please create, sometimes it doesn't show, so enable show hidden files)

Edit/Add given code.

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule . /index.html [L]
</code>```

What do these 4 lines of code?

Ans: It redirects to the index.html page.

Because the flutter web is a single file code-based web application, your URL doesn't exist, like your URL is https://yourdomain.com/my-page but flutter web has only index.html. So we force to redirect that URL to the index.html

Body:
I am trying to deploy my Flutter app to Firebase Hosting. App runs fine with flutter run -d chrome and builds successfully using flutter build web --web-renderer html --release

In my flutter web application I have more then one page. I am using

velocity_x: ^3.3.0

for page routing because this plugin using flutter 2.0 navigation.

The issue that I'm facing when I open my web home is working fine when I go to another page by clicking the next page open but when I refresh that second page that shows 404 not found I do not Understand what I am doing wrong. That same thing is working fine in debug mode but after deploying my flutter web that 404 issue comes.
please help me I tried a lot but did understand what should I do.

my main.dart file

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Vx.setPathUrlStrategy();
  Hive.registerAdapter(MultiAccountAdapter());
  await Hive.openBox<MultiAccount>('accounts');
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

Locale locale;
void getPref() async {
  var res = await SharedPref().getStringVariable("lan");

  if (res != null) {
    if (res != null && res == "ENGLISH") {
      locale = Locale('en', 'US');
    } else if (res != null && res == "DUTCH") {
      locale = Locale('nl', 'NL');
    } else {
      locale = Locale('en', 'US');
    }
  } else {
    locale = ui.window.locale;
    // Get.updateLocale(locale);
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return OverlaySupport(
      child: GetMaterialApp.router(
        debugShowCheckedModeBanner: false,
        translations: LocaleString(),
        locale: locale,
        theme: ThemeData(
          primaryColor: green,
          primaryColorDark: greenDark,
          fontFamily: 'Montserrat-Medium',
          accentColor: Colors.grey,
          cursorColor: greenDark,
          textTheme: TextTheme(
            bodyText1: TextStyle(fontSize: 14.0),
          ),
        ),
        routeInformationParser: VxInformationParser(),
        routerDelegate: VxNavigator(
          routes: VxRoutes.instance.newMethod,
        ),
      ),
    );
  }
}

my routing file

class VxRoutes {
  static VxRoutes instance = VxRoutes();
  Map<Pattern, VxPageBuilder> get newMethod {
    return {
      "/": (_, param) => VxRoutePage(
            child: HomeScreen(
              showSnackbar: param ?? false,
            ),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          ),
  SteplerDetailScreenRoute: (uri, params) {
        var steplerId = uri.queryParameters["steplerId"];
        if (steplerId == null || steplerId == "") {
          return VxRoutePage(
            child: CrashScreen(),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        }
        return VxRoutePage(
          child: SteplerDetailScreen(
            steplerId: int.tryParse(steplerId.toString()),
          ),
          transition: (animation, child) => FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },

   FullPhotoRoute: (uri, params) {
        var url = uri.queryParameters["url"];
        if (url == null || url == "") {
          return VxRoutePage(
            child: CrashScreen(),
            transition: (animation, child) => FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        }
        return VxRoutePage(
          child: FullPhoto(
            url: url,
          ),
          transition: (animation, child) => FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },

    };
  }
}

my index.html

<!DOCTYPE html>

  <base href="/">
  <meta name="google-signin-client_id"abc">
  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="stepler_web">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <link rel="icon" type="image/png" href="favicon.png" />

  <title>Stepler</title>
  <link rel="manifest" href="manifest.json">

Body:
Follow these steps

Go to your firebase console (where your code is hosted)

Edit .htaccess (it doesn't exist please create, sometimes it doesn't show, so enable show hidden files)

Edit/Add given code.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule . /index.html [L]

What do these 4 lines of code?

Ans: It redirects to the index.html page.

Because the flutter web is a single file code-based web application, your URL doesn't exist, like your URL is https://yourdomain.com/my-page but flutter web has only index.html. So we force to redirect that URL to the index.html


问:
What is the difference beween writting logic in Python or plain SQL in Foundry's SQL Transforms?
Foundry's SQL Transforms offers at least 2 ways to write logic code: Python and plain text SQL.

I already noticed some differences:

SQL does not allow incremental computation,

SQL does not allow to use variables, constantes or factorised functions,

SQL does not allow to add parameters to output dataset such "column description".

I'm I wrong on some points and is there other differences (e.g. execution time, consumed ressources) ?

答:
This is a bit of a subjective question, but let me give it a shot. The purpose of both SQL and Python when building transforms is to build a Spark Query, which will execute and return something. That something will be saved in your output dataset.

SQL as the name says is a "structured query language" which generates a query directly, while Python is a traditional programming language which needs the help from a Python library called PySpark to generate queries.

While SQL will generate your query plan and jump straight away to the executors, Python enables you to run code on the driver, which in turn enables you to use the language tooling to help you.

So the main difference is that you can write tooling when using python, and you can't while using sql. The things you list above "allowing incremental computation", "column descriptions", ... etc. Are all things that are possible because Python is a regular programming language, and Palantir foundry has shipped with libraries to do those, but you can also write your own if you want. Unlike SQL which is just the query language, so it has no knowledge of libraries, or about foundry itself. Python also makes the whole code base much easier to maintain, test and expand.

There are too many others to list here, so I invite you to experiment with Python transforms, and read through the docs in https://www.palantir.com/docs/foundry/transforms-python/transforms-python-api/ . Here's some of my favourites: Data Expectations, Unit testing, Capturing re-usable pyspark logic as python libraries, multi output transforms, consuming publicly available open source libraries for data manipulation, accessing the dataset file system for manually parsing when needed...

p.s.: You can also do transforms in other languages, such as java.


问:
How to reset a lookup value to blank and leave other values intact in a Power Apps form
In a simple canvas Power Apps form with several controls, I have a lookup field (data source is a SP List) whose selection I would like to be able to undo (revert to no selection whenever necessary). Currently, if I click the little "x" on the right hand side of the field, the selected value vanishes, but once I click the Save button, the selected value remains in the main SP List grid. I want to be able to reset this specific value from this one control (not values from the entire form).
On the OnSelect property of a button, I have tried Reset(comboBoxLookupValueX) but that is not doing anything.
Any ideas?</p>

答:
If the SP field is not set to required, you could put this into the Button.OnSelect:

Patch(mySPList, myRecord, { myLookUpField: Blank() })

If it still doesn't work, I suggest you test with an open Monitor session in Studio and analyze the response coming from SharePoint, it can yield useful info.

Btw, if the current value in SP for the Lookup field is a given record, the Reset function will only restore this record as selection in your ComboBox as I guess it's set as the default value for the ComboBox via Default or DefaultSelectedItems.


问:
I want to add dot between number
i'm going to convert Epoch time to '%Y-%m-%d %H:%M:%S.%N'
but "converted Epoch time(date -> Epoch time)" is expressed nanoseconds.
if convert "1612483249166", output "53067-07-24 10:26:46.000".

so i want to input "1612483249.166"
how ??????

```<code>ptime1=`echo $(($evtime2+$p))` ###Epoch time
ptime2=`gdate -u -d "1970-01-01 $ptime1 seconds" '+%Y-%m-%dT%H:%M:%S.%3N'`
</code>```

_i'm sorry if the sentence if awkward. thank you

答:
How about using the calculated variable ptime1_?

```<code>ptime1=`echo $(($evtime2+$p))` ###Epoch time
ptime1_=`expr $ptime1 / 1000`
ptime2=`gdate -u -d "1970-01-01 $ptime1_ seconds" '+%Y-%m-%dT%H:%M:%S.%3N'`
</code>```

Title: I want to add dot between number

Body:
i'm going to convert Epoch time to '%Y-%m-%d %H:%M:%S.%N'
but "converted Epoch time(date -> Epoch time)" is expressed nanoseconds.
if convert "1612483249166", output "53067-07-24 10:26:46.000".

so i want to input "1612483249.166"
how ??????

ptime1=`echo $(($evtime2+$p))` ###Epoch time
ptime2=`gdate -u -d "1970-01-01 $ptime1 seconds" '+%Y-%m-%dT%H:%M:%S.%3N'`

_i'm sorry if the sentence if awkward. thank you

Body:
How about using the calculated variable ptime1_?

ptime1=`echo $(($evtime2+$p))` ###Epoch time
ptime1_=`expr $ptime1 / 1000`
ptime2=`gdate -u -d "1970-01-01 $ptime1_ seconds" '+%Y-%m-%dT%H:%M:%S.%3N'`


问:
Is a ternary expression possible for this construct?
I'm not sure if the following statement is possible to write as one line (i.e., ternary form).

```<code>if (A == B)
    FunctionA();
else
    FunctionB();
</code>```

Both FunctionA and FunctionB are type void.

答:
No, use the if statement.

However, by casting the two void functions to Action, this hack is possible:

```<code>(A == B ? (Action)FunctionA : FunctionB).Invoke();
</code>```

This is especially handy when used in expression body => methods because if can't be used there.

Of course: don't do that in serious projects!

Body:
I'm not sure if the following statement is possible to write as one line (i.e., ternary form).

if (A == B)
    FunctionA();
else
    FunctionB();

Both FunctionA and FunctionB are type void.

Body:
No, use the if statement.

However, by casting the two void functions to Action, this hack is possible:

(A == B ? (Action)FunctionA : FunctionB).Invoke();

This is especially handy when used in expression body => methods because if can't be used there.

Of course: don't do that in serious projects!


问:
Using multirow and multicoloum in Table in Overleaf
I am trying to make a table where the first column is multiple columns (2 columns) and also multiple rows (2 rows). The error is on the first column (Aspects). How to make it work?</p>
```<code>\begin{table}[htb]
\centering
\begin{tabular}{l|c|c|c|c|c}
\hline

\multirow{2}{c}{}\multicolumn{2}{c|}{Aspects} & \multicolumn{4}{c}{Methods} \\
\cline{3-6}
 & & Binomial Test & Tangram & Stereoscope & BayesPrism\\
\hline
\multirow{10}{*}{\begin{turn}{270}Total Number\end{turn}} & Cell Type 0 & 3381 & 25  & 1200 &  331    \\
                               & Cell Type 1 & 1903 & 40  & 3360 &  3468    \\
                               & Cell Type 2 & 3466 & 0   & 1357 &  2729    \\
                               & Cell Type 3 & 3468 & 40  & 1711 &  412   \\
                               & Cell Type 4 & 3406 & 64  & 1996 &  3458   \\
                               & Cell Type 5 & 2934 & 31  & 1512 &  1772    \\
                               & Cell Type 6 & 494  & 55  & 3463 &  3468   \\
                               & Cell Type 7 & 3159 & 30  & 2367 &  3467    \\
                               & Cell Type 8 & 3454 & 53  & 3275 &  3456    \\
                               & Cell Type 9 & 3281 & 18  & 1320 &  1451    \\
            \hline
\multicolumn{2}{c|}{Total Variables}     & 28,946 & 356 & 21,443 & 23,962\\
\multicolumn{2}{c|}{Residual Error Mean} & 3.04   & 3.50 & 2.92  & 2.93 \\
\hline
\end{tabular}
\caption{Total Number of Each Cell Types for The Model \ref{regression}}
\label{total_cell}
\end{table}
</code>```

答:
This line is completely messed up:

```<code>\multirow{2}{c}{}\multicolumn{2}{c|}{Aspects}
</code>```

The \multirow has the wrong syntax, and moreover, \multirow must be inside \multicolumn if you want to combine them (see the multirow manual).

Also I added a \multicolumn{1}{l}{} to get rid of the vertical bar in the 2x2 cell.

```<code>\documentclass{article}
\usepackage{multirow}
\usepackage{rotating}

\begin{document}

\begin{table}[htb]
\centering
\begin{tabular}{l|c|c|c|c|c}
\hline

\multicolumn{2}{c|}{\multirow{2}{*}{Aspects}} & \multicolumn{4}{c}{Methods} \\
\cline{3-6}
\multicolumn{1}{l}{} & & Binomial Test & Tangram & Stereoscope & BayesPrism\\
\hline
\multirow{10}{*}{\begin{turn}{270}Total Number\end{turn}} & Cell Type 0 & 3381 & 25  & 1200 &  331    \\
                               & Cell Type 1 & 1903 & 40  & 3360 &  3468    \\
                               & Cell Type 2 & 3466 & 0   & 1357 &  2729    \\
                               & Cell Type 3 & 3468 & 40  & 1711 &  412   \\
                               & Cell Type 4 & 3406 & 64  & 1996 &  3458   \\
                               & Cell Type 5 & 2934 & 31  & 1512 &  1772    \\
                               & Cell Type 6 & 494  & 55  & 3463 &  3468   \\
                               & Cell Type 7 & 3159 & 30  & 2367 &  3467    \\
                               & Cell Type 8 & 3454 & 53  & 3275 &  3456    \\
                               & Cell Type 9 & 3281 & 18  & 1320 &  1451    \\
            \hline
\multicolumn{2}{c|}{Total Variables}     & 28,946 & 356 & 21,443 & 23,962\\
\multicolumn{2}{c|}{Residual Error Mean} & 3.04   & 3.50 & 2.92  & 2.93 \\
\hline
\end{tabular}
\caption{Total Number of Each Cell Types for The Model \ref{regression}}
\label{total_cell}
\end{table}

\end{document}
</code>```

Body:
I am trying to make a table where the first column is multiple columns (2 columns) and also multiple rows (2 rows). The error is on the first column (Aspects). How to make it work?

\begin{table}[htb]
\centering
\begin{tabular}{l|c|c|c|c|c}
\hline

\multirow{2}{c}{}\multicolumn{2}{c|}{Aspects} & \multicolumn{4}{c}{Methods} \\
\cline{3-6}
 & & Binomial Test & Tangram & Stereoscope & BayesPrism\\
\hline
\multirow{10}{*}{\begin{turn}{270}Total Number\end{turn}} & Cell Type 0 & 3381 & 25  & 1200 &  331    \\
                               & Cell Type 1 & 1903 & 40  & 3360 &  3468    \\
                               & Cell Type 2 & 3466 & 0   & 1357 &  2729    \\
                               & Cell Type 3 & 3468 & 40  & 1711 &  412   \\
                               & Cell Type 4 & 3406 & 64  & 1996 &  3458   \\
                               & Cell Type 5 & 2934 & 31  & 1512 &  1772    \\
                               & Cell Type 6 & 494  & 55  & 3463 &  3468   \\
                               & Cell Type 7 & 3159 & 30  & 2367 &  3467    \\
                               & Cell Type 8 & 3454 & 53  & 3275 &  3456    \\
                               & Cell Type 9 & 3281 & 18  & 1320 &  1451    \\
            \hline
\multicolumn{2}{c|}{Total Variables}     & 28,946 & 356 & 21,443 & 23,962\\
\multicolumn{2}{c|}{Residual Error Mean} & 3.04   & 3.50 & 2.92  & 2.93 \\
\hline
\end{tabular}
\caption{Total Number of Each Cell Types for The Model \ref{regression}}
\label{total_cell}
\end{table}

Body:
This line is completely messed up:

\multirow{2}{c}{}\multicolumn{2}{c|}{Aspects}

The \multirow has the wrong syntax, and moreover, \multirow must be inside \multicolumn if you want to combine them (see the multirow manual).

Also I added a \multicolumn{1}{l}{} to get rid of the vertical bar in the 2x2 cell.

\documentclass{article}
\usepackage{multirow}
\usepackage{rotating}

\begin{document}

\begin{table}[htb]
\centering
\begin{tabular}{l|c|c|c|c|c}
\hline

\multicolumn{2}{c|}{\multirow{2}{*}{Aspects}} & \multicolumn{4}{c}{Methods} \\
\cline{3-6}
\multicolumn{1}{l}{} & & Binomial Test & Tangram & Stereoscope & BayesPrism\\
\hline
\multirow{10}{*}{\begin{turn}{270}Total Number\end{turn}} & Cell Type 0 & 3381 & 25  & 1200 &  331    \\
                               & Cell Type 1 & 1903 & 40  & 3360 &  3468    \\
                               & Cell Type 2 & 3466 & 0   & 1357 &  2729    \\
                               & Cell Type 3 & 3468 & 40  & 1711 &  412   \\
                               & Cell Type 4 & 3406 & 64  & 1996 &  3458   \\
                               & Cell Type 5 & 2934 & 31  & 1512 &  1772    \\
                               & Cell Type 6 & 494  & 55  & 3463 &  3468   \\
                               & Cell Type 7 & 3159 & 30  & 2367 &  3467    \\
                               & Cell Type 8 & 3454 & 53  & 3275 &  3456    \\
                               & Cell Type 9 & 3281 & 18  & 1320 &  1451    \\
            \hline
\multicolumn{2}{c|}{Total Variables}     & 28,946 & 356 & 21,443 & 23,962\\
\multicolumn{2}{c|}{Residual Error Mean} & 3.04   & 3.50 & 2.92  & 2.93 \\
\hline
\end{tabular}
\caption{Total Number of Each Cell Types for The Model \ref{regression}}
\label{total_cell}
\end{table}

\end{document}


问:
How to add price on an item from a binded ComboBox?
I'm trying to learn the difference between Hashtable and HashMap and I'm trying to add specific prices to these items here. The goal is to print the price of the item selected from comboItem into txtPrice.

```<code>        String[] items = {"Select Item","Betta Fish","Snail","Supplies","Food"};
        comboGroup = new JComboBox<String>(items);
        comboGroup.addActionListener(this);
        comboGroup.setBounds(130,35,150,40);

        comboItem = new JComboBox<>();
        comboItem.setPrototypeDisplayValue("XXXXXXXXXXX");
        comboItem.setBounds(130,85,150,40);

        String[] subItems1 = {"Select Betta","Plakat","Halfmoon","Double Tail","Crown Tail"};
        subItems.put(items[1], subItems1);

        String[] subItems2 = {"Select Snail","Pond Snail","Ramshorn","Apple Snail","Assassin Snail"};
        subItems.put(items[2], subItems2);

        String[] subItems3 = {"Select Supply","Small Fine Net","Large Fine Net","Flaring Mirror","Aquarium Hose (1meter)"};
        subItems.put(items[3], subItems3);

        String[] subItems4 = {"Select Food","Daphnia","Tubifex","Mosquito Larvae","Optimum Pellets"};
        subItems.put(items[4], subItems4);
        comboGroup.setSelectedIndex(1);

        //TextFields <- this is the attempt to add price to subItems value but commented out
        /*int[] items1price = {0,150,350,200,200};
        subItems.put(items[1], items1price);
        int[] items2price = {0,15,25,80,120};
        subItems.put(items[2], items2price);
        int[] items3price = {0,50,80,25,15};
        subItems.put(items[3], items3price);
        int[] items4price = {0,50,100,50,50};
        subItems.put(items[4], items4price);
        comboGroup.setSelectedIndex(1);
        */
        txtPrice = new JTextField();
        txtPrice.setBounds(130,135,150,40);
</code>```

So far with my understanding from HashMap applying it to CLi and not in GUI, If I try HashMap<String,Integer> I can only print it altogether in a single line.

eg.

```<code>HashMap<String,Integer> item = new HashMap<String,Integer>();
item.put("Plakat",50);

CLi Prints:
Plakat=50
</code>```

What I want is to print Plakat from selected comboItem then print 50 to txtPrice but I don't know how to do that.

The whole code is here: https://github.com/kontext66/GuwiPos
GUI and Main.

Additional note: I am a beginner and I'm trying to understand Layout Manager for now, so the code here is a bit messy and literal.

答:
Below is an example using JComboBox and HashMap to get the corresponding "prices" to specific items in the combo box. I would suggest going through the tutorial on How to Use Various Layout Managers and choose the ones that suit you best. As for the difference between HashMap and HashTable, please have a look at this answer. The main difference is that HashTable is synchronized, whereas HashMap is not, and since synchronization is not an issue for you, I'd suggest HashMap. Also, another option would be to add instances of a custom object to a JComboBox, as described here. Thus, there would be no need to use HashMap.

```<code>import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class App {
    Map<String, String> map;
    JTextField tf;

    public App() {
        map = new HashMap<String, String>();
        map.put("Plakat", "50");
        map.put("Halfmoon", "25");
        map.put("Double Tail", "80");
    }

    private void addComponentsToPane(Container pane) {
        String[] items = { "Select Item", "Plakat", "Halfmoon", "Double Tail" };
        JComboBox<String> comboBox = new JComboBox<String>(items);

        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String item = (String) event.getItem();
                    System.out.println(item);
                    tf.setText(map.get(item));
                }
            }
        });

        tf = new JTextField();
        JPanel p = new JPanel();
        pane.add(comboBox, BorderLayout.NORTH);
        pane.add(tf, BorderLayout.SOUTH);
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        // frame.setSize(640, 480);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().createAndShowGUI();
            }
        });
    }

}
</code>```

Update

Below is the implementation of the second approach described earlier, where a custom object is used for adding items to a JComboBox, and hence, there is no need to use a HashMap.

P.S. I should also add that if the user shouldn't be allowed to edit the "price" in the text field, then you should use tf.setEditable(false);, or even use a JLabel instead.

```<code>import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class App {
    JTextField tf;

    class ComboItem {
        private String key;
        private String value;

        public ComboItem(String key, String value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public String toString() {
            return key;
        }

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }
    }

    private void addComponentsToPane(Container pane) {
        JComboBox<ComboItem> comboBox = new JComboBox<ComboItem>();
        comboBox.addItem(new ComboItem("Select Item", ""));
        comboBox.addItem(new ComboItem("Plakat", "50"));
        comboBox.addItem(new ComboItem("Halfmoon", "25"));
        comboBox.addItem(new ComboItem("Double Tail", "80"));

        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    Object item = comboBox.getSelectedItem();
                    String value = ((ComboItem) item).getValue();
                    tf.setText(value);
                }
            }
        });

        tf = new JTextField();
        JPanel p = new JPanel();
        pane.add(comboBox, BorderLayout.NORTH);
        pane.add(tf, BorderLayout.SOUTH);
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().createAndShowGUI();
            }
        });
    }
}
</code>```

Update 2

To convert the string from the text field into double, you can use Double.parseDouble(String), as shown below (again, make sure to use tf.setEditable(false);, so that the value cannot be modified by the user).

```<code>double price = 0;
if (tf.getText() != null && !tf.getText().trim().isEmpty())
    price = Double.parseDouble(tf.getText());
System.out.println(price);
</code>```

Body:
I'm trying to learn the difference between Hashtable and HashMap and I'm trying to add specific prices to these items here. The goal is to print the price of the item selected from comboItem into txtPrice.

        String[] items = {"Select Item","Betta Fish","Snail","Supplies","Food"};
        comboGroup = new JComboBox<String>(items);
        comboGroup.addActionListener(this);
        comboGroup.setBounds(130,35,150,40);

        comboItem = new JComboBox<>();
        comboItem.setPrototypeDisplayValue("XXXXXXXXXXX");
        comboItem.setBounds(130,85,150,40);

        String[] subItems1 = {"Select Betta","Plakat","Halfmoon","Double Tail","Crown Tail"};
        subItems.put(items[1], subItems1);

        String[] subItems2 = {"Select Snail","Pond Snail","Ramshorn","Apple Snail","Assassin Snail"};
        subItems.put(items[2], subItems2);

        String[] subItems3 = {"Select Supply","Small Fine Net","Large Fine Net","Flaring Mirror","Aquarium Hose (1meter)"};
        subItems.put(items[3], subItems3);

        String[] subItems4 = {"Select Food","Daphnia","Tubifex","Mosquito Larvae","Optimum Pellets"};
        subItems.put(items[4], subItems4);
        comboGroup.setSelectedIndex(1);

        //TextFields <- this is the attempt to add price to subItems value but commented out
        /*int[] items1price = {0,150,350,200,200};
        subItems.put(items[1], items1price);
        int[] items2price = {0,15,25,80,120};
        subItems.put(items[2], items2price);
        int[] items3price = {0,50,80,25,15};
        subItems.put(items[3], items3price);
        int[] items4price = {0,50,100,50,50};
        subItems.put(items[4], items4price);
        comboGroup.setSelectedIndex(1);
        */
        txtPrice = new JTextField();
        txtPrice.setBounds(130,135,150,40);

So far with my understanding from HashMap applying it to CLi and not in GUI, If I try HashMap<String,Integer> I can only print it altogether in a single line.

eg.

HashMap<String,Integer> item = new HashMap<String,Integer>();
item.put("Plakat",50);

CLi Prints:
Plakat=50

What I want is to print Plakat from selected comboItem then print 50 to txtPrice but I don't know how to do that.

The whole code is here: https://github.com/kontext66/GuwiPos
GUI and Main.

Additional note: I am a beginner and I'm trying to understand Layout Manager for now, so the code here is a bit messy and literal.

Body:
Below is an example using JComboBox and HashMap to get the corresponding "prices" to specific items in the combo box. I would suggest going through the tutorial on How to Use Various Layout Managers and choose the ones that suit you best. As for the difference between HashMap and HashTable, please have a look at this answer. The main difference is that HashTable is synchronized, whereas HashMap is not, and since synchronization is not an issue for you, I'd suggest HashMap. Also, another option would be to add instances of a custom object to a JComboBox, as described here. Thus, there would be no need to use HashMap.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class App {
    Map<String, String> map;
    JTextField tf;

    public App() {
        map = new HashMap<String, String>();
        map.put("Plakat", "50");
        map.put("Halfmoon", "25");
        map.put("Double Tail", "80");
    }

    private void addComponentsToPane(Container pane) {
        String[] items = { "Select Item", "Plakat", "Halfmoon", "Double Tail" };
        JComboBox<String> comboBox = new JComboBox<String>(items);

        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String item = (String) event.getItem();
                    System.out.println(item);
                    tf.setText(map.get(item));
                }
            }
        });

        tf = new JTextField();
        JPanel p = new JPanel();
        pane.add(comboBox, BorderLayout.NORTH);
        pane.add(tf, BorderLayout.SOUTH);
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        // frame.setSize(640, 480);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().createAndShowGUI();
            }
        });
    }

}

Update

Below is the implementation of the second approach described earlier, where a custom object is used for adding items to a JComboBox, and hence, there is no need to use a HashMap.

P.S. I should also add that if the user shouldn't be allowed to edit the "price" in the text field, then you should use tf.setEditable(false);, or even use a JLabel instead.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class App {
    JTextField tf;

    class ComboItem {
        private String key;
        private String value;

        public ComboItem(String key, String value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public String toString() {
            return key;
        }

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }
    }

    private void addComponentsToPane(Container pane) {
        JComboBox<ComboItem> comboBox = new JComboBox<ComboItem>();
        comboBox.addItem(new ComboItem("Select Item", ""));
        comboBox.addItem(new ComboItem("Plakat", "50"));
        comboBox.addItem(new ComboItem("Halfmoon", "25"));
        comboBox.addItem(new ComboItem("Double Tail", "80"));

        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    Object item = comboBox.getSelectedItem();
                    String value = ((ComboItem) item).getValue();
                    tf.setText(value);
                }
            }
        });

        tf = new JTextField();
        JPanel p = new JPanel();
        pane.add(comboBox, BorderLayout.NORTH);
        pane.add(tf, BorderLayout.SOUTH);
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new App().createAndShowGUI();
            }
        });
    }
}

Update 2

To convert the string from the text field into double, you can use Double.parseDouble(String), as shown below (again, make sure to use tf.setEditable(false);, so that the value cannot be modified by the user).

double price = 0;
if (tf.getText() != null && !tf.getText().trim().isEmpty())
    price = Double.parseDouble(tf.getText());
System.out.println(price);


问:
Closest subsequent index for a specified value
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)
```
<p>I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.</p>
<p>For instance,</p>
<pre class="lang-r prettyprint-override"><code>f(int, 0)
# [1] 2 1 0 2 1 0 0 NA
</code>```

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA
```
<p>This should also work for character vectors:</p>
<pre class="lang-r prettyprint-override"><code>char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0
</code>```

答:
Look for the match from nth position to the end of the vector, then get the 1st match:</p>
```<code>f <- function(v, x){
  sapply(seq_along(v), function(i){
    which(v[ i:length(v) ] == x)[ 1 ] - 1
  })
}

f(int, 0)
# [1]  2  1  0  2  1  0  0 NA
f(int, 1)
# [1]  0  0 NA NA NA NA NA NA
f(int, 2)
# [1] 4 3 2 1 0 2 1 0
f(int, 3)
# [1] NA NA NA NA NA NA NA NA

f(char, "A")
# [1] 0 2 1 0 0
</code>```

Body:
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)

I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.

For instance,

f(int, 0)
# [1] 2 1 0 2 1 0 0 NA

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA

This should also work for character vectors:

char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0

Body:
Look for the match from nth position to the end of the vector, then get the 1st match:

f <- function(v, x){
  sapply(seq_along(v), function(i){
    which(v[ i:length(v) ] == x)[ 1 ] - 1
  })
}

f(int, 0)
# [1]  2  1  0  2  1  0  0 NA
f(int, 1)
# [1]  0  0 NA NA NA NA NA NA
f(int, 2)
# [1] 4 3 2 1 0 2 1 0
f(int, 3)
# [1] NA NA NA NA NA NA NA NA

f(char, "A")
# [1] 0 2 1 0 0


问:
Invisible Character Unicode
Does anyone know if there is any invisible character other than the space? like a website using (Example: This Invisible Character). Is it possible to programmatically add some such characters that are not shown by any editor, i'm trying by unicode but when ever i paste it so it takes same unicode but don't copy it as an invisible character?</p>

答:
Yes, there are other invisible characters. Like for example U+200b.
This might be even invisible in your Code Editor.

For example VSCode however has a feature now to highlight invisible unicode characters.

To type a chracter like this on windows for example:

To insert a Unicode character, type the character code, press ALT, and then press X. For example, to type a dollar symbol ($), type 0024, press ALT, and then press X. For more Unicode character codes, see Unicode character code charts by script.

Source: Microsoft

The Website you linked used a character that's invisible but adds some "whitespace". The character I choose as an example is invisible but doesn't cause visible space between other characters.

This Website offers a list of many different types of invisible Unicode characters for reference.

Title: Invisible Character Unicode


问:
How to have class-transform converting properly the _id of a mongoDb class?
I've the following mongoDb class:

```<code>@Schema()
export class Poker {
  @Transform(({ value }) => value.toString())
  _id: ObjectId;

  @Prop()
  title: string;

  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
  @Type(() => User)
  author: User;
}
</code>```

which I return, transformed by class-transform in a NestJs server.

It get transformed by an interceptor:

```<code>  @Get()
  @UseGuards(JwtAuthenticationGuard)
  @UseInterceptors(MongooseClassSerializerInterceptor(Poker))
  async findAll(@Req() req: RequestWithUser) {
    return this.pokersService.findAll(req.user);
  }
</code>```

I'm not the author of the interceptor, but here is how it is implemented:

```<code>function MongooseClassSerializerInterceptor(
  classToIntercept: Type,
): typeof ClassSerializerInterceptor {
  return class Interceptor extends ClassSerializerInterceptor {
    private changePlainObjectToClass(document: PlainLiteralObject) {
      if (!(document instanceof Document)) {
        return document;
      }

      return plainToClass(classToIntercept, document.toJSON());
    }

    private prepareResponse(
      response: PlainLiteralObject | PlainLiteralObject[],
    ) {
      if (Array.isArray(response)) {
        return response.map(this.changePlainObjectToClass);
      }

      return this.changePlainObjectToClass(response);
    }

    serialize(
      response: PlainLiteralObject | PlainLiteralObject[],
      options: ClassTransformOptions,
    ) {
      return super.serialize(this.prepareResponse(response), options);
    }
  };
}

export default MongooseClassSerializerInterceptor;
</code>```

The problem I'm having, is that when I do a console.log of the return of my controller, I get this:

```<code>[
  {
    _id: new ObjectId("61f030a9527e209d8cad179b"),
    author: {
      _id: new ObjectId("61f03085527e209d8cad1793"),
      password: '--------------------------',
      name: '----------',
      email: '-------------',
      __v: 0
    },
    title: 'Wonderfull first poker2',
    __v: 0
  }
]
</code>```

but I get this returned:

```<code>[
    {
        "_id": "61f5149643092051ba048c6e",
        "author": {
            "_id": "61f5149643092051ba048c6f",
            "name": "----------",
            "email": "-------------",
            "__v": 0
        },
        "title": "Wonderfull first poker2",
        "__v": 0
    }
]
</code>```

If you check the id, it's not at all the same. Then the client will ask some data for this ID and receive nothing.

Any idea what am I missing?

Also, everytime I make a Get request, I receive a different value back.

答:
Try using this for _id:

```<code>@Transform(params => params.obj._id)
</code>```

Or this for a more general case:

```<code>@Transform(({ key, obj }) => obj[key])
</code>```

Stuck with the same problem, solved it this way. params.obj is an original object. Unfortunately, I don't know, why class-transformer doesn't define _id correctly by default.

Body:
I've the following mongoDb class:

@Schema()
export class Poker {
  @Transform(({ value }) => value.toString())
  _id: ObjectId;

  @Prop()
  title: string;

  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
  @Type(() => User)
  author: User;
}

which I return, transformed by class-transform in a NestJs server.

It get transformed by an interceptor:

  @Get()
  @UseGuards(JwtAuthenticationGuard)
  @UseInterceptors(MongooseClassSerializerInterceptor(Poker))
  async findAll(@Req() req: RequestWithUser) {
    return this.pokersService.findAll(req.user);
  }

I'm not the author of the interceptor, but here is how it is implemented:

function MongooseClassSerializerInterceptor(
  classToIntercept: Type,
): typeof ClassSerializerInterceptor {
  return class Interceptor extends ClassSerializerInterceptor {
    private changePlainObjectToClass(document: PlainLiteralObject) {
      if (!(document instanceof Document)) {
        return document;
      }

      return plainToClass(classToIntercept, document.toJSON());
    }

    private prepareResponse(
      response: PlainLiteralObject | PlainLiteralObject[],
    ) {
      if (Array.isArray(response)) {
        return response.map(this.changePlainObjectToClass);
      }

      return this.changePlainObjectToClass(response);
    }

    serialize(
      response: PlainLiteralObject | PlainLiteralObject[],
      options: ClassTransformOptions,
    ) {
      return super.serialize(this.prepareResponse(response), options);
    }
  };
}

export default MongooseClassSerializerInterceptor;

The problem I'm having, is that when I do a console.log of the return of my controller, I get this:

[
  {
    _id: new ObjectId("61f030a9527e209d8cad179b"),
    author: {
      _id: new ObjectId("61f03085527e209d8cad1793"),
      password: '--------------------------',
      name: '----------',
      email: '-------------',
      __v: 0
    },
    title: 'Wonderfull first poker2',
    __v: 0
  }
]

but I get this returned:

[
    {
        "_id": "61f5149643092051ba048c6e",
        "author": {
            "_id": "61f5149643092051ba048c6f",
            "name": "----------",
            "email": "-------------",
            "__v": 0
        },
        "title": "Wonderfull first poker2",
        "__v": 0
    }
]

If you check the id, it's not at all the same. Then the client will ask some data for this ID and receive nothing.

Any idea what am I missing?

Also, everytime I make a Get request, I receive a different value back.

Body:
Try using this for _id:

@Transform(params => params.obj._id)

Or this for a more general case:

@Transform(({ key, obj }) => obj[key])

Stuck with the same problem, solved it this way. params.obj is an original object. Unfortunately, I don't know, why class-transformer doesn't define _id correctly by default.


问:
Where to place ||
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!</p>

```<code>if ([[file pathExtension] isEqualToString:@"caf"])
</code>```

答:
|| means 'or' in Objective c. So this if (a == 1 || a == 2) means if a is equal to 1 OR a is equal to 2. So:

==  equal

&& and

||    or

ContentLicense: CC BY-SA 3.0

Title: Where to place ||

Body:
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!

if ([[file pathExtension] isEqualToString:@"caf"])


问:
Problem in Android AudioStream class in new API 32
The AudioStream class in API 32 is having a problem with the join method, what does it do together with the AudioGroup class, I just opened a call for Google but the same ones didn't help me, someone has the same problem or I've gone through something similar, I'm not going to to first native class do google be with problem?

enter image description here

答:
all SIP-related classes, incl. AudioGroup and AudioStream, were deprecated in API31, so you just can't rely on these on API31+

This class was deprecated in API level 31.
SipManager and associated classes are no longer supported and should not be used as the basis of future VOIP apps.

edit after some inspection: built-in AudioGroup class doesn't have add or remove methods. Inspect your imports


问:
how to solve element overlap problem in flutter
I have a row of 3 children and I am sending one of them from another page. I want it to be side by side with the text, but it stays above the text. How can I fix this problem?

Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            textComponent ?? Container(),
                            Flexible(
                              fit: FlexFit.loose,
                              child: SizedBox(
                                width: 140,
                                child: Row(
                                  children: [
                                    Text(
                                      state.value == initialValue
                                          ? initialValueLabel ?? ""
                                          : valueLabel ?? "",
                                      style: TextStyle(
                                        fontWeight: FontWeight.normal,
                                        fontSize: 16,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Icon(Icons.arrow_drop_down)
                          ],
                        ),```
</div>
</div>
</p>
<p><img src="https://i.stack.imgur.com/8XTXQ.png" alt="enter image description here" /></p>
```textComponent: girisHesapTipi != ""
                      ? ClipOval(
                          child: Container(
                          //todo renk dinamik değişecek
                          color: Colors.grey,
                          padding: EdgeInsets.symmetric(horizontal: 5),
                          child: Text(
                            girisHesapTipi,
                            style: TextStyle(color: Colors.black, fontSize: 20),
                          ),
                        ))
                      : null,

```

答:
try this:

```<code>Row(
 mainAxisAlignment: MainAxisAlignment.start,
 children: [
    textComponent ?? Container(),
    const SizedBox(width: 10),
    Flexible(
      Text(
        state.value == initialValue
         ? initialValueLabel ?? ""
         : valueLabel ?? "",
        style: TextStyle(
          fontWeight: FontWeight.normal,
          fontSize: 16,
        ),
       overflow: TextOverflow.ellipsis,
      ),
    ),
    Icon(Icons.arrow_drop_down),
  ]
)
</code>```

where textComponent is:

```<code>girisHesapTipi.isNotEmpty
  ? Container(
      //todo renk dinamik değişecek
      decoration: BoxDecoration(
       color: Colors.grey,
       borderRadius: BorderRadius.circular(100.0),
      ),
      padding: EdgeInsets.symmetric(horizontal: 5),
      child: Align(
       alignment: Alignment.center,
       child: Text(
        girisHesapTipi,
        style: TextStyle(
         color: Colors.black, fontSize: 20
        ),
       ),
      ),
     ),
   : null,
</code>```

Body:
I have a row of 3 children and I am sending one of them from another page. I want it to be side by side with the text, but it stays above the text. How can I fix this problem?

Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            textComponent ?? Container(),
                            Flexible(
                              fit: FlexFit.loose,
                              child: SizedBox(
                                width: 140,
                                child: Row(
                                  children: [
                                    Text(
                                      state.value == initialValue
                                          ? initialValueLabel ?? ""
                                          : valueLabel ?? "",
                                      style: TextStyle(
                                        fontWeight: FontWeight.normal,
                                        fontSize: 16,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Icon(Icons.arrow_drop_down)
                          ],
                        ),

textComponent: girisHesapTipi != ""
                      ? ClipOval(
                          child: Container(
                          //todo renk dinamik değişecek
                          color: Colors.grey,
                          padding: EdgeInsets.symmetric(horizontal: 5),
                          child: Text(
                            girisHesapTipi,
                            style: TextStyle(color: Colors.black, fontSize: 20),
                          ),
                        ))
                      : null,

Body:
try this:

Row(
 mainAxisAlignment: MainAxisAlignment.start,
 children: [
    textComponent ?? Container(),
    const SizedBox(width: 10),
    Flexible(
      Text(
        state.value == initialValue
         ? initialValueLabel ?? ""
         : valueLabel ?? "",
        style: TextStyle(
          fontWeight: FontWeight.normal,
          fontSize: 16,
        ),
       overflow: TextOverflow.ellipsis,
      ),
    ),
    Icon(Icons.arrow_drop_down),
  ]
)

where textComponent is:

girisHesapTipi.isNotEmpty
  ? Container(
      //todo renk dinamik değişecek
      decoration: BoxDecoration(
       color: Colors.grey,
       borderRadius: BorderRadius.circular(100.0),
      ),
      padding: EdgeInsets.symmetric(horizontal: 5),
      child: Align(
       alignment: Alignment.center,
       child: Text(
        girisHesapTipi,
        style: TextStyle(
         color: Colors.black, fontSize: 20
        ),
       ),
      ),
     ),
   : null,


问:
kotlin multiplaform using HashMap in javascript
I'm using kotlin multiplatform to export a library to ios, android and possibly js.

the kotlin class is like this:

```<code>@JsExport
class CoreClient (private val httpClient: HTTPClient, private val socket: SocketClient, eventDelegate:EventEngineDelegate? = null): SocketClientDelegate {
  ...
   fun sessionLogin(data: Map<String, Any>, callback: ((Exception?, String?) -> Unit)) {
        Logger.i { "CoreClient - sessionLogin"}

        val body = data["body"] as Map<String, Any?>
        // create an event for connecting the socket, store the token for the login to happen after connected
        val event = SocketConnectEvent(
            body,
            null,
            null,
            null,
            null,
            "SocketConnect"
        )
        invokeEngine(event, eventCallback(callback))
    }
    ...

}
</code>```

that's how I'm trying to use it:

```<code>const lib = require("../build/js/packages/clientsdk-core-js-legacy");

const kotlin = require("../build/js/packages_imported/kotlin/1.6.10/kotlin");
const HashMap = kotlin.kotlin.collections.HashMap
HashMap.prototype.get = HashMap.prototype.get_11rb$
HashMap.prototype.put = HashMap.prototype.put_xwzc9p$

const {core, middleware, api } = lib.com.nexmo.clientsdk
const {CoreClient} = core
const {VoiceClient, MediaClient} = api
const coreClient = new CoreClient(HTTPClient(), SocketClient())

const mediaClient = new MediaClient()
const client = new VoiceClient(coreClient, mediaClient)

loginEventBody = new HashMap()
loginEventBody.put('token', 'TOKEN')
loginEventBody.put('device_id', 'js1')
loginEventBody.put('device_type', 'js')
loginEventBody.put('SDK_version', 'foo')

const loginEvent = new HashMap()
loginEvent.put('body', loginEventBody)

// console.log('sessionLogin_wt4221$')
coreClient.sessionLogin(loginEvent)
</code>```

if I do this, I got the following error:

```<code>/Users/jboemo/WorkspaceNexmo/nexmoclient-sdk-core-kmp/build/js/packages_imported/kotlin/1.6.10/kotlin.js:41851
      return this.internalMap_uxhen5$_0.put_xwzc9p$(key, value);
                                        ^

TypeError: Cannot read property 'put_xwzc9p$' of null
</code>```

my gradle configuration for js is the following:

```<code>js(BOTH){
        browser {
            commonWebpackConfig{
                cssSupport.enabled = false
            }
        }
    }
</code>```

so my questions are:

why the kotlin hashmap got his method called in that wired name?

how am I supposed to use the kotlin hashmap in js?

is there a better way to expose this without using the expect and actual mechanism?

this was to do things is working great in both android and ios

答: See an issue in Kotlin Youtrack - https://youtrack.jetbrains.com/issue/KT-34995.

Body:
I'm using kotlin multiplatform to export a library to ios, android and possibly js.

the kotlin class is like this:

@JsExport
class CoreClient (private val httpClient: HTTPClient, private val socket: SocketClient, eventDelegate:EventEngineDelegate? = null): SocketClientDelegate {
  ...
   fun sessionLogin(data: Map<String, Any>, callback: ((Exception?, String?) -> Unit)) {
        Logger.i { "CoreClient - sessionLogin"}

        val body = data["body"] as Map<String, Any?>
        // create an event for connecting the socket, store the token for the login to happen after connected
        val event = SocketConnectEvent(
            body,
            null,
            null,
            null,
            null,
            "SocketConnect"
        )
        invokeEngine(event, eventCallback(callback))
    }
    ...

}

that's how I'm trying to use it:

const lib = require("../build/js/packages/clientsdk-core-js-legacy");

const kotlin = require("../build/js/packages_imported/kotlin/1.6.10/kotlin");
const HashMap = kotlin.kotlin.collections.HashMap
HashMap.prototype.get = HashMap.prototype.get_11rb$
HashMap.prototype.put = HashMap.prototype.put_xwzc9p$

const {core, middleware, api } = lib.com.nexmo.clientsdk
const {CoreClient} = core
const {VoiceClient, MediaClient} = api
const coreClient = new CoreClient(HTTPClient(), SocketClient())

const mediaClient = new MediaClient()
const client = new VoiceClient(coreClient, mediaClient)

loginEventBody = new HashMap()
loginEventBody.put('token', 'TOKEN')
loginEventBody.put('device_id', 'js1')
loginEventBody.put('device_type', 'js')
loginEventBody.put('SDK_version', 'foo')

const loginEvent = new HashMap()
loginEvent.put('body', loginEventBody)

// console.log('sessionLogin_wt4221$')
coreClient.sessionLogin(loginEvent)

if I do this, I got the following error:

/Users/jboemo/WorkspaceNexmo/nexmoclient-sdk-core-kmp/build/js/packages_imported/kotlin/1.6.10/kotlin.js:41851
      return this.internalMap_uxhen5$_0.put_xwzc9p$(key, value);
                                        ^

TypeError: Cannot read property 'put_xwzc9p$' of null

my gradle configuration for js is the following:

js(BOTH){
        browser {
            commonWebpackConfig{
                cssSupport.enabled = false
            }
        }
    }

so my questions are:

why the kotlin hashmap got his method called in that wired name?

how am I supposed to use the kotlin hashmap in js?

is there a better way to expose this without using the expect and actual mechanism?

this was to do things is working great in both android and ios


问:
Simple way to bind two different properties together?
In my application I always want hscrollbar.LargeChange to equal panel.Width. Currently I set hscrollbar.LargeChange to panel.Widthin resizing events, painting events, et cetera. I do not know much about binding so I'm wondering if it is possible to do this.

Sorry if this is a simple question but when I tried googling binding and c# I got a lot of complicated information about other platforms.

答:
Actually, there is a way to bind the LargeChange property of the HScrollBar to the Width property of the panel, but I think I've just discovered a bug in .NET 4 with regards to this as it works if I target .NET 3.5.

Basically, you need to manually create a Binding object and assign it to the HScrollBar's DataBindings collection, like so:

```<code>hScrollBar1.DataBindings.Add(new Binding("LargeChange", panel1, "Size.Width", true, DataSourceUpdateMode.OnPropertyChanged));
</code>```

Again, this doesn't work in .NET 4, but it does in .NET 3.5. I'll probably submit a bug report.

Cheers

Body:
Actually, there is a way to bind the LargeChange property of the HScrollBar to the Width property of the panel, but I think I've just discovered a bug in .NET 4 with regards to this as it works if I target .NET 3.5.

Basically, you need to manually create a Binding object and assign it to the HScrollBar's DataBindings collection, like so:

hScrollBar1.DataBindings.Add(new Binding("LargeChange", panel1, "Size.Width", true, DataSourceUpdateMode.OnPropertyChanged));

Again, this doesn't work in .NET 4, but it does in .NET 3.5. I'll probably submit a bug report.

Cheers


问:
How to add datetime.time object in pandas
I have a column which has datetime,time objects. I need to find average time, total time.

inp:

```<code>150    03:00:00
157    03:00:00
Name: col , dtype: object
</code>```

their type:

```<code><class 'datetime.time'>
</code>```

I used

```<code>df["col"].sum()

</code>```

but I didn't get the exact results

答:
Convert values to strings and then timedeltas:</p>
```<code>s = pd.to_timedelta(df["col"].astype(str))

out = s.sum()
print (out)
0 days 06:00:00
</code>```

Body:
I have a column which has datetime,time objects. I need to find average time, total time.

inp:

150    03:00:00
157    03:00:00
Name: col , dtype: object

their type:

<class 'datetime.time'>

I used

df["col"].sum()

but I didn't get the exact results

Body:
Convert values to strings and then timedeltas:

s = pd.to_timedelta(df["col"].astype(str))

out = s.sum()
print (out)
0 days 06:00:00


问:
Docker --mount type=tmpfs with 'exec' permission
I'm trying to start multiple service and mount tmpfs but cant find any way to pass "exec" permission to this command.

```<code>docker run -d \
  -it \
  --name tmptest \
  --mount type=tmpfs,destination=/app \
  nginx:latest
</code>```

Its working perfectly with --tmpfs /tmp/test:exec  when you start single container but i have been smashing my head to make it work with --mount type=tmpfs,destination=/app  and still no luck to find anything.

Maybe any1 good any idea to work around it or im missing something.

答:
because --mount type=tmpfs,destination=/app by default runs with noexec flag which is not change able yet...

more details in this issue

Body:
I'm trying to start multiple service and mount tmpfs but cant find any way to pass "exec" permission to this command.

docker run -d \
  -it \
  --name tmptest \
  --mount type=tmpfs,destination=/app \
  nginx:latest

Its working perfectly with --tmpfs /tmp/test:exec  when you start single container but i have been smashing my head to make it work with --mount type=tmpfs,destination=/app  and still no luck to find anything.

Maybe any1 good any idea to work around it or im missing something.


问:
Serverless offline complains about missing stack before the first deployment
I am trying to run locally a serverless application, but it is throwing this error:

Stack with id <my_stack_id> does not exist
```

I didn't deploy the stack yet, just trying to run it locally. It is possible that the offline serverless plugin only works with an existing deployed stack?

答:
You don't need to deploy your stack

Things you need to have to use serverless offline :

plugins:
  - serverless-offline
```

in your serverless.yml file

then run the command sls offline start

then you can call your lambda functions with sls invoke local

Body:
I am trying to run locally a serverless application, but it is throwing this error:

Stack with id <my_stack_id> does not exist

I didn't deploy the stack yet, just trying to run it locally. It is possible that the offline serverless plugin only works with an existing deployed stack?

Body:
You don't need to deploy your stack

Things you need to have to use serverless offline :

plugins:
  - serverless-offline

in your serverless.yml file

then run the command sls offline start

then you can call your lambda functions with sls invoke local


问:
How to merge / combine / extend type declarations
In typescript, how can I create a new type from multiple type declarations in an outer join kind of way ?

I have 2 type declarations

```<code>type OverflowPosition = "safe" | "unsafe" | "";
type BaselinePosition = "baseline" | "center";
</code>```

I would like to see them combined to

```<code>type OverflowBaselinePosition = "safe baseline" | "safe center" | "unsafe baseline" | "unsafe center" | "baseline" | "center" ;
</code>```

答:
You can use template literal types, e.g.

```<code>type OverflowPosition = "safe" | "unsafe" | "";
type BaselinePosition = "baseline" | "center";

type CombinedPosition = `${OverflowPosition} ${BaselinePosition}`
</code>```

Playground link

Body:
In typescript, how can I create a new type from multiple type declarations in an outer join kind of way ?

I have 2 type declarations

type OverflowPosition = "safe" | "unsafe" | "";
type BaselinePosition = "baseline" | "center";

I would like to see them combined to

type OverflowBaselinePosition = "safe baseline" | "safe center" | "unsafe baseline" | "unsafe center" | "baseline" | "center" ;

Body:
You can use template literal types, e.g.

type OverflowPosition = "safe" | "unsafe" | "";
type BaselinePosition = "baseline" | "center";

type CombinedPosition = `${OverflowPosition} ${BaselinePosition}`

Playground link


问:
I want to write a python code using tkinter to get textbox value and output it. But Its not working properly
.</p>
```<code>from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self):
        self.gui=Tk()
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()

    def signup_form(self):
        global username
        global password
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username)

signup=sign()
</code>```

答:
Try this:

from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self):
        self.gui=Tk()
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()
        self.gui.mainloop()

    def signup_form(self):
        global username
        global password
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username.get())

signup=sign()

```

Body:
.

from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self):
        self.gui=Tk()
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()

    def signup_form(self):
        global username
        global password
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username)

signup=sign()