Title: How to detect zigzags in 2d arrays?

Body:
I'm trying to detect zigzags in 2d arrays.

Each row is given seperately.

Zigzags consist of the same number

There has to be at least 2 corners to be acknowledged as a zigzag

                    corner 1  corner 2
        0 0            0 0
          0 0            0       0 0
            0                      0

Elements of zigzags have to be adjacent to each other

        OK             OK             OK             OK
        0 0            0              0              0 0 0 0
          0 0            0            0                0 0 0 0 0
            0              0            0                    0
                                        0
                                          0

arr0 = array([[1, 1, 1, 1, 1, 1, 1, 1],
              [1, 0, 0, 0, 1, 1, 1, 1],
              [1, 1, 0, 0, 1, 1, 1, 1],
              [1, 1, 1, 0, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1]]).reshape(8,8)

-> start (1,1), end (3,3), 1 zigzag

arr1 = array([[1, 1, 1, 1, 1, 1, 1, 1],
              [1, 0, 1, 1, 1, 1, 1, 1],
              [1, 1, 0, 1, 1, 1, 1, 1],
              [1, 1, 1, 0, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1]]).reshape(8,8)

-> start (1,1), end (3,3), 1 zigzag

arr2 = array([[1, 1, 1, 1, 1, 1, 1, 1],
              [1, 0, 0, 0, 1, 1, 1, 1],
              [1, 1, 1, 0, 0, 1, 1, 1],
              [1, 1, 1, 0, 0, 1, 1, 1],
              [1, 1, 1, 0, 1, 1, 1, 1],
              [1, 1, 1, 1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1]]).reshape(8,8)

-> start (1,1), end (6,4), 1 zigzag

arr3 = array([[1, 1, 1, 1, 1, 1, 1, 1],
              [1, 0, 0, 0, 0, 0, 0, 1],
              [1, 0, 0, 0, 1, 0, 0, 1],
              [1, 0, 1, 0, 1, 1, 0, 1],
              [1, 0, 1, 1, 0, 1, 1, 1],
              [1, 0, 1, 1, 0, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 1, 1, 1]]).reshape(8,8)

-> start (1,1), end (5,4),
   start (1,1), end (3,6), 2 zigzags

I tried making a dictionary of start and end points of consecutive 0s and tracking continuous rows that meet n[start] <= n+1[start] <= n[end+1] and then conclude it's a zigzag if there are at least 3 different starts points in a group.

However, I failed to program it, because I got lost in multiple for, break loops and I still don't know how to track continuous rows that have the same start point(the same consecutive 0s).

So, I'd like to know

If there are any functions or algorithms that I could use to detect the pattern

Any good ideas to track continuous rows that meet the conditions

Better ways to do this


来源: stackexchange

问:
When FSM terminates early, the bot hangs
I have a tg-bot which has several commands, two of them activate the state machine. My problem: I activate FSM and go through a series of questions, but decide not to answer completely and enter a completely different command to the bot. The reaction of the bot is as follows: it continues the sequence of states in the FSM, and then completely freezes. How can this be fixed? I have asked this question a lot, but no one has been able to give an answer, I hope the community

Code start code:

```<code>    class Protest(StatesGroup):
        full_name = State()
        team_name = State()
        enemy = State()
        date = State()
        time = State()
        cause = State()

    @dp.message_handler(state=Protest.full_name)
    async def name_protest(message: types.Message, state=FSMContext):
        async with state.proxy() as data:
            data["full_name"] = message.text
        await Protest.next()
        await message.answer("Введите название Вашей команды:")
</code>```

End of code:

```<code>    @dp.message_handler(state=Protest.cause)
    async def cause_protest(message: types.Message, state=FSMContext):
        async with state.proxy() as data:
            data["cause"] = message.text
        await protest_db.sql_add_command(state)
        await state.finish()
        await message.answer("Ваш протест будет рассмотрен")

    def register_handlers_protest(dp: Dispatcher):
        dp.register_message_handler(start_protest, commands=["protest"], state=None)
        dp.register_message_handler(name_protest, state=Protest.full_name)
        dp.register_message_handler(teem_name_protest, state=Protest.team_name)
        dp.register_message_handler(enemy_teem, state=Protest.enemy)
        dp.register_message_handler(inline_kb_answer_callback_handler, state=Protest.date)
        dp.register_message_handler(time_match, state=Protest.time)
        dp.register_message_handler(cause_protest, state=Protest.cause)
</code>```

I deliberately don't paste the intermediate code, as it is very long and repetitive, which may interfere with your .

ContentLicense: CC BY-SA 4.0

Body:
I have a tg-bot which has several commands, two of them activate the state machine. My problem: I activate FSM and go through a series of questions, but decide not to answer completely and enter a completely different command to the bot. The reaction of the bot is as follows: it continues the sequence of states in the FSM, and then completely freezes. How can this be fixed? I have asked this question a lot, but no one has been able to give an answer, I hope the community

Code start code:

    class Protest(StatesGroup):
        full_name = State()
        team_name = State()
        enemy = State()
        date = State()
        time = State()
        cause = State()

    @dp.message_handler(state=Protest.full_name)
    async def name_protest(message: types.Message, state=FSMContext):
        async with state.proxy() as data:
            data["full_name"] = message.text
        await Protest.next()
        await message.answer("Введите название Вашей команды:")

End of code:

    @dp.message_handler(state=Protest.cause)
    async def cause_protest(message: types.Message, state=FSMContext):
        async with state.proxy() as data:
            data["cause"] = message.text
        await protest_db.sql_add_command(state)
        await state.finish()
        await message.answer("Ваш протест будет рассмотрен")

    def register_handlers_protest(dp: Dispatcher):
        dp.register_message_handler(start_protest, commands=["protest"], state=None)
        dp.register_message_handler(name_protest, state=Protest.full_name)
        dp.register_message_handler(teem_name_protest, state=Protest.team_name)
        dp.register_message_handler(enemy_teem, state=Protest.enemy)
        dp.register_message_handler(inline_kb_answer_callback_handler, state=Protest.date)
        dp.register_message_handler(time_match, state=Protest.time)
        dp.register_message_handler(cause_protest, state=Protest.cause)

I deliberately don't paste the intermediate code, as it is very long and repetitive, which may interfere with your .


问:
How can I resolve the faulting error in Apache
```<code>Faulting application name: httpd.exe, version: 2.4.48.0, time stamp: 0x60a37f00
Faulting module name: opencv_videoio_ffmpeg460_64.dll, version: 2022.5.0.0, time stamp: 0x00000000
Exception code: 0x40000015
Fault offset: 0x0000000000f7fd52
Faulting process id: 0x102d0
Faulting application start time: 0x01d913a882251b82
Faulting application path: C:\AI_People_Counter\Software_Files\Apache24\bin\httpd.exe
Faulting module path: C:\Program Files\Python38\Lib\site-packages\cv2\opencv_videoio_ffmpeg460_64.dll
Report Id: 63bbc67f-ae93-4b02-83d9-f9541a09f63b
Faulting package full name:
Faulting package-relative application ID:
</code>```

How can I resolve this issue?

Body:
Faulting application name: httpd.exe, version: 2.4.48.0, time stamp: 0x60a37f00
Faulting module name: opencv_videoio_ffmpeg460_64.dll, version: 2022.5.0.0, time stamp: 0x00000000
Exception code: 0x40000015
Fault offset: 0x0000000000f7fd52
Faulting process id: 0x102d0
Faulting application start time: 0x01d913a882251b82
Faulting application path: C:\AI_People_Counter\Software_Files\Apache24\bin\httpd.exe
Faulting module path: C:\Program Files\Python38\Lib\site-packages\cv2\opencv_videoio_ffmpeg460_64.dll
Report Id: 63bbc67f-ae93-4b02-83d9-f9541a09f63b
Faulting package full name:
Faulting package-relative application ID:

How can I resolve this issue?


问:
How to make API call from react-admin to backend in Golang?
I am not able to make API call from react-admin to backend which is developed in Golang.

I tried using the dataProvider according to the react-admin document.


问:
How can I successfully double jump in pygame?
When trying to create a double I either can jump infinitely or jump once, struggling to find a solution to only jump once.

I was able to create a double jump using two different keys however I want it to where I only have to use the 'W' key.

here's my code:

```<code>import pygame

pygame.init()

class Fighter:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.rect = pygame.Rect((self.x, self.y, 70, 200))
        self.x_vel = 0
        self.y_vel = 0
        self.jump = False

    def draw_player(self, surface):
        pygame.draw.rect(surface, "Red", self.rect)

    def detect_collisions(self, platforms):
        collisions = []
        for platform in platforms:
            if self.rect.colliderect(platform.rect):
                collisions.append(platform)
        return collisions

    def movement(self, player, platforms, screen_height, screen_width):
        self.x = 0
        self.y = 0
        self.y_vel = 0
        pixel_move = 30
        gravity = 5

        # get key presses
        key = pygame.key.get_pressed()

        # player one inputs
        if player == 1:
            if key[pygame.K_a]:
                self.x = -pixel_move
            if key[pygame.K_d]:
                self.x = pixel_move
            if key[pygame.K_w] and self.jump == False:
                self.y_vel = -pixel_move
                self.jump = True
            if key[pygame.K_s]:
                self.y_vel = pixel_move
        # player two inputs
        elif player == 2:
            if key[pygame.K_LEFT]:
                self.x = -pixel_move
            if key[pygame.K_RIGHT]:
                self.x = pixel_move

        # apply gravity
        self.y_vel += gravity

        # makes sure the player actually moves
        self.rect.x += self.x
        self.rect.y += self.y_vel

        # make sure player stays onto the screen
        self.platform_interaction(platforms)

        # make sure the player doesn't fall off the screen
        if self.rect.bottom + self.y_vel > screen_height:
            self.y_vel = 0
            self.rect.bottom = screen_height
            self.jump = False
        # make sure the player doesn't go above the screen
        if self.rect.top < 0:
            self.rect.top = 0
        # make sure the player doesn't go across the right side of the screen
        if self.rect.right > screen_width:
            self.rect.right = screen_width
        # makes sure the player doesn't go across the left side of the screen
        if self.rect.left <= 0:
            self.rect.left = 0

    def platform_interaction(self, platforms):
        collisions = self.detect_collisions(platforms)

        for platform in collisions:
            # player lands on top off platform
            if abs(self.rect.bottom - platform.rect.top) < 10:
                self.rect.bottom = platform.rect.top
                self.jump = False
            # player collides with the sides of the platform
            elif abs(self.rect.right - platform.rect.left) < 20:
                self.rect.right = platform.rect.left
            elif abs(self.rect.left - platform.rect.right) < 20:
                self.rect.left = platform.rect.right
            elif platform.state:
                # player hits themselves on bottom of the platform
                if abs(self.rect.top + self.y_vel) < platform.rect.bottom:
                    self.rect.top = platform.rect.bottom
                # make sure player doesn't fall through solid platforms
                elif abs(self.rect.bottom + self.y_vel) > platform.rect.top:
                    self.rect.bottom = platform.rect.top
</code>```

Body:
When trying to create a double I either can jump infinitely or jump once, struggling to find a solution to only jump once.

I was able to create a double jump using two different keys however I want it to where I only have to use the 'W' key.

here's my code:

import pygame

pygame.init()

class Fighter:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.rect = pygame.Rect((self.x, self.y, 70, 200))
        self.x_vel = 0
        self.y_vel = 0
        self.jump = False

    def draw_player(self, surface):
        pygame.draw.rect(surface, "Red", self.rect)

    def detect_collisions(self, platforms):
        collisions = []
        for platform in platforms:
            if self.rect.colliderect(platform.rect):
                collisions.append(platform)
        return collisions

    def movement(self, player, platforms, screen_height, screen_width):
        self.x = 0
        self.y = 0
        self.y_vel = 0
        pixel_move = 30
        gravity = 5

        # get key presses
        key = pygame.key.get_pressed()

        # player one inputs
        if player == 1:
            if key[pygame.K_a]:
                self.x = -pixel_move
            if key[pygame.K_d]:
                self.x = pixel_move
            if key[pygame.K_w] and self.jump == False:
                self.y_vel = -pixel_move
                self.jump = True
            if key[pygame.K_s]:
                self.y_vel = pixel_move
        # player two inputs
        elif player == 2:
            if key[pygame.K_LEFT]:
                self.x = -pixel_move
            if key[pygame.K_RIGHT]:
                self.x = pixel_move

        # apply gravity
        self.y_vel += gravity

        # makes sure the player actually moves
        self.rect.x += self.x
        self.rect.y += self.y_vel

        # make sure player stays onto the screen
        self.platform_interaction(platforms)

        # make sure the player doesn't fall off the screen
        if self.rect.bottom + self.y_vel > screen_height:
            self.y_vel = 0
            self.rect.bottom = screen_height
            self.jump = False
        # make sure the player doesn't go above the screen
        if self.rect.top < 0:
            self.rect.top = 0
        # make sure the player doesn't go across the right side of the screen
        if self.rect.right > screen_width:
            self.rect.right = screen_width
        # makes sure the player doesn't go across the left side of the screen
        if self.rect.left <= 0:
            self.rect.left = 0

    def platform_interaction(self, platforms):
        collisions = self.detect_collisions(platforms)

        for platform in collisions:
            # player lands on top off platform
            if abs(self.rect.bottom - platform.rect.top) < 10:
                self.rect.bottom = platform.rect.top
                self.jump = False
            # player collides with the sides of the platform
            elif abs(self.rect.right - platform.rect.left) < 20:
                self.rect.right = platform.rect.left
            elif abs(self.rect.left - platform.rect.right) < 20:
                self.rect.left = platform.rect.right
            elif platform.state:
                # player hits themselves on bottom of the platform
                if abs(self.rect.top + self.y_vel) < platform.rect.bottom:
                    self.rect.top = platform.rect.bottom
                # make sure player doesn't fall through solid platforms
                elif abs(self.rect.bottom + self.y_vel) > platform.rect.top:
                    self.rect.bottom = platform.rect.top


问:
Detecting equal columns in big datasets
For my master's thesis, I merged some large datasets for a machine learning model in which I try to predict the outcome of elections. In every dataset, there is for example a variable concerning the gender of the respondents. However, in some datasets, gender is labeled as 'gndr' and in others as 'sex'. As the datasets all contain different waves, it is useless to look for equal columns manually (because for example the European Social Survey ends up with more than 1000 variables when the different waves are merged).
I want to merge these equal columns (gender, but also for example age) before I handle other missings and before I conduct a cluster analysis.
I have been looking for the answer the past few days, but I just do not find a solution to detect these columns.

For the moment, I have been looking into the literature and online for an answer but with no solution found...
is there someone who can help? Thanks!

Title: Detecting equal columns in big datasets


问:
how to send notification on chrome?
I am developing an app where I get notifications at certain situations,
and I wanted to make it as a webapp so I don't have to make a developer account on Android/iOS.
But I haven't found any method to send notification on web browser environment, what I found only supports Android/iOS.
Is there any way to do it in web browser environment?</p>

Title: how to send notification on chrome?


问:
Package id emulator not avaible - Android Studio
I'm trying to install a virtual device in the Android Studio emulator but it won't let me and I get the Package id emulator error

Image of my mistake

I tried to reinstall android studio but still got the same error and also tried to install android studio canary version. Adding that I'm on version 3.6.2


问:
How should i extract text from pdf to csv on the basis of coordinates using python?
```<code></code>```
```<code>import pdfquery
import pandas as pd

pdf = pdfquery.PDFQuery('HBL.PDF')
pdf.load()
pdf.tree.write('pdfXML.xml', pretty_print = True)

def pdfscrape(pdf):
    # Extract each relevant information individually
    shipper = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.0, 756.181, 281.4, 787.659")').text()
    consignee = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.0, 650.454, 281.4, 704.409")').text()
    notify_party = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.0, 612.909, 124.8, 621.909")').text()
    ocean_vessel = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.75, 518.409, 147.15, 527.409")').text()
    port_of_loading = pdf.pq('LTTextLineHorizontal:overlaps_bbox("164.25, 518.409, 245.25, 527.409")').text()
    port_of_discharge = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.75, 495.159, 103.95, 504.159")').text()
    place_of_delivery = pdf.pq('LTTextLineHorizontal:overlaps_bbox("164.25, 497.409, 234.45, 506.409")').text()
    for_delivery_of_goods = pdf.pq('LTTextLineHorizontal:overlaps_bbox("286.5, 549.219, 507.9, 618.159")').text()
    container_no_and_seal_no = pdf.pq('LTTextLineHorizontal:overlaps_bbox("54.75, 455.409, 92.55, 464.409")').text()
    no_of_container = pdf.pq('LTTextLineHorizontal:overlaps_bbox("164.25, 454.659, 223.65, 463.659")').text()
    gross_weight = pdf.pq('LTTextLineHorizontal:overlaps_bbox("432.75, 455.409, 475.95, 464.409")').text()
    measurement = pdf.pq('LTTextLineHorizontal:overlaps_bbox("502.5, 447.916, 534.9, 464.409")').text()
# Combined all relevant information into single observation
    page = pd.DataFrame({
                         'Shipper': shipper,
                         'Consignee': consignee,
                         'Notify_party': notify_party,
                         'Ocean_vessel': ocean_vessel,
                         'Port_of_loading': port_of_loading,
                         'port_of_discharge': port_of_discharge,
                         'place_of_delivery': place_of_delivery,
                         'for_delivery_of_goods': for_delivery_of_goods,
                         'container_no_and_seal_no': container_no_and_seal_no,
                         'no_of_container': no_of_container,
                         'gross_weight': gross_weight,
                         'measurement': measurement
                       }, index=[0])
    return(page)

pagecount = pdf.doc.catalog['Pages'].resolve()['Count']
master = pd.DataFrame()
for p in range(pagecount):
    pdf.load(p)
    page = pdfscrape(pdf)
    master = master.append(page, ignore_index=True)

master.to_csv('output.csv', index=False)
</code>```

`

`

I have extracted text in CSV format after converting it to xml file. And, on the basis of coordinates I am converting it to csv. But, here I am putting coordinates after checking xml manually. As, it can be different for other pdf. So, I want to use coordinates dynamically (directly from xml file).

This is the pdf from which I am extracting data

Here, I am attaching the CSV file in which I am getting a data.

Now, I just want to extract those coordinates from XML file directly. I do not want to put those coordinates manually inside code.

Body:
import pdfquery
import pandas as pd

pdf = pdfquery.PDFQuery('HBL.PDF')
pdf.load()
pdf.tree.write('pdfXML.xml', pretty_print = True)

def pdfscrape(pdf):
    # Extract each relevant information individually
    shipper = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.0, 756.181, 281.4, 787.659")').text()
    consignee = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.0, 650.454, 281.4, 704.409")').text()
    notify_party = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.0, 612.909, 124.8, 621.909")').text()
    ocean_vessel = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.75, 518.409, 147.15, 527.409")').text()
    port_of_loading = pdf.pq('LTTextLineHorizontal:overlaps_bbox("164.25, 518.409, 245.25, 527.409")').text()
    port_of_discharge = pdf.pq('LTTextLineHorizontal:overlaps_bbox("33.75, 495.159, 103.95, 504.159")').text()
    place_of_delivery = pdf.pq('LTTextLineHorizontal:overlaps_bbox("164.25, 497.409, 234.45, 506.409")').text()
    for_delivery_of_goods = pdf.pq('LTTextLineHorizontal:overlaps_bbox("286.5, 549.219, 507.9, 618.159")').text()
    container_no_and_seal_no = pdf.pq('LTTextLineHorizontal:overlaps_bbox("54.75, 455.409, 92.55, 464.409")').text()
    no_of_container = pdf.pq('LTTextLineHorizontal:overlaps_bbox("164.25, 454.659, 223.65, 463.659")').text()
    gross_weight = pdf.pq('LTTextLineHorizontal:overlaps_bbox("432.75, 455.409, 475.95, 464.409")').text()
    measurement = pdf.pq('LTTextLineHorizontal:overlaps_bbox("502.5, 447.916, 534.9, 464.409")').text()
# Combined all relevant information into single observation
    page = pd.DataFrame({
                         'Shipper': shipper,
                         'Consignee': consignee,
                         'Notify_party': notify_party,
                         'Ocean_vessel': ocean_vessel,
                         'Port_of_loading': port_of_loading,
                         'port_of_discharge': port_of_discharge,
                         'place_of_delivery': place_of_delivery,
                         'for_delivery_of_goods': for_delivery_of_goods,
                         'container_no_and_seal_no': container_no_and_seal_no,
                         'no_of_container': no_of_container,
                         'gross_weight': gross_weight,
                         'measurement': measurement
                       }, index=[0])
    return(page)

pagecount = pdf.doc.catalog['Pages'].resolve()['Count']
master = pd.DataFrame()
for p in range(pagecount):
    pdf.load(p)
    page = pdfscrape(pdf)
    master = master.append(page, ignore_index=True)

master.to_csv('output.csv', index=False)

`

`

I have extracted text in CSV format after converting it to xml file. And, on the basis of coordinates I am converting it to csv. But, here I am putting coordinates after checking xml manually. As, it can be different for other pdf. So, I want to use coordinates dynamically (directly from xml file).

This is the pdf from which I am extracting data

Here, I am attaching the CSV file in which I am getting a data.

Now, I just want to extract those coordinates from XML file directly. I do not want to put those coordinates manually inside code.


问:
Problem starting tomcat (code=exited, status=217/USER)
I have an amazon linux machine and I am configuring
it to run an app, I made it through an AMI and deleted the old user, when I try to use the command "sudo systemctl start tomcat" I am getting the error (code=exited, status=217/USER), any idea what it could to be?

systemctl status tomcat.service

```<code>● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2022-12-19 09:56:59 -03; 10s ago
  Process: 3307 ExecStart=/bin/bash /home/test/scripts/start-tomcats.sh (code=exited, status=217/USER)

</code>```

my tomcat.service
`[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

EnvironmentFile=/etc/environment

ExecStart=/bin/bash /home/test/scripts/start-tomcats.sh
ExecStop=/bin/bash /home/test/scripts/shutdown-tomcats.sh

User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target

I created a new user and redid all the work thinking it would fix it but the problem persisted

Body:
I have an amazon linux machine and I am configuring
it to run an app, I made it through an AMI and deleted the old user, when I try to use the command "sudo systemctl start tomcat" I am getting the error (code=exited, status=217/USER), any idea what it could to be?

systemctl status tomcat.service

● tomcat.service - Apache Tomcat Web Application Container
   Loaded: loaded (/etc/systemd/system/tomcat.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2022-12-19 09:56:59 -03; 10s ago
  Process: 3307 ExecStart=/bin/bash /home/test/scripts/start-tomcats.sh (code=exited, status=217/USER)

my tomcat.service
`[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

EnvironmentFile=/etc/environment

ExecStart=/bin/bash /home/test/scripts/start-tomcats.sh
ExecStop=/bin/bash /home/test/scripts/shutdown-tomcats.sh

User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target

I created a new user and redid all the work thinking it would fix it but the problem persisted


问:
which is best to use: (viewStub) or (androidx.constraintlayout.widget.Group)?
In my android app, have 2 different layouts in MainActivity based on data presence
1- layout that shows empty state
2- layout that shows a list of data

I do not sure which is the best way (from the performance view) to implement this case, is using (viewStub) or (androidx.constraintlayout.widget.Group) or (fragment)?

I tried to implement it by using (androidx.constraintlayout.widget.Group) then control the visibility at run time


问:
redirct url with apex_authentication.callback
I try to connect the application to the identity, but when I do the required configuration, it receives an unauthorized_client error.

My question is:

The address is my local lcoalhost:7015/ords and

my app address is localhost:7015/ords/r/operation_report/operation_report

I need to find and config redirct url for apex_authentication.callback .

it Thank you for your help

redirct url with apex_authentication.callback


问:
Implement video ringtone for phone calls in flutter
I am doing a project in flutter. I am developing an app. using this app we can set a video ringtone for our default phone calls. I don't know how to achieve this.

How to I receive incoming calls in my app?

How can I achieve this? Kindly help me to implement this. Thanks in advance.


问:
Google Play Console - The Android App Bundle was not signed
I'm having a problem with uploading my game in the Google Play Console.

Platform I'm working on: Windows
Unity version: 2021.3.2f1
Also I'm using "App integrity" from Google Play Console.

The Error I get is: "The Android App Bundle was not signed."

The things I tried are:

Keystore is setup correctly.

I tried setting the Developer Build checked and unchecked. Neither of the options worked.

SHA fingerprints are setup correctly.

I have reset the SHA fingerprint values multiple times.


问:
How to decide either is it stationary data or not ? what if p value is less than 0.05 but decomposition shows trend and seasonality in graph
Decomposition result

Dicky-fuller test

Which should I consider and go forward with result?


问:
What's the proper way to replace manifest flag `android:windowSoftInputMode="adjustResize"` with insets API?
If I understood correctly, we can replace manifest flag android:windowSoftInputMode="adjustResize" with insets api.

My theme contains flags:

```<code><item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:navigationBarColor">?backgroundColorPrimary</item>
<item name="android:windowLightNavigationBar">true</item>
</code>```

Also I set some flags programmatically:

```<code>window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or
        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
</code>```

What should I do to refactor my code?

Body:
If I understood correctly, we can replace manifest flag android:windowSoftInputMode="adjustResize" with insets api.

My theme contains flags:

<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:navigationBarColor">?backgroundColorPrimary</item>
<item name="android:windowLightNavigationBar">true</item>

Also I set some flags programmatically:

window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or
        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

What should I do to refactor my code?


问:
How to call functions from js file on .ts Angular 12
I am using an external API built with javascript, and I need to call some functions on js file.

My main file are in src/asssets/openlayers/scripts/main.js

I imported them all on index.html, like

```<code><script src="/assets/openlayers/scripts/libs/jquery-1.10.2.min.js"></script>
<script src="/assets/openlayers/scripts/libs/jquery-ui-1.10.3.custom/jquery-ui-1.10.3.custom.min.js"></script>
<script src="/assets/openlayers/scripts/libs/proj4js-1.1.0/proj4js-compressed.js"></script>
<script src="/assets/openlayers/scripts/libs/OpenLayers-2.13.1/OpenLayers.js"></script>

<script src="/assets/openlayers/scripts/main.js"></script>
<script src="/assets/openlayers/scripts/classes/event.js"></script>
<script src="/assets/openlayers/scripts/classes/drawing.js"></script>
<script src="/assets/openlayers/scripts/classes/culturesDrawing.js"></script>
<script src="/assets/openlayers/scripts/classes/cultureMarkerDrawing.js"></script>
<script src="/assets/openlayers/scripts/map/map.initialize.js"></script>
<script src="/assets/openlayers/scripts/map/map.js"></script>
<script src="/assets/openlayers/scripts/map/map.tool.js"></script>
<script src="/assets/openlayers/scripts/map/map.tools.js"></script>
<script src="/assets/openlayers/scripts/map/map.cookies.js"></script>
<script src="/assets/openlayers/scripts/map/map.custom.controls.js"></script>
<script src="/assets/openlayers/scripts/map/map.contextmenu.js"></script>
<script src="/assets/openlayers/scripts/map/map.info.js"></script>
<script src="/assets/openlayers/scripts/map/map.drawingLayer.js"></script>
<script src="/assets/openlayers/scripts/map/map.layerStyle.js"></script>
<script src="/assets/openlayers/scripts/map/map.spatialLayer.js"></script>
<script src="/assets/openlayers/scripts/map/map.rasterLayer.js"></script>
<script src="/assets/openlayers/scripts/map/map.Legend.js"></script>
<script src="/assets/openlayers/scripts/map/map.rasterLegend.js"></script>
<script src="/assets/openlayers/scripts/map/map.layerSwitcher.js"></script>
<script src="/assets/openlayers/scripts/map/map.tooltip.js"></script>
<script src="/assets/openlayers/scripts/map/map.obsolete.js"></script>
</code>```

But now I need to call some fucntions that I have on main.js. How can I achieve this on my .ts file. I dont want to declare each function on the ts file like

```<code>declare var drawGauge: any;

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-geospacial-map',
  templateUrl: './geospatial-map.component.html',
  styleUrls: ['./geospatial-map.component.scss'],
})
export class GeospacialMapComponent implements OnInit {

  constructor() {}

  ngOnInit(): void {

  }
}
</code>```

It's possible to access everything from file globaly?
Sry for my bad expression, it's a lot of stuff, just ask me if you need more explanation

Body:
I am using an external API built with javascript, and I need to call some functions on js file.

My main file are in src/asssets/openlayers/scripts/main.js

I imported them all on index.html, like

But now I need to call some fucntions that I have on main.js. How can I achieve this on my .ts file. I dont want to declare each function on the ts file like

declare var drawGauge: any;

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-geospacial-map',
  templateUrl: './geospatial-map.component.html',
  styleUrls: ['./geospatial-map.component.scss'],
})
export class GeospacialMapComponent implements OnInit {

  constructor() {}

  ngOnInit(): void {

  }
}

It's possible to access everything from file globaly?
Sry for my bad expression, it's a lot of stuff, just ask me if you need more explanation


问:
How to mock handle.useTransaction in JDBI
I have a class with public method name process() which invoked a private method called processAandB().
In the method processAandB() we are using

```<code>handle.useTransaction(h -> {
   //calling processA and processB private methods
   processA(h)

   processB(h)

}) [JDBI handle]
</code>```

In processA we are creating tasks(Callable) which are to be processed via executor service and same applies to processB.

I am writing a JUnit test case where I've mocked the Handle and called the process() method and the problem is control is not going inside handle.useTransaction().
I am not sure how to invoke useTransaction in such a way that it call the processA and processB method too.

I tried mocking transaction too but couldn't.
Not sure what is the approach I should follow here.

Body:
I have a class with public method name process() which invoked a private method called processAandB().
In the method processAandB() we are using

handle.useTransaction(h -> {
   //calling processA and processB private methods
   processA(h)

   processB(h)

}) [JDBI handle]

In processA we are creating tasks(Callable) which are to be processed via executor service and same applies to processB.

I am writing a JUnit test case where I've mocked the Handle and called the process() method and the problem is control is not going inside handle.useTransaction().
I am not sure how to invoke useTransaction in such a way that it call the processA and processB method too.

I tried mocking transaction too but couldn't.
Not sure what is the approach I should follow here.


问:
how to debug a mavenized Java and flex integrated code
I am trying to debug a flex code integrated with java as a backend. It is a mavenized project and I am using eclipse . I tried going through similar question like How to debug Flex application under maven but I am not able to perform debugging properly. Can any one help me with this. I am not able to debug the code. The error which I am getting is very generic i.e. it just says problem in building the project and problem in executing the flex mojo. Can any one please help me with flex Debugging. </p>

```<code> Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:3.9:compile-swf (default-compile-swf) on project succor-ui: Error compiling! -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:3.9:compile-swf (default-compile-swf) on project succor-ui: Error compiling!
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error compiling!
    at org.sonatype.flexmojos.compiler.AbstractCompilerMojo.callCompiler(AbstractCompilerMojo.java:1141)
    at org.sonatype.flexmojos.compiler.AbstractCompilerMojo.run(AbstractCompilerMojo.java:2404)
    at org.sonatype.flexmojos.AbstractIrvinMojo.execute(AbstractIrvinMojo.java:155)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
[ERROR]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to debug a flex code integrated with java as a backend. It is a mavenized project and I am using eclipse . I tried going through similar question like How to debug Flex application under maven but I am not able to perform debugging properly. Can any one help me with this. I am not able to debug the code. The error which I am getting is very generic i.e. it just says problem in building the project and problem in executing the flex mojo. Can any one please help me with flex Debugging.

 Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:3.9:compile-swf (default-compile-swf) on project succor-ui: Error compiling! -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:3.9:compile-swf (default-compile-swf) on project succor-ui: Error compiling!
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error compiling!
    at org.sonatype.flexmojos.compiler.AbstractCompilerMojo.callCompiler(AbstractCompilerMojo.java:1141)
    at org.sonatype.flexmojos.compiler.AbstractCompilerMojo.run(AbstractCompilerMojo.java:2404)
    at org.sonatype.flexmojos.AbstractIrvinMojo.execute(AbstractIrvinMojo.java:155)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
[ERROR]


问:
Android List view SectionIndexer - list view not displaying curent scroll letter
I am trying to use secionIndexer with fast scroll in list view.
I have  implemented but
on scroll of list it should popup the current letter at which we have scrolled,
but its not showing that.

on debug mode I came to know that getSectipons() and getPositionForSection() are never called in my case ,
but in any other simple example that i tried from web it does make a call to those functions.

Pelase suggest me what to do
//##################
here is code of my adapter

//#######################

```<code>public class MyListAdapter extends ArrayAdapter<Object> implements SectionIndexer {

    Activity context;
    Object[] listData;
    HashMap<String, Integer> alphaIndexer;
    String[] sections;

    public MyListAdapter(Activity context, Object[] objects) {
        super(context, R.layout.new_invest_row, objects);
        this.context = context;
        listData = objects;
        alphaIndexer = new HashMap<String, Integer>();
        //changes here

         ArrayList myArrayList = new ArrayList();
           for (int ix=0; ix<objects.length; ix++) {
               myArrayList.add(objects[ix]);
               }

           Collections.sort(myArrayList, new Comparator<HashMap<String, String>>(){
                public int compare(HashMap<String, String> one, HashMap<String, String> two) {
                    return one.get("Name").compareToIgnoreCase(two.get("Name"));
                }
        });

         listData = myArrayList.toArray();
        //Arrays.sort(listData);
        for (int i = listData.length - 1; i >= 0; i--) {
            final HashMap<String, String> obj = (HashMap<String, String>)listData[i];
            String element = obj.get("Name");
            alphaIndexer.put(element.substring(0, 1).toUpperCase(), i);
        }

        Set<String> keys = alphaIndexer.keySet(); // set of letters

        // Copy into a List for sorting
        Iterator<String> it = keys.iterator();
        ArrayList<String> keyList = new ArrayList<String>();
        while (it.hasNext()) {
            String key = it.next();
            keyList.add(key);
        }
        Collections.sort(keyList);

        // Convert to array
        sections = new String[keyList.size()];
        keyList.toArray(sections);
        for(int c=0;c < sections.length;c++)Log.e("secction<"+c+">","+"+sections[c]);
        Log.e("alphaIndexer","+"+alphaIndexer);
    }

    static class ViewHolder {
        TextView txtName;
        TextView txtOwner;
        TextView txtStartDate;
        TextView txtEndDate;
        TextView txtStatus;
        ImageView imgIcon;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        View rowView = convertView;

        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.new_invest_row, null, true);
            holder = new ViewHolder();
            **holder.txtName = (TextView) rowView.findViewById(R.id.invest_row_name);**
//my custom code here

            rowView.setTag(holder);
        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        @SuppressWarnings("unchecked")
        final HashMap<String, String> obj = (HashMap<String, String>)listData[position];

        String str = obj.get("Name");
        if(null == str){
            str = "";
        }
        holder.txtName.setText(str);

        //#################
               //my custom code here

        return rowView;
    }

    public int getPositionForSection(int section) {
        String letter = sections[section];
        Log.e("alphaIndexer.get(letter)","+"+alphaIndexer.get(letter));

        return alphaIndexer.get(letter);
    }

    public int getSectionForPosition(int arg0) {
        // TODO Auto-generated method stub
        return 1;
    }

    public Object[] getSections() {
        return sections;
    }
}

//#######################
</code>```

I assume that in adapter when I am passing the textViewId its not taking the currect textVewId as the sectionIndexer functions are never called.

In the Layout new_invest_row I am getting custom row which have an icon and  few textViews.
I am sorting the list on the basis of name of the Object that I am displaying in each row.
i want indexer to work on the name of the object.

Please help me with exact solution

Body:
I am trying to use secionIndexer with fast scroll in list view.
I have  implemented but
on scroll of list it should popup the current letter at which we have scrolled,
but its not showing that.

on debug mode I came to know that getSectipons() and getPositionForSection() are never called in my case ,
but in any other simple example that i tried from web it does make a call to those functions.

Pelase suggest me what to do
//##################
here is code of my adapter

//#######################

public class MyListAdapter extends ArrayAdapter<Object> implements SectionIndexer {

    Activity context;
    Object[] listData;
    HashMap<String, Integer> alphaIndexer;
    String[] sections;

    public MyListAdapter(Activity context, Object[] objects) {
        super(context, R.layout.new_invest_row, objects);
        this.context = context;
        listData = objects;
        alphaIndexer = new HashMap<String, Integer>();
        //changes here

         ArrayList myArrayList = new ArrayList();
           for (int ix=0; ix<objects.length; ix++) {
               myArrayList.add(objects[ix]);
               }

           Collections.sort(myArrayList, new Comparator<HashMap<String, String>>(){
                public int compare(HashMap<String, String> one, HashMap<String, String> two) {
                    return one.get("Name").compareToIgnoreCase(two.get("Name"));
                }
        });

         listData = myArrayList.toArray();
        //Arrays.sort(listData);
        for (int i = listData.length - 1; i >= 0; i--) {
            final HashMap<String, String> obj = (HashMap<String, String>)listData[i];
            String element = obj.get("Name");
            alphaIndexer.put(element.substring(0, 1).toUpperCase(), i);
        }

        Set<String> keys = alphaIndexer.keySet(); // set of letters

        // Copy into a List for sorting
        Iterator<String> it = keys.iterator();
        ArrayList<String> keyList = new ArrayList<String>();
        while (it.hasNext()) {
            String key = it.next();
            keyList.add(key);
        }
        Collections.sort(keyList);

        // Convert to array
        sections = new String[keyList.size()];
        keyList.toArray(sections);
        for(int c=0;c < sections.length;c++)Log.e("secction<"+c+">","+"+sections[c]);
        Log.e("alphaIndexer","+"+alphaIndexer);
    }

    static class ViewHolder {
        TextView txtName;
        TextView txtOwner;
        TextView txtStartDate;
        TextView txtEndDate;
        TextView txtStatus;
        ImageView imgIcon;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        View rowView = convertView;

        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.new_invest_row, null, true);
            holder = new ViewHolder();
            **holder.txtName = (TextView) rowView.findViewById(R.id.invest_row_name);**
//my custom code here

            rowView.setTag(holder);
        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        @SuppressWarnings("unchecked")
        final HashMap<String, String> obj = (HashMap<String, String>)listData[position];

        String str = obj.get("Name");
        if(null == str){
            str = "";
        }
        holder.txtName.setText(str);

        //#################
               //my custom code here

        return rowView;
    }

    public int getPositionForSection(int section) {
        String letter = sections[section];
        Log.e("alphaIndexer.get(letter)","+"+alphaIndexer.get(letter));

        return alphaIndexer.get(letter);
    }

    public int getSectionForPosition(int arg0) {
        // TODO Auto-generated method stub
        return 1;
    }

    public Object[] getSections() {
        return sections;
    }
}

//#######################

I assume that in adapter when I am passing the textViewId its not taking the currect textVewId as the sectionIndexer functions are never called.

In the Layout new_invest_row I am getting custom row which have an icon and  few textViews.
I am sorting the list on the basis of name of the Object that I am displaying in each row.
i want indexer to work on the name of the object.

Please help me with exact solution


问:
Getting 403 forbidden error while uploading file to S3 using httpclient
Recently i have updated my project to .net6. I have to use httpclient since HttpWebRequest package is deprecated in previous version. I am getting 403 forbidden error for below code

```<code>using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.TryAddWithoutValidation("x-amz-date", "Mon, 01 Dec 2020 19:40:37 GMT");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "AWS {AWSAccessKeyId}:{CanonicalId}");

    HttpResponseMessage response = await client.GetAsync(url);
}
</code>```

When i use presignedurl it is working fine. but due to some secutiry concern i have to send the keys in header

Body:
Recently i have updated my project to .net6. I have to use httpclient since HttpWebRequest package is deprecated in previous version. I am getting 403 forbidden error for below code

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.TryAddWithoutValidation("x-amz-date", "Mon, 01 Dec 2020 19:40:37 GMT");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "AWS {AWSAccessKeyId}:{CanonicalId}");

    HttpResponseMessage response = await client.GetAsync(url);
}

When i use presignedurl it is working fine. but due to some secutiry concern i have to send the keys in header


问:
Perl Net::DNS version 1.35 resolver query fails
I am trying to test out the new version of cpan-Net-DNS (version 1.35) and it fails in the Net/DNS/Resolver/Base.pm file at line 987 with the following error.

```<code>***  FATAL PROGRAM ERROR!!  Unknown instance method 'size'
***  which the program has attempted to call for the object:
***
.   IN  OPT  ; no data
***
***  THIS IS A BUG IN THE CALLING SOFTWARE, which incorrectly assumes
***  that the object would be of a particular type.  The type of an
***  object should be checked before calling any of its methods.
***
Net::DNS::RR 1714 at Net/DNS/Resolver/Base.pm line 987.
    Net::DNS::Resolver::Base::_make_query_packet(Net::DNS::Resolver=HASH(0x55ebcfcd3d68), "example.com") called at Net/DNS/Resolver/Base.pm line 402
    Net::DNS::Resolver::Base::send(Net::DNS::Resolver=HASH(0x55ebcfcd3d68), "example.com") called at Net/DNS/Resolver/Base.pm line 374

</code>```

Has anyone seen this before?

This was on linux version 5.15. I tried the same thing on linux version 5.10 and it works but I can't pin point as to why. Here is the snippet of code I am running. This is on perl5.26

```<code>use Test::Simple;
use Net::DNS;
my $resolver = new Net::DNS::Resolver();
my $packet = $resolver->query('example.com');
ok($packet->answersize > 0, "NET::DNS");
</code>```

Body:
I am trying to test out the new version of cpan-Net-DNS (version 1.35) and it fails in the Net/DNS/Resolver/Base.pm file at line 987 with the following error.

***  FATAL PROGRAM ERROR!!  Unknown instance method 'size'
***  which the program has attempted to call for the object:
***
.   IN  OPT  ; no data
***
***  THIS IS A BUG IN THE CALLING SOFTWARE, which incorrectly assumes
***  that the object would be of a particular type.  The type of an
***  object should be checked before calling any of its methods.
***
Net::DNS::RR 1714 at Net/DNS/Resolver/Base.pm line 987.
    Net::DNS::Resolver::Base::_make_query_packet(Net::DNS::Resolver=HASH(0x55ebcfcd3d68), "example.com") called at Net/DNS/Resolver/Base.pm line 402
    Net::DNS::Resolver::Base::send(Net::DNS::Resolver=HASH(0x55ebcfcd3d68), "example.com") called at Net/DNS/Resolver/Base.pm line 374

Has anyone seen this before?

This was on linux version 5.15. I tried the same thing on linux version 5.10 and it works but I can't pin point as to why. Here is the snippet of code I am running. This is on perl5.26

use Test::Simple;
use Net::DNS;
my $resolver = new Net::DNS::Resolver();
my $packet = $resolver->query('example.com');
ok($packet->answersize > 0, "NET::DNS");


问:
Pipe stream from io.Reader into POST without storing in memory
Application A has a url pointing to a certain stored file. Can be stored on a disk, an S3 bucket or whatever else. Application B needs to receive a POST request, where the body is the content of what pointed by the URL, hence my file.

I have no access to Application B: what I think it's happening in there, and let's assume it's like this, is that it opens a stream reader towards the body content of the POST request. What I would like to achieve is that Application A passes the content of the file through a POST without having to:

open a stream reader towards the URL itself

stream the content in memory

embed the content in the body of the HTTP POST request.

Of course the main part I am avoiding is the "store in memory" part.
So far what I did is:

```<code>request, err := http.NewRequestWithContext(ctx, http.MethodGet, fileURL, nil)

response, err := httpClient.Do(request)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, ApplicationB_URL, response.Body)

res, err := httpClient.Do(req)
</code>```

Unfortunately this doesn't work in my case because Application B doesn't receive in the Body of the http POST the content of the file, but receives an IO Reader. Hence, I am trying to achieve what above, without having to download the file in memory of Application A. Am I missing some concept here?

Body:
Application A has a url pointing to a certain stored file. Can be stored on a disk, an S3 bucket or whatever else. Application B needs to receive a POST request, where the body is the content of what pointed by the URL, hence my file.

I have no access to Application B: what I think it's happening in there, and let's assume it's like this, is that it opens a stream reader towards the body content of the POST request. What I would like to achieve is that Application A passes the content of the file through a POST without having to:

open a stream reader towards the URL itself

stream the content in memory

embed the content in the body of the HTTP POST request.

Of course the main part I am avoiding is the "store in memory" part.
So far what I did is:

request, err := http.NewRequestWithContext(ctx, http.MethodGet, fileURL, nil)

response, err := httpClient.Do(request)

req, err := http.NewRequestWithContext(ctx, http.MethodPost, ApplicationB_URL, response.Body)

res, err := httpClient.Do(req)

Unfortunately this doesn't work in my case because Application B doesn't receive in the Body of the http POST the content of the file, but receives an IO Reader. Hence, I am trying to achieve what above, without having to download the file in memory of Application A. Am I missing some concept here?


问:
Parsing multiple dates from a sentence - Python
I need to parse multiple dates and numbers from a single sentence, for example

Repay $1000, $250 every 2 weeks 01/13-02/24/2023

however there need to be 100s of lines read like this and all are in different formats, some may have the installation amounts written first or not at all, some only put one or two dates others none at all.
I was planning on using multiple string manipulation commands to do this but that would be too inconsistent.
Is there a more optimised way to do this by any chance?

I'm using the reddit api to pull the post titles

this is the base code for finding the initial return amount

```<code>repayment = re.findall(r"\B[$/€/£]\d+", df1["Return_Amount"].values[0].lower())
y = list(map(str, repayment))
if len(y) > 1:
    return_amt = y[1]
    return_amt = return_amt[1:]
    return_amt = int(return_amt)
    df1["Return_Amount"].values[0] = return_amt
</code>```

there are too many variations for string manipulation to effectively work on them all

Body:
I need to parse multiple dates and numbers from a single sentence, for example

Repay $1000, $250 every 2 weeks 01/13-02/24/2023

however there need to be 100s of lines read like this and all are in different formats, some may have the installation amounts written first or not at all, some only put one or two dates others none at all.
I was planning on using multiple string manipulation commands to do this but that would be too inconsistent.
Is there a more optimised way to do this by any chance?

I'm using the reddit api to pull the post titles

this is the base code for finding the initial return amount

repayment = re.findall(r"\B[$/€/£]\d+", df1["Return_Amount"].values[0].lower())
y = list(map(str, repayment))
if len(y) > 1:
    return_amt = y[1]
    return_amt = return_amt[1:]
    return_amt = int(return_amt)
    df1["Return_Amount"].values[0] = return_amt

there are too many variations for string manipulation to effectively work on them all


Title: how can i make the lines variable in a file?

Body:
I am using a Unix-based program. I want to automate the code so as not to copy and paste data one by one. For this, I need to define line-by-line data in a file as a variable for the code.

The program converts xyz coordinates to local coordinates. How can I run the coordinates in the xyz_coordinates file I created, one by one, in the code below? In the program I use, the conversion code works like this,

echo 4208830.039709186 2334850.551667509 4171267.377406844 -6.753E-01 4.493E-01 2.849E-01  | xyz2env.py

and this is the file I am trying to run,

2679689.926729193 -727950.9964290063 5722789.538975053 7.873E-02 3.466E-01 6.410E-01

2679689.927123377 -727950.9971557076 5722789.540522 7.912E-02 3.458E-01 6.425E-01

2679689.930567728 -727950.9979971027 5722789.550832021 8.257E-02 3.450E-01 6.528E-01

2679689.931029495 -727950.9992263148 5722789.549927638 8.303E-02 3.438E-01 6.519E-01

2679689.929031829 -727950.9981009626 5722789.546359798 8.103E-02 3.449E-01 6.484E-01
........

and goes on like this. Also, there are spaces between the lines. Will this be a problem?


问:
Cannot add LibTorch-Lite, TensorFlowLiteSwift together as dependency for CocoaPod on M1 MacBook
I'm trying to add below as dependencies together for my CocoaPod (installing either one works but cannot install both)

s.dependency 'TensorFlowLiteSwift'

s.dependency 'LibTorch-Lite'

'LibTorch-Lite' requires below spec

```<code>s.static_framework = true

s.pod_target_xcconfig = {
      'HEADER_SEARCH_PATHS' => '$(inherited) ${PODS_ROOT}/LibTorch-Lite/install/include’,
      'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'
  }
  s.user_target_xcconfig = {
      'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'
  }
</code>```

because I get below error.

```<code>libtorch.a(empty.cpp.o), building for iOS Simulator, but linking in object file built for iOS, file '/var/folders/3x/x73_p70n2tg0gnwq9lct7rmr0000gn/T/CocoaPods-Lint-20221219-7300-1w8h64c-PyTorchTensorFlowCocoaPod/Pods/LibTorch-Lite/install/lib/libtorch.a' for architecture arm64
</code>```

However spec 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' causes below error when installing TensorFlowLiteSwift.

```<code>main.swift:1:8: error: could not find module 'PyTorchTensorFlowCocoaPod' for target 'arm64-apple-ios-simulator'; found: x86_64-apple-ios-simulator, at: /Users/steve.ham/Library/Developer/Xcode/DerivedData/App-dnxlikhybfsytahdpnmquhblzyly/Build/Products/Release-iphonesimulator/PyTorchTensorFlowCocoaPod/PyTorchTensorFlowCocoaPod.framework/Modules/PyTorchTensorFlowCocoaPod.swiftmodule
</code>```

Does anyone know how to install both CocoaPods as dependency? Thanks.

Body:
I'm trying to add below as dependencies together for my CocoaPod (installing either one works but cannot install both)

s.dependency 'TensorFlowLiteSwift'

s.dependency 'LibTorch-Lite'

'LibTorch-Lite' requires below spec

s.static_framework = true

s.pod_target_xcconfig = {
      'HEADER_SEARCH_PATHS' => '$(inherited) ${PODS_ROOT}/LibTorch-Lite/install/include’,
      'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'
  }
  s.user_target_xcconfig = {
      'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'
  }

because I get below error.

libtorch.a(empty.cpp.o), building for iOS Simulator, but linking in object file built for iOS, file '/var/folders/3x/x73_p70n2tg0gnwq9lct7rmr0000gn/T/CocoaPods-Lint-20221219-7300-1w8h64c-PyTorchTensorFlowCocoaPod/Pods/LibTorch-Lite/install/lib/libtorch.a' for architecture arm64

However spec 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' causes below error when installing TensorFlowLiteSwift.

main.swift:1:8: error: could not find module 'PyTorchTensorFlowCocoaPod' for target 'arm64-apple-ios-simulator'; found: x86_64-apple-ios-simulator, at: /Users/steve.ham/Library/Developer/Xcode/DerivedData/App-dnxlikhybfsytahdpnmquhblzyly/Build/Products/Release-iphonesimulator/PyTorchTensorFlowCocoaPod/PyTorchTensorFlowCocoaPod.framework/Modules/PyTorchTensorFlowCocoaPod.swiftmodule

Does anyone know how to install both CocoaPods as dependency? Thanks.


问:
"libunity.so" - Play Console Crash
we've been getting this crash on play console on our hypercasual games up on google play console. We are unable to track it down to what may be causing it. Here is the stack trace.

We are using Unity3d for our games and Firebase Analytics, Crashlytics and Messaging alongside Google Admob and Applovin sdks.

```<code>*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 4912 >>> com.dopegames.carsim <<<

backtrace:
  #00  pc 0x00000000004f850c  /vendor/lib64/egl/libGLES_mali.so
  #01  pc 0x0000000000475388  /vendor/lib64/egl/libGLES_mali.so
  #02  pc 0x00000000005e8234  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #03  pc 0x00000000005e7b70  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #04  pc 0x00000000005e6240  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #05  pc 0x00000000005c0678  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #06  pc 0x00000000005c57e8  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #07  pc 0x00000000005c5700  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #08  pc 0x00000000005ae6c0  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #09  pc 0x0000000000321cf4  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #10  pc 0x0000000000322458  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #11  pc 0x0000000000324b08  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #12  pc 0x000000000031928c  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #13  pc 0x0000000000331204  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #14  pc 0x000000000006f944  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/oat/arm64/base.odex
</code>```

Title: "libunity.so" - Play Console Crash

Body:
we've been getting this crash on play console on our hypercasual games up on google play console. We are unable to track it down to what may be causing it. Here is the stack trace.

We are using Unity3d for our games and Firebase Analytics, Crashlytics and Messaging alongside Google Admob and Applovin sdks.

*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 4912 >>> com.dopegames.carsim <<<

backtrace:
  #00  pc 0x00000000004f850c  /vendor/lib64/egl/libGLES_mali.so
  #01  pc 0x0000000000475388  /vendor/lib64/egl/libGLES_mali.so
  #02  pc 0x00000000005e8234  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #03  pc 0x00000000005e7b70  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #04  pc 0x00000000005e6240  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #05  pc 0x00000000005c0678  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #06  pc 0x00000000005c57e8  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #07  pc 0x00000000005c5700  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #08  pc 0x00000000005ae6c0  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #09  pc 0x0000000000321cf4  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #10  pc 0x0000000000322458  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #11  pc 0x0000000000324b08  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #12  pc 0x000000000031928c  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #13  pc 0x0000000000331204  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/lib/arm64/libunity.so
  #14  pc 0x000000000006f944  /data/app/~~_9hlgqK-ziZ2hhvPVMlTeg==/com.dopegames.carsim-vUmgewFgMybM0yE8UyZdjQ==/oat/arm64/base.odex


问:
How to provide path to local file in libUrl field using Highcharts
I'm using Highcharts to generate graphs and I am working on making the export functionality fully offline. The PNG and JPG exports work fine, but I order to export in PDF format the browser downloads jspdf.js and svg2pdf.js files. I tried to include them in my project files and use libUrl (https://api.highcharts.com/highcharts/exporting.libURL).

I tried things like

```<code>"file:///.../exportLibs/"
</code>```

but it doesn't seem to work. Is my approach correct and how should I provide a path to the directory with these 2 files?

Body:
I'm using Highcharts to generate graphs and I am working on making the export functionality fully offline. The PNG and JPG exports work fine, but I order to export in PDF format the browser downloads jspdf.js and svg2pdf.js files. I tried to include them in my project files and use libUrl (https://api.highcharts.com/highcharts/exporting.libURL).

I tried things like

"file:///.../exportLibs/"

but it doesn't seem to work. Is my approach correct and how should I provide a path to the directory with these 2 files?


问:
how to store foriegn key ids in new table in mvc in many to many relationship
the problem is that i have made three tables and first two table's primary keys are declared as foreign keys in the third table. now i want to store data in the third table but the problem is that no ids are being passsed to the foreign Key values thats why i am getting errors

as you can see i have shown to drop down lists, one for student and second for courses but when i try to register the record it is not getting ids of primary keys which are declared as foreign keys in the new table


问:
JaCoCo report showing 0% for excluded classes
I'm trying to integrate jacoco with jenkins. For now, whenever there's a push, jenkins detects and runs the jenkins file, where I have a stage for JaCoCo, that looks as follow and working:

```<code>if(runJaCoCo){
    stage('JaCoCo'){
            jacoco(
            )
            }
}
</code>```

My pom.xml looks as follow:

```<code><plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.5</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <excludes>
                                <exclude>com/Abc/Bcd/Cde/*</exclude>
                            </excludes>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>

                    </execution>
                </executions>
            </plugin>
</code>```

To simplify, my problem is that whenever I open the report in Jenkins, instead of not showing the package, it shows 0% for all files under Cde, which is making the report look worst than before.

I'm expecting that the report doesn't show at all the packages, instead of showing 0% for them.

Body:
I'm trying to integrate jacoco with jenkins. For now, whenever there's a push, jenkins detects and runs the jenkins file, where I have a stage for JaCoCo, that looks as follow and working:

if(runJaCoCo){
    stage('JaCoCo'){
            jacoco(
            )
            }
}

My pom.xml looks as follow:

<plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.5</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <excludes>
                                <exclude>com/Abc/Bcd/Cde/*</exclude>
                            </excludes>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>

                    </execution>
                </executions>
            </plugin>

To simplify, my problem is that whenever I open the report in Jenkins, instead of not showing the package, it shows 0% for all files under Cde, which is making the report look worst than before.

I'm expecting that the report doesn't show at all the packages, instead of showing 0% for them.


问:
how to blur the image?
I need to implement image blur

to do this, I have to use a double array in the form of a matrix, and implement the following:

each coefficient of the convolution matrix must be multiplied by the color value of the corresponding neighbor of the current (changeable) pixel

I need to handle going beyond 0 to 255

I tried to create and fill in the matrix with the 1/9 numbers that are in the task, but then I don't understand what and by what should I multiply?

has anyone solved this?

```<code>public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File("image.jpg"));
    WritableRaster raster = image.getRaster();

    int width = raster.getWidth();
    int height = raster.getHeight();

    final int colorsCountInRgb = 3;
    final int colorMaximum = 255;

    int[] pixel = new int[colorsCountInRgb];

    double[][] matrix = new double[3][3];
    double matrixMultiplier = 1 / 9d;

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            matrix[i][j] = matrixMultiplier;
        }
    }

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            raster.getPixel(x, y, pixel);

            raster.setPixel(x, y, pixel);
        }
    }

    ImageIO.write(image, "png", new File("out.png"));
}
</code>```

Title: how to blur the image?

Body:
I need to implement image blur

to do this, I have to use a double array in the form of a matrix, and implement the following:

each coefficient of the convolution matrix must be multiplied by the color value of the corresponding neighbor of the current (changeable) pixel

I need to handle going beyond 0 to 255

I tried to create and fill in the matrix with the 1/9 numbers that are in the task, but then I don't understand what and by what should I multiply?

has anyone solved this?

public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File("image.jpg"));
    WritableRaster raster = image.getRaster();

    int width = raster.getWidth();
    int height = raster.getHeight();

    final int colorsCountInRgb = 3;
    final int colorMaximum = 255;

    int[] pixel = new int[colorsCountInRgb];

    double[][] matrix = new double[3][3];
    double matrixMultiplier = 1 / 9d;

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            matrix[i][j] = matrixMultiplier;
        }
    }

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            raster.getPixel(x, y, pixel);

            raster.setPixel(x, y, pixel);
        }
    }

    ImageIO.write(image, "png", new File("out.png"));
}


问:
How to enforce the use of a wrapper function in JS
I am writing many functions which require the same setup (e.g. a login) and at the end of the function the same cleanup (e.g. a logout). Each funtion looks like this:

```<code>function myFunction() {
    //same for each function
    setup();
    //---------------------------
    // function individual code
    //---------------------------
    //same for each function
    cleanup();
}
</code>```

My current approach to reduce redundancy:

```<code>function myFunction() {
    //---------------------------
    // function individual code
    //---------------------------
}

function withLogin(callbackFunction) {
    setup();
    callbackFunction();
    cleanup();
}

withLogin(myFunction);
</code>```

Is there a way to ensure that myFunction is always called with the wrapper withLogin?

Is there a better way to solve my issue in the first place?

Body:
I am writing many functions which require the same setup (e.g. a login) and at the end of the function the same cleanup (e.g. a logout). Each funtion looks like this:

function myFunction() {
    //same for each function
    setup();
    //---------------------------
    // function individual code
    //---------------------------
    //same for each function
    cleanup();
}

My current approach to reduce redundancy:

function myFunction() {
    //---------------------------
    // function individual code
    //---------------------------
}

function withLogin(callbackFunction) {
    setup();
    callbackFunction();
    cleanup();
}

withLogin(myFunction);

Is there a way to ensure that myFunction is always called with the wrapper withLogin?

Is there a better way to solve my issue in the first place?


问:
Not able to update and retrieve both image and text from mongoDB
Javascript code

```<code>require('dotenv').config();
const express = require("express");
const path = require("path");
const crypto = require("crypto");
const multer = require("multer");
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require("gridfs-stream");
const methodOverride = require("method-override");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const findOrCreate = require("mongoose-findorcreate")

const app = express();
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

const mongoURI = 'mongodb://127.0.0.1:27017/userDB';
const conn = mongoose.createConnection(mongoURI);
//mongoose.connect("mongodb://127.0.0.1:27017/userDB", {useNewUrlParser: true});

let posts = [];

let gfs, gridfsBucket;

conn.once("open",() => {
  gridfsBucket = new mongoose.mongo.GridFSBucket(conn.db, {
        bucketName: "upload"
      });
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection("upload");
});

const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if(err) {
          return reject(err);
        }
        const filename = buf.toString("hex") + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: "upload"
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({storage});

app.get("/", function(req, res){
  res.render("review");
});

app.post("/review", (req, res) => {
  const post = {
    name: req.body.userName,
    hotel: req.body.hotelName,
    address: req.body.hotelAddress,
    star: req.body.rating,
    userexperience: req.body.experience
  };

  posts.push(post);
  //res.json({ file: req.file});
  res.redirect("/content");
});

app.get("/content", function(req, res){
  gfs.files.find().toArray((err, files) => {
    // Check if files
    if (!files || files.length === 0) {
      res.render("content", {files: false});
    } else {
      files.map(file => {
        if(file.contentType === "image/jpeg" || file.contentType === "image/png"){
          file.isImage = true;
        }else{
          file.isImage = false;
        }
      });
      res.render("content", {files: files});
    }
  });

});

app.get("/content", function(req, res){
  res.render("content", {posts: posts});
});

//@route GET /files
//@desc  Display all files in JSON
app.get("/files", (req, res) => {
  gfs.files.find().toArray((err, files) => {
    // Check if files
    if (!files || files.length === 0) {
      return res.status(404).json({
        err: "No files exist"
      });
    }

    // Files exist
    return res.json(files);
  });
});

app.get("/files/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    // Check if file
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }
    // File exists
    return res.json(file);
  });
});

// @route GET /image/:filename
// @desc Display Image
app.get("/image/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    // Check if file
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }

    // Check if image
    if (file.contentType === "image/jpeg" || file.contentType === "image/png") {
      // Read output to browser
      const readstream = gridfsBucket.openDownloadStreamByName(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: "Not an image"
      });
    }
  });
});

// Server setup
app.listen(3000, function(req, res) {
  console.log("Connected on port:3000");
});

</code>```

HTML Code where the review should be displayed - this is content page

```<code><section class="review-content">
    <% posts.forEach(function(post){ %>
  <h6><b>User Name:</b><%=post.name%></h6>
  <h5><b>Hotel Name:</b><%=post.hotel%></h5>
  <p><b>Hotel Address:</b><%=post.address%></p>
  <%if(post.star == 5){%>
      <p><b>Rating: </b>⭐⭐⭐⭐⭐ - Luxury</p>
  <%}%>
  <%if(post.star == 4){%>
      <p><b>Rating: </b>⭐⭐⭐⭐ - First Class</p>
  <%}%>
  <%if(post.star == 3){%>
      <p><b>Rating: </b>⭐⭐⭐ - Comfort</p>
  <%}%>
  <%if(post.star == 2){%>
      <p><b>Rating: </b>⭐⭐ - Standard</p>
  <%}%>
  <%if(post.star == 1){%>
      <p><b>Rating: </b>⭐ - Basic</p>
  <%}%>
  <% if(files){ %>
          <% files.forEach(function(file) { %>

              <% if(file.isImage) { %>
                <img src="image/<%= file.filename %>" alt="">
                <% } %>

            <% }) %>
              <% } else { %>
                <p>No files to show</p>
                <% } %

  <p><b>User experience:</b><%=post.userexperience%></p>
  <%});%>
</code>```

HTML Code where the review should be displayed - this is review page

```<code><form class="" action="/review" method="post" enctype="application/x-www-form-urlencoded" enctype="multipart/form-data" action="submit.php">
    <section class="review-section-height">

      <section class="review-section">
        <div class="review-section-div">
          <div class="user-name-review">
            <label for="hotel-name">User Name:</label>
            <input type="text" id="user-id-name" name="userName" placeholder="User Name" size="40"><br>
          </div>
          <div class="review-hotel-name">

            <label for="hotel-name">Hotel Name:</label>
            <input type="text" id="hotel-id-name" name="hotelName" placeholder="Hotel Name" size="40"><br>
          </div>
          <div class="hotel-address-div">

            <label for="hotel-address-name">Hotel Address:</label>
            <input type="text" id="hotel-id-address" name="hotelAddress" placeholder="Hotel Address" size="40"><br>
          </div>
        </div>
      </section>

      <section class="star-rating-section">

        <div class="food-experience-div">

          <h5>Rate your experience in hotel:</h5>
          <div class="rating">

            <input type="radio" name="rating" value="5" id="5"><label for="5">☆</label>
            <input type="radio" name="rating" value="4" id="4"><label for="4">☆</label>
            <input type="radio" name="rating" value="3" id="3"><label for="3">☆</label>
            <input type="radio" name="rating" value="2" id="2"><label for="2">☆</label>
            <input type="radio" name="rating" value="1" id="1"><label for="1">☆</label>

          </div>
        </div>

      </section>
    </section>

    <div class="container">
      <div class="wrapper">
        <div class="image">
          <img width="50%" height="450vh" src="" alt="">
        </div>
        <div class="content">
          <div class="icon">
            <i class="fas fa-cloud-upload-alt"></i>
          </div>
          <div class="text">
            No file chosen, yet!
          </div>
        </div>
        <div id="cancel-btn">
          <i class="fas fa-times"></i>
        </div>
        <div class="file-name">
          File name here
        </div>
      </div>
      <input name="file" id="default-btnn" type="file" >
    </div>

    <section class="overall-user-review">
      <div class="overall-user-review-div">
        <label for="experience-write-box">Write your experience:</label><br>
        <textarea class="experience-textarea" name="experience" rows="10" cols="47" placeholder="Elaborate your experince in the hotel..."></textarea>
      </div>

    </section>

<script>
      const wrapper = document.querySelector(".wrapper");
      const fileName = document.querySelector(".file-name");
      const defaultBtn = document.querySelector("#default-btnn");
      const customBtn = document.querySelector("#custom-btn");
      const cancelBtn = document.querySelector("#cancel-btn i");
      const img = document.querySelector("img");
      let regExp = /[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/;

      function defaultBtnActive() {
        defaultBtnn.click();
      }
      defaultBtn.addEventListener("change", function() {
        const file = this.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = function() {
            const result = reader.result;
            img.src = result;
            wrapper.classList.add("active");
          }
          cancelBtn.addEventListener("click", function() {
            img.src = "";
            wrapper.classList.remove("active");
          })
          reader.readAsDataURL(file);
        }
        if (this.value) {
          let valueStore = this.value.match(regExp);
          fileName.textContent = valueStore;
        }
      });
    </script>

</code>```

[Output at hyper terminal]
[Output at localhost at chrome]
Looking forward if someone can help me with this...
I need both image and text to be rendered on the screen
I am stuck with this problem for several days...
It's saying posts not defined... at eval... and so on...
Hoping a positive reply from developers...
Thank you for your help...

Body:
Javascript code

require('dotenv').config();
const express = require("express");
const path = require("path");
const crypto = require("crypto");
const multer = require("multer");
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require("gridfs-stream");
const methodOverride = require("method-override");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const findOrCreate = require("mongoose-findorcreate")

const app = express();
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

const mongoURI = 'mongodb://127.0.0.1:27017/userDB';
const conn = mongoose.createConnection(mongoURI);
//mongoose.connect("mongodb://127.0.0.1:27017/userDB", {useNewUrlParser: true});

let posts = [];

let gfs, gridfsBucket;

conn.once("open",() => {
  gridfsBucket = new mongoose.mongo.GridFSBucket(conn.db, {
        bucketName: "upload"
      });
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection("upload");
});

const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if(err) {
          return reject(err);
        }
        const filename = buf.toString("hex") + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: "upload"
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({storage});

app.get("/", function(req, res){
  res.render("review");
});

app.post("/review", (req, res) => {
  const post = {
    name: req.body.userName,
    hotel: req.body.hotelName,
    address: req.body.hotelAddress,
    star: req.body.rating,
    userexperience: req.body.experience
  };

  posts.push(post);
  //res.json({ file: req.file});
  res.redirect("/content");
});

app.get("/content", function(req, res){
  gfs.files.find().toArray((err, files) => {
    // Check if files
    if (!files || files.length === 0) {
      res.render("content", {files: false});
    } else {
      files.map(file => {
        if(file.contentType === "image/jpeg" || file.contentType === "image/png"){
          file.isImage = true;
        }else{
          file.isImage = false;
        }
      });
      res.render("content", {files: files});
    }
  });

});

app.get("/content", function(req, res){
  res.render("content", {posts: posts});
});

//@route GET /files
//@desc  Display all files in JSON
app.get("/files", (req, res) => {
  gfs.files.find().toArray((err, files) => {
    // Check if files
    if (!files || files.length === 0) {
      return res.status(404).json({
        err: "No files exist"
      });
    }

    // Files exist
    return res.json(files);
  });
});

app.get("/files/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    // Check if file
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }
    // File exists
    return res.json(file);
  });
});

// @route GET /image/:filename
// @desc Display Image
app.get("/image/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    // Check if file
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }

    // Check if image
    if (file.contentType === "image/jpeg" || file.contentType === "image/png") {
      // Read output to browser
      const readstream = gridfsBucket.openDownloadStreamByName(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: "Not an image"
      });
    }
  });
});

// Server setup
app.listen(3000, function(req, res) {
  console.log("Connected on port:3000");
});

HTML Code where the review should be displayed - this is content page

    <% posts.forEach(function(post){ %>

User Name:<%=post.name%>

Hotel Name:<%=post.hotel%>

Hotel Address:<%=post.address%>

  <%if(post.star == 5){%>

Rating: ⭐⭐⭐⭐⭐ - Luxury

  <%}%>
  <%if(post.star == 4){%>

Rating: ⭐⭐⭐⭐ - First Class

  <%}%>
  <%if(post.star == 3){%>

Rating: ⭐⭐⭐ - Comfort

  <%}%>
  <%if(post.star == 2){%>

Rating: ⭐⭐ - Standard

  <%}%>
  <%if(post.star == 1){%>

Rating: ⭐ - Basic

  <%}%>
  <% if(files){ %>
          <% files.forEach(function(file) { %>

              <% if(file.isImage) { %>
                <img src="image/<%= file.filename %>" alt="">
                <% } %>

            <% }) %>
              <% } else { %>

No files to show

                <% } %

User experience:<%=post.userexperience%>

  <%});%>

HTML Code where the review should be displayed - this is review page

<form class="" action="/review" method="post" enctype="application/x-www-form-urlencoded" enctype="multipart/form-data" action="submit.php">

            User Name:
            <input type="text" id="user-id-name" name="userName" placeholder="User Name" size="40">

            Hotel Name:
            <input type="text" id="hotel-id-name" name="hotelName" placeholder="Hotel Name" size="40">

            Hotel Address:
            <input type="text" id="hotel-id-address" name="hotelAddress" placeholder="Hotel Address" size="40">

Rate your experience in hotel:

            <input type="radio" name="rating" value="5" id="5">☆
            <input type="radio" name="rating" value="4" id="4">☆
            <input type="radio" name="rating" value="3" id="3">☆
            <input type="radio" name="rating" value="2" id="2">☆
            <input type="radio" name="rating" value="1" id="1">☆

            No file chosen, yet!

          File name here

      <input name="file" id="default-btnn" type="file" >

        Write your experience:

        <textarea class="experience-textarea" name="experience" rows="10" cols="47" placeholder="Elaborate your experince in the hotel..."></textarea>

[Output at hyper terminal]
[Output at localhost at chrome]
Looking forward if someone can help me with this...
I need both image and text to be rendered on the screen
I am stuck with this problem for several days...
It's saying posts not defined... at eval... and so on...
Hoping a positive reply from developers...
Thank you for your help...