问:
Attempting to use docker / docker compose to setup nginx to proxy requests to different ports on localhost - what am I missing?
I am attempting to forward requests this way:

```<code>https://xxx.domain1.com -> http://localhost:3000
https://yyy.domain2.com -> http://localhost:3001
</code>```

To make it easier to get nginx up and running, I'm using docker. Here is my Dockerfile:

```<code>version: '3.7'

services:
    proxy:
        image: nginx:alpine
        container_name: proxy
        ports:
            - '443:443'
            - '80:80'
        volumes:
            - ./nginx.conf:/etc/nginx/nginx.conf
            - ./.cert/cert.pem:/etc/nginx/.cert/cert.pem
            - ./.cert/key.pem:/etc/nginx/.cert/key.pem
        restart: 'unless-stopped'
        networks:
            - backend

networks:
    backend:
        driver: bridge
</code>```

And here is my nginx.conf:

```<code>http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server {
        listen 80;
        server_name yyy.domain2.com;

        chunked_transfer_encoding on;

        location / {
            proxy_pass http://localhost:3001/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }

    server {
        listen 80;
        server_name xxx.domain1.com;

        chunked_transfer_encoding on;

        location / {
            proxy_pass http://localhost:3000/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
}

stream {
        map $ssl_preread_server_name $name {
            xxx.domain1.com backend;
            yyy.domain2.com frontend;
        }

        upstream backend {
            server localhost:3000;
        }

        upstream frontend {
            server localhost:3001;
        }

        server {
            listen 443;
            listen [::]:443;
            proxy_pass $name;
            ssl_preread on;

            ssl_certificate        ./.cert/cert.pem;
            ssl_certificate_key    ./.cert/key.pem;

            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_prefer_server_ciphers on;
            ssl_ciphers "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";

        }
}

</code>```

I can access my services locally if I just open http://localhost:3000/test and http://localhost:3001/test, no problem.

But if I attempt to access with https://xxx.domain1.com/test, it spins for a while and then fails with ERR_CONNECTION_TIMED_OUT.

What am I missing?

UPDATE: I tried setting up the nginx service with a host network, but same result so far. I tried:

```<code>services:
    proxy:
        image: nginx:alpine
        # ports:
        #  - '443:443'
        #  - '80:80'
        ...
        extra_hosts:
            - "host.docker.internal:host-gateway"
</code>```

and

```<code>services:
    proxy:
        image: nginx:alpine
        ports:
          - '443:443'
          - '80:80'
        ...
        network_mode: "host"
</code>```

But no luck...

I think I'm missing the part on how to tell nginx to forward the request to the host, instead to localhost inside of it's own container.

But how to fix that?

Thanks,

Eduardo

Body:
I am attempting to forward requests this way:

https://xxx.domain1.com -> http://localhost:3000
https://yyy.domain2.com -> http://localhost:3001

To make it easier to get nginx up and running, I'm using docker. Here is my Dockerfile:

version: '3.7'

services:
    proxy:
        image: nginx:alpine
        container_name: proxy
        ports:
            - '443:443'
            - '80:80'
        volumes:
            - ./nginx.conf:/etc/nginx/nginx.conf
            - ./.cert/cert.pem:/etc/nginx/.cert/cert.pem
            - ./.cert/key.pem:/etc/nginx/.cert/key.pem
        restart: 'unless-stopped'
        networks:
            - backend

networks:
    backend:
        driver: bridge

And here is my nginx.conf:

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server {
        listen 80;
        server_name yyy.domain2.com;

        chunked_transfer_encoding on;

        location / {
            proxy_pass http://localhost:3001/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }

    server {
        listen 80;
        server_name xxx.domain1.com;

        chunked_transfer_encoding on;

        location / {
            proxy_pass http://localhost:3000/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
}

stream {
        map $ssl_preread_server_name $name {
            xxx.domain1.com backend;
            yyy.domain2.com frontend;
        }

        upstream backend {
            server localhost:3000;
        }

        upstream frontend {
            server localhost:3001;
        }

        server {
            listen 443;
            listen [::]:443;
            proxy_pass $name;
            ssl_preread on;

            ssl_certificate        ./.cert/cert.pem;
            ssl_certificate_key    ./.cert/key.pem;

            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_prefer_server_ciphers on;
            ssl_ciphers "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";

        }
}

I can access my services locally if I just open http://localhost:3000/test and http://localhost:3001/test, no problem.

But if I attempt to access with https://xxx.domain1.com/test, it spins for a while and then fails with ERR_CONNECTION_TIMED_OUT.

What am I missing?

UPDATE: I tried setting up the nginx service with a host network, but same result so far. I tried:

services:
    proxy:
        image: nginx:alpine
        # ports:
        #  - '443:443'
        #  - '80:80'
        ...
        extra_hosts:
            - "host.docker.internal:host-gateway"

and

services:
    proxy:
        image: nginx:alpine
        ports:
          - '443:443'
          - '80:80'
        ...
        network_mode: "host"

But no luck...

I think I'm missing the part on how to tell nginx to forward the request to the host, instead to localhost inside of it's own container.

But how to fix that?

Thanks,

Eduardo


来源: stackexchange

问:
Class property this._container children is empty in focus in and focus out
Trying to understand the cause of the below cases

Without instantiating new Graphics/Container in renderView method this._container is undefined if i try to access it, even though i have set the instantiated value to a variable.

In focus in and focus out this._container children is empty even after adding it in createText i.e this._container.addChild(text);

Can anyone please tell me if i am doing something wrong

```<code>import { Container, Graphics } from "pixi.js-legacy";
import { Models } from "@discovery-dni/cd-tv.sonic-network";
import {
    ImageComponent,
  } from "../../display";
import { Keys } from "@src/constants/keys";
import { Colours } from "@src/constants/theme";

import { SquareTile } from "./SquareTile";
import { TextComponent } from "@src/ui/display";
import { Icon, IconSizes, IconTypes } from "@src/ui/display";
import { animate } from "@src/helpers/animate";
import { Back } from "@src/greensock";

export enum Scale {
    NORMAL = 1,
    FOCUSED = 1.1
  }

const NETWORK_LOGO_WIDTH = 40;
const NETWORK_LOGO_MARGIN_LEFT = 24;
const TITLE_FONT_SIZE = 20;

export class SquareSecondaryTile extends SquareTile {
    private _graphic = new Graphics();
    public _container = new Container();

    protected renderImage(): any {
        if (this.image) {
          this._image = new ImageComponent(
            this.image.src as string,
            150,
            this.options.imageQuality.md,
            this.imageFormat,
            this.options.isCacheBuster
          );
          this._image.setAnchor(0.5, 0.5);
          this._image.x = 150;
          this._image.y = 150;
          this.addChild(this._image);
        }
      }

      protected renderTitles(): void {
        this.createText();
        this.addChild(this._container);
      }

    protected createText(): void {
        if (this.title) {
          const text = new TextComponent(
            this.title,
            {
              fill: Colours.GREY60,
              fontSize: TITLE_FONT_SIZE,
              wordWrapWidth: this.options.width - NETWORK_LOGO_WIDTH - NETWORK_LOGO_MARGIN_LEFT
            },
            2
          );
          text.position.set(0, this.options.titleY);
          this._container.addChild(text);
        }
      }

    protected createGraphic(): void {
      const width = this.options.width;
      const height = this.options.height;
      this._graphic.beginFill(Colours.BLACK);
      this._graphic.drawRect(0, 0, width, height);
      this.addChildAt(this._graphic, 0);
    }

    protected onFocusIn(): void {
        this.children.forEach(child => {
          if (child instanceof ImageComponent) {
            animate({
              config: {
                duration: 0.4,
                ease: Back.easeOut,
                pixi: { scaleX: Scale.FOCUSED, scaleY: Scale.FOCUSED }
              },
              enabled: this.options.animations.display,
              fallback: () => {
                child.scale.set(Scale.FOCUSED, Scale.FOCUSED);
              },
              target: child
            });
          }

          if (child instanceof TextComponent) {
            child.style.fill = Colours.WHITE;
          }
        });

        this._container.children.forEach(child => {
          if (child instanceof TextComponent) {
            child.style.fill = Colours.WHITE;
          }
          if (child instanceof ImageComponent) {
            child.setTint(Colours.WHITE);
          }
        });
      }

      protected onFocusOut(): void {
        this.children.forEach(child => {
          if (child instanceof ImageComponent) {
            animate({
              config: {
                duration: 0.4,
                ease: Back.easeOut,
                pixi: { scaleX: Scale.NORMAL, scaleY: Scale.NORMAL }
              },
              enabled: this.options.animations.display,
              fallback: () => {
                child.scale.set(Scale.NORMAL, Scale.NORMAL);
              },
              target: child
            });
          }
        });

        this._container.children.forEach(child => {
          if (child instanceof TextComponent) {
            child.style.fill = Colours.GREY60;
          }
          if (child instanceof ImageComponent) {
            child.setTint(Colours.GREY60);
          }
        });
      }

    public renderView(): void {
        this._container = new Container();
        this._graphic = new Graphics();
        this.createGraphic();
        this.renderImage();
        this.renderTitles();
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to understand the cause of the below cases

Without instantiating new Graphics/Container in renderView method this._container is undefined if i try to access it, even though i have set the instantiated value to a variable.

In focus in and focus out this._container children is empty even after adding it in createText i.e this._container.addChild(text);

Can anyone please tell me if i am doing something wrong

import { Container, Graphics } from "pixi.js-legacy";
import { Models } from "@discovery-dni/cd-tv.sonic-network";
import {
    ImageComponent,
  } from "../../display";
import { Keys } from "@src/constants/keys";
import { Colours } from "@src/constants/theme";

import { SquareTile } from "./SquareTile";
import { TextComponent } from "@src/ui/display";
import { Icon, IconSizes, IconTypes } from "@src/ui/display";
import { animate } from "@src/helpers/animate";
import { Back } from "@src/greensock";

export enum Scale {
    NORMAL = 1,
    FOCUSED = 1.1
  }

const NETWORK_LOGO_WIDTH = 40;
const NETWORK_LOGO_MARGIN_LEFT = 24;
const TITLE_FONT_SIZE = 20;

export class SquareSecondaryTile extends SquareTile {
    private _graphic = new Graphics();
    public _container = new Container();

    protected renderImage(): any {
        if (this.image) {
          this._image = new ImageComponent(
            this.image.src as string,
            150,
            this.options.imageQuality.md,
            this.imageFormat,
            this.options.isCacheBuster
          );
          this._image.setAnchor(0.5, 0.5);
          this._image.x = 150;
          this._image.y = 150;
          this.addChild(this._image);
        }
      }

      protected renderTitles(): void {
        this.createText();
        this.addChild(this._container);
      }

    protected createText(): void {
        if (this.title) {
          const text = new TextComponent(
            this.title,
            {
              fill: Colours.GREY60,
              fontSize: TITLE_FONT_SIZE,
              wordWrapWidth: this.options.width - NETWORK_LOGO_WIDTH - NETWORK_LOGO_MARGIN_LEFT
            },
            2
          );
          text.position.set(0, this.options.titleY);
          this._container.addChild(text);
        }
      }

    protected createGraphic(): void {
      const width = this.options.width;
      const height = this.options.height;
      this._graphic.beginFill(Colours.BLACK);
      this._graphic.drawRect(0, 0, width, height);
      this.addChildAt(this._graphic, 0);
    }

    protected onFocusIn(): void {
        this.children.forEach(child => {
          if (child instanceof ImageComponent) {
            animate({
              config: {
                duration: 0.4,
                ease: Back.easeOut,
                pixi: { scaleX: Scale.FOCUSED, scaleY: Scale.FOCUSED }
              },
              enabled: this.options.animations.display,
              fallback: () => {
                child.scale.set(Scale.FOCUSED, Scale.FOCUSED);
              },
              target: child
            });
          }

          if (child instanceof TextComponent) {
            child.style.fill = Colours.WHITE;
          }
        });

        this._container.children.forEach(child => {
          if (child instanceof TextComponent) {
            child.style.fill = Colours.WHITE;
          }
          if (child instanceof ImageComponent) {
            child.setTint(Colours.WHITE);
          }
        });
      }

      protected onFocusOut(): void {
        this.children.forEach(child => {
          if (child instanceof ImageComponent) {
            animate({
              config: {
                duration: 0.4,
                ease: Back.easeOut,
                pixi: { scaleX: Scale.NORMAL, scaleY: Scale.NORMAL }
              },
              enabled: this.options.animations.display,
              fallback: () => {
                child.scale.set(Scale.NORMAL, Scale.NORMAL);
              },
              target: child
            });
          }
        });

        this._container.children.forEach(child => {
          if (child instanceof TextComponent) {
            child.style.fill = Colours.GREY60;
          }
          if (child instanceof ImageComponent) {
            child.setTint(Colours.GREY60);
          }
        });
      }

    public renderView(): void {
        this._container = new Container();
        this._graphic = new Graphics();
        this.createGraphic();
        this.renderImage();
        this.renderTitles();
    }

}


问:
Always getting 20:mm when using tempus dominus datetimepicker
I am using tempus dominus datetimepicker. I create record in db using create page where I set start time e.g. 15:30, in database everything is saved as normal, but when I want to edit the record using edit page I always get 20:30 in field for Time.
I am using .NET Core 3.1.

```<code>$('#timepicker').datetimepicker({
  format: 'HH:mm',
  locale: 'mk',
});
</code>```
```<code><div class="form-group col-3">
 <label asp-for="Time" class="control-label">@DbResHtml.T("Време","Resources")</label>
 <div class="input-group date" id="timepicker" data-target-input="nearest">
  <input asp-for="Time" required type="text" class="form-control datetimepicker-input" data-target="#timepicker" />
   <div class="input-group-append" data-target="#timepicker" data-toggle="datetimepicker">
     <div class="input-group-text"><i class="fa fa-clock"></i></div>
   </div>
 </div>
<span asp-validation-for="Time" class="text-danger"></span>
</div>
</code>```

What should I change here, I have tried changing value dynamically using jquery but that attemp was unsuccessful.

Body:
I am using tempus dominus datetimepicker. I create record in db using create page where I set start time e.g. 15:30, in database everything is saved as normal, but when I want to edit the record using edit page I always get 20:30 in field for Time.
I am using .NET Core 3.1.

$('#timepicker').datetimepicker({
  format: 'HH:mm',
  locale: 'mk',
});

 @DbResHtml.T("Време","Resources")

  <input asp-for="Time" required type="text" class="form-control datetimepicker-input" data-target="#timepicker" />

What should I change here, I have tried changing value dynamically using jquery but that attemp was unsuccessful.


问:
Tkinter: Check if no widgets have focus
I have a script that creates a Canvas when either of the 2 Spinboxes gets focused. The Canvas contains a set of interactable shapes that require a user to click on.

I am looking for a method that checks if the focus is not on the spinboxes, canvas or canvas shapes and if so closes the canvas (a simple click off event). There may be other widgets that get focused after the canvas so i cannot simply bind a focus event to root.

I have created a MCVE below with a binding on root using Button-1, If you run the example this will close the canvas every time the mouse button is pressed, changing this to FocusIn only closes it if you deselect the entire window.

I need for s1, s2, Canvas and all canvas shapes to be checked if they have focus and if not close the canvas.

from tkinter import *
from tkinter.ttk import Spinbox

state=False

def draw(c):
    ax, ay, bx, by = 25, 25, 75, 75
    r = (by-ay)/2
    c.create_rectangle(ax, ay, bx, by, fill="#BBBBBB", width=0, tag='aa11')
    c.create_arc(bx-r, ay, bx+r, by, start=-90, extent=180, fill="#BBBBBB", width=0, outline="#BBBBBB", tag='aa11')
    c.create_arc(ax-r, ay, ax+r, by, start=270, extent=-180, fill="#BBBBBB", width=0, outline="#BBBBBB", tag='aa11')
    c.tag_bind('aa11', '<Button-1>', lambda e=Event(), m="Clicked": print(m))

def popup(event, c): ##opens the canvas
    global state
    if state:
        return
    state=True
    print("popped")
    c.pack_propagate(False)
    c.place(x=20, y=20)
    draw(c)

def popdown(event, c): ##closes the canvas
    global state
    if not state:
        return
    state=False
    print("deleted")
    c.delete('all')
    c.place_forget()

root=Tk()
root.geometry("500x500+100+100")
Button(root, text="do stuff").pack(side=TOP)
f= Frame(root)
f.pack()
c = Canvas(root, width=100, height=100)
s1 = Spinbox(f, wrap=True, values=tuple(list(str(x).zfill(2) for x in range(10))))
s1.pack(side=LEFT)
Label(f, text=":").pack(side=LEFT)
s2 = Spinbox(f, wrap=True, values=tuple(list(str(x).zfill(2) for x in range(10, 20))))
s2.pack()
s1.bind('<FocusIn>', lambda e=Event(), c=c: popup(e, c))
s2.bind('<FocusIn>', lambda e=Event(), c=c: popup(e, c))
root.bind('<Button-1>', lambda e=Event(), c=c: popdown(e, c)) ##for testing
Button(root, text="do other stuff").pack(side=TOP)

root.mainloop()
```

Title: Tkinter: Check if no widgets have focus


问:
Redshift: Temp table returning no results
I am trying to add week numbers to a temp Redshift table and two things are peculiar to me.

After running the query the first time, I get a 1table already exists` error, which defeats the purpose of the temp keyword. Does it not function as expected?

When I query this table despite it already existing, no rows are returned. What's going on here?

```<code>--DROP TABLE IF EXISTS weeks_in_year_table;

CREATE TEMP TABLE weeks_in_year_table (
    week_num INT
);

INSERT INTO weeks_in_year_table VALUES
     (1),  (2),  (3),  (4),  (5),  (6),  (7),  (8),  (9), (10),
    (11), (12), (13), (14), (15), (16), (17), (18), (19), (20),
    (21), (22), (23), (24), (25), (26), (27), (28), (29), (30),
    (31), (32), (33), (34), (35), (36), (37), (38), (39), (40),
    (41), (42), (43), (44), (45), (46), (47), (48), (49), (50),
    (51), (52);

SELECT * FROM weeks_in_year_table;

</code>```

Body:
I am trying to add week numbers to a temp Redshift table and two things are peculiar to me.

After running the query the first time, I get a 1table already exists` error, which defeats the purpose of the temp keyword. Does it not function as expected?

When I query this table despite it already existing, no rows are returned. What's going on here?

--DROP TABLE IF EXISTS weeks_in_year_table;

CREATE TEMP TABLE weeks_in_year_table (
    week_num INT
);

INSERT INTO weeks_in_year_table VALUES
     (1),  (2),  (3),  (4),  (5),  (6),  (7),  (8),  (9), (10),
    (11), (12), (13), (14), (15), (16), (17), (18), (19), (20),
    (21), (22), (23), (24), (25), (26), (27), (28), (29), (30),
    (31), (32), (33), (34), (35), (36), (37), (38), (39), (40),
    (41), (42), (43), (44), (45), (46), (47), (48), (49), (50),
    (51), (52);

SELECT * FROM weeks_in_year_table;


问:
On Duplicate Key Update with Greatest Value
I have 4 rows in my SQL table. id, tokenid, score and time.

If a player is playing the game for the first time, I can save it to the database.
If a player replays and collects more points than when they first played, I can save that to the database as well.
What I want to do and what I cannot do is; adding the player's time in the game with the most points to the database. When I try to do this, it saves it to the database even if the player has scored less points than the previous game. When I try to do this it updates the time value even if the player collects less points than the previous game.

This is how it works now:

First Game player scores 15 points at 19:00:00 (Database; score: 15,
time: 19:00:00)

Second Game player scores 13 points at 19:02:00 (Database; score: 15,
time: 19:02:00)

Third Game player scores 17 points at 19:03:00 (Database; score: 17,
time: 19:03:00)

This is what I want:

First Game player scores 15 points at 19:00:00 (Database; score: 15,
time: 19:00:00)

Second Game player scores 13 points at 19:02:00 (Database; score: 15,
time: 19:00:00)

Third Game player scores 17 points at 19:03:00 (Database; score: 17,
time: 19:03:00)

```<code>$tokenid = $_POST["tokenid1"];
$score = $_POST["score1"];
$time = date("H:i:s");

$records= "INSERT INTO scoreboard (tokenid, score, time)values('".$tokenid."', '".$score."', '".$time."') ON DUPLICATE KEY UPDATE score= GREATEST(score, VALUES(score))";
</code>```

I made some attempts for the time variable after the score variable, but I was not successful.

Body:
I have 4 rows in my SQL table. id, tokenid, score and time.

If a player is playing the game for the first time, I can save it to the database.
If a player replays and collects more points than when they first played, I can save that to the database as well.
What I want to do and what I cannot do is; adding the player's time in the game with the most points to the database. When I try to do this, it saves it to the database even if the player has scored less points than the previous game. When I try to do this it updates the time value even if the player collects less points than the previous game.

This is how it works now:

First Game player scores 15 points at 19:00:00 (Database; score: 15,
time: 19:00:00)

Second Game player scores 13 points at 19:02:00 (Database; score: 15,
time: 19:02:00)

Third Game player scores 17 points at 19:03:00 (Database; score: 17,
time: 19:03:00)

This is what I want:

First Game player scores 15 points at 19:00:00 (Database; score: 15,
time: 19:00:00)

Second Game player scores 13 points at 19:02:00 (Database; score: 15,
time: 19:00:00)

Third Game player scores 17 points at 19:03:00 (Database; score: 17,
time: 19:03:00)

$tokenid = $_POST["tokenid1"];
$score = $_POST["score1"];
$time = date("H:i:s");

$records= "INSERT INTO scoreboard (tokenid, score, time)values('".$tokenid."', '".$score."', '".$time."') ON DUPLICATE KEY UPDATE score= GREATEST(score, VALUES(score))";

I made some attempts for the time variable after the score variable, but I was not successful.


问:
Changing the text color inside a PrimeVue Dropdown Menu
I'm working on a Vue.js project that uses PrimeVue attributes. I needed a dropdown menu and I used PrimeVue's . It works great, but when I select an option on the dropdown, the selected option text becomes white. Dropdown itself is also white, so I cannot see the chosen option. You should know that this issue doesn't happen when I use a light PrimeVue theme. But when I use a dark PrimeVue theme, this issue appears.

PrimeVue themes I am using:
primevue/resources/themes/lara-light-blue/theme.css
primevue/resources/themes/lara-dark-blue/theme.css

Again, the dark one has the problem. So, I want to change the color of the text inside the Dropdown. I thought that if I make the text color black as a fixed color, the issue would be handled. Or any other suggestions?

I tried to assign a background-color to black but it did not solve my problem.


问:
how to insert dataframe into sql workbench. on local host
```<code># Create the connection object
mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    password = "umar1234",
    database="date_sheet"
)
# print(mydb)
#     # To Create Database
mycursor = mydb.cursor()
# creating column list for insertion#BSIT(M)-VII
print(data.columns.tolist())
cols = "`,`".join([str(i) for i in data])
for i,row in data.iterrows():
    sql = "INSERT INTO `room` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
    # cursor.execute(sql, tuple(row))
    cursor.execute()
    connection.commit()

</code>```

i want to insert data frame into sql workbench ...
database name ,and username and password is mentioned..
but i got an error..

```<code>Traceback (most recent call last):
  File "C:\Users\UMAR\PycharmProjects\FYP\scend.py", line 36, in <module>
    cursor.execute()
AttributeError: module 'mysql.connector.cursor' has no attribute 'execute'
</code>```

Body:
# Create the connection object
mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    password = "umar1234",
    database="date_sheet"
)
# print(mydb)
#     # To Create Database
mycursor = mydb.cursor()
# creating column list for insertion#BSIT(M)-VII
print(data.columns.tolist())
cols = "`,`".join([str(i) for i in data])
for i,row in data.iterrows():
    sql = "INSERT INTO `room` (`" +cols + "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
    # cursor.execute(sql, tuple(row))
    cursor.execute()
    connection.commit()

i want to insert data frame into sql workbench ...
database name ,and username and password is mentioned..
but i got an error..

Traceback (most recent call last):
  File "C:\Users\UMAR\PycharmProjects\FYP\scend.py", line 36, in <module>
    cursor.execute()
AttributeError: module 'mysql.connector.cursor' has no attribute 'execute'


问:
Nestjs doesn't handle request from nginx proxy_pass using docker-compose
I'm facing an issue using Nestjs with an request coming from proxy_pass by nginx with docker-compose.

I have a nestjs service that listen on the port 3000 with the following endpoints

get /api/users/:id

get /api/users

post /api/users

I have the following nginx configuration

```<code>events {
   worker_connections 1024;
}
http {

    upstream ticketing_users {
        server ticketing_users:3000;
    }

    server {
        listen 80;
        server_name ticketing.dev;

        location ~ ^/api/users(.*)$ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_intercept_errors on;
            proxy_pass http://ticketing_users/;
        }

        access_log /var/logs/nginx/access_log access;
        error_log  /var/logs/nginx/error.log error;
    }
}
</code>```

Here is my nginx config in docker-compose.yaml :

```<code>reverse-proxy:
    image: nginx
    volumes:
      - ./docker/nginx.conf:/etc/nginx/nginx.conf
      - ./docker/nginx:/var/logs/nginx
    networks:
      - ticketing.dev
    ports:
      - 8080:80
    depends_on:
      - ticketing_users
    links:
      - ticketing_users
</code>```

Here is my main.ts :

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(UsersModule, {
    cors: true,
    logger: ['verbose', 'debug', 'error', 'warn']
  });
  app.set('trust proxy', true);
  app.use(morgan('combined'));
  app.setGlobalPrefix('api');
  await app.listen(3000);
}
bootstrap();
```
<p>and my controller (generated with cli so it's declared in the module) :</p>
<pre class="lang-js prettyprint-override"><code>@Controller('users')
export class UsersController {
  @Get(':id')
  public findById(@Param('id') id: string): string {
    return id;
  }
}
</code>```

And i've set ticketing.dev in my host file.
But when i'm querying for exemple get http://ticketing.dev:8080/api/users/1234 with postman i always get the same result, i tried to put some console.logs but nothing appears :

{
"statusCode": 404,
"message": "Cannot GET /api/users/1234",
"error": "Not Found" }

But morgan middleware handle correctly the request and is showing :

GET /api/users/test 404 0.496 ms - 77

What am i doing wrong ?

Body:
I'm facing an issue using Nestjs with an request coming from proxy_pass by nginx with docker-compose.

I have a nestjs service that listen on the port 3000 with the following endpoints

get /api/users/:id

get /api/users

post /api/users

I have the following nginx configuration

events {
   worker_connections 1024;
}
http {

    upstream ticketing_users {
        server ticketing_users:3000;
    }

    server {
        listen 80;
        server_name ticketing.dev;

        location ~ ^/api/users(.*)$ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_intercept_errors on;
            proxy_pass http://ticketing_users/;
        }

        access_log /var/logs/nginx/access_log access;
        error_log  /var/logs/nginx/error.log error;
    }
}

Here is my nginx config in docker-compose.yaml :

reverse-proxy:
    image: nginx
    volumes:
      - ./docker/nginx.conf:/etc/nginx/nginx.conf
      - ./docker/nginx:/var/logs/nginx
    networks:
      - ticketing.dev
    ports:
      - 8080:80
    depends_on:
      - ticketing_users
    links:
      - ticketing_users

Here is my main.ts :

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(UsersModule, {
    cors: true,
    logger: ['verbose', 'debug', 'error', 'warn']
  });
  app.set('trust proxy', true);
  app.use(morgan('combined'));
  app.setGlobalPrefix('api');
  await app.listen(3000);
}
bootstrap();

and my controller (generated with cli so it's declared in the module) :

@Controller('users')
export class UsersController {
  @Get(':id')
  public findById(@Param('id') id: string): string {
    return id;
  }
}

And i've set ticketing.dev in my host file.
But when i'm querying for exemple get http://ticketing.dev:8080/api/users/1234 with postman i always get the same result, i tried to put some console.logs but nothing appears :

{
"statusCode": 404,
"message": "Cannot GET /api/users/1234",
"error": "Not Found" }

But morgan middleware handle correctly the request and is showing :

GET /api/users/test 404 0.496 ms - 77

What am i doing wrong ?


问:
Max Sum of All K consecutive sub arrays from 1 to n of an array using sliding window

This is my code and it does well for positive numbers given in the array but when one of the input      numbers is negative it doesn't work

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);  // Getting the length of array
    int arr[n];       // array of n length
    int sum[n];       // a sum array for finding the biggest sub arrays
    int max = -50;

    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);  // getting arrays elements
    }
    for (int k = 1; k <= n; k++) {
        for (int i = 0; i < n; i++) {
            sum[i] = 0;
            for (int j = 0; j < k; j++) {
                sum[i] = sum[i] + arr[j + i];
                if (sum[i] > max) {
                    max = sum[i];
                }
            }
        }
        printf("%d", max);
        printf("\n");
    }
}
```
<p>i think the max=-50 might be the problem but it is there for comparing
sums so if they were bigger it would put them as the new max</p>
<p>first input is the length of the array</p>
<p>Example Input:</p>
```
4
3
7
-5
1
```
<p>Expected Output:</p>
```
7
10
5
6
```
<p>Observed output:</p>
```
7
10
10
10
```

Body:
This is my code and it does well for positive numbers given in the array but when one of the input      numbers is negative it doesn't work

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);  // Getting the length of array
    int arr[n];       // array of n length
    int sum[n];       // a sum array for finding the biggest sub arrays
    int max = -50;

    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);  // getting arrays elements
    }
    for (int k = 1; k <= n; k++) {
        for (int i = 0; i < n; i++) {
            sum[i] = 0;
            for (int j = 0; j < k; j++) {
                sum[i] = sum[i] + arr[j + i];
                if (sum[i] > max) {
                    max = sum[i];
                }
            }
        }
        printf("%d", max);
        printf("\n");
    }
}

i think the max=-50 might be the problem but it is there for comparing
sums so if they were bigger it would put them as the new max

first input is the length of the array

Example Input:

4
3
7
-5
1

Expected Output:

7
10
5
6

Observed output:

7
10
10
10


问:
Restrict access of static files to permission groups
I'm fairly new to web development and I can't really find the best way to handle serving files with Django.

My situation is:
I have users from different departments that can upload, edit and download files. Users should have access to files from other users of the same department, but not of the others.

The way it works until now is: each file path is written in a database, with a reference to which department it belongs. If requesting a file Django checks if the department of the user is the same as the file, and denies access if that is not the case. So it's implemented using a normal view that returns a StreamingHttpResponse.

After researching a bit it seemed that serving files that way isn't the standard way, and I should serve them as static files (from the web server, not directly by Django). My question is: can I still restrict the access of static files, or can anyone read them?


问:
How to find the optimal path and values from a subset of multi-dimensional variables?
I am working on designing an experiment, where a system can receive 5 inputs [x1, x2, x3, x4, x5] and record target data associated with this "state". Given a new input state, the system will then transition from the old to the new state with a certain speed (these are constants) and record the target value along the path. Given the constraint in total time the system can run, what is the best subset of states that can be selected and the optimal trajectory to maximize the total diversity of data points generated?

The following are the variables we use:

```<code>x1 = np.arange(5, 37, 2)
x2 = np.arange(5, 53, 3)
x3 = np.arange(0, 3, 1)
x4 = np.arange(0, 4.3, 0.3)
x5 = np.arange(-3, 3.2, 0.2)
</code>```

There are a total of 357120 possible state combinations

Total experiment time cannot exceed 20 minutes (or 1200 seconds)

When a new state is reached, the system remains stationary for 5 seconds before beginning to move to a new state

The following are the rates of change (per 1/10 of a second) for each variable:

```<code>x1_speed = 0.1
x2_speed = 0.1
x3_speed = 0.005
x4_speed = 0.13
x5_speed = 0.1
</code>```

The best strategy I could come up with so far is to randomly initialize subset of states within the constraints of total time allowed, calculate total Euclidian distance between all points in the data and record the subset of states that maximizes that distance as measure of diversity of data points. However, inspecting some interactions in 2D plane still leaves chunks of space not mapped (per picture below).

Result of random state generation & optimization for Euclidian distance

I've looked into path optimization problems, but given the number of possible states * transitions to simulate all possible edges between all possible nodes seemed like wrong approach. Given that the points selected for experiment have to be optimized and are not pre-defined complicates things as well. If it is a diversity maximization LP problem with some constraints, how do you make it recursive to map out the whole path? Alternatively, was reading more about Reinforcement Learning approach.

The code I used to accomplish the above is as follows. I skipped the part where I record the states, but there's extra lines to populate states_df, which then I use to calculate total Euclidian distance. I can add it if necessary, but please let me know if there is a better strategy/algorithm to solve this problem given some of the constraints, thanks!

```<code>import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist

def state_gen():

    var1 = np.random.choice(x1)
    var2 = np.random.choice(x2)
    var3 = round(np.random.choice(x3), 1)
    var4 = round(np.random.choice(x4), 1)
    var5 = round(np.random.choice(x5), 1)

    state = [var1, var2, var3, var4, var5]
    return state

def state_change(state_old):

    state_new = state_gen()

    #x1
    x1_travel = state_old[0] - state_new[0]
    x1_time = abs(x1_travel/x1_speed) #in seconds

    #x2
    x2_travel = state_old[1] - state_new[1]
    x2_time = abs(x2_travel/x2_speed) #in seconds

    #x3
    x3_travel = state_old[2] - state_new[2]
    x3_time = abs(x3_travel/x3_speed) #in seconds

    #x4
    x4_travel = state_old[3] - state_new[3]
    x4_time = abs(x4_travel/x4_speed) #in seconds

    #x5
    x5_travel = state_old[4] - state_new[4]
    x5_time = abs(x5_travel/x5_speed) #in seconds

    #Record values to **states_df** here, add to return statement

    t_change = max(x1_time, x2_time, x3_time, x4_time, x5_time)
    return state_new, t_change

def objective():

    #Initialize first state
    state_old = state_gen()

    t_tot = 0

    while t_tot < 11500: #Little under 20 minutes in tenths of seconds

        state_new, t_change, = state_change(state_old)

        #System stationary for 5 seconds
        t_change += 50
        t_tot += t_change
        state_init = state_new

    tot_euc = pdist(states_df.values, metric='euclidean').sum()
    return tot_euc, tot_time, states_df

iter_nums = 250000
tot_euc_max = 0

for i in range(0, iter_nums):
    tot_euc, tot_time, states_df = objective()
    if tot_euc > tot_euc_max:
        tot_euc_max = tot_euc

print('Maximum {} attained'.format(tot_euc_max))
print('Total run time: {}'.format(tot_time))

</code>```

Body:
I am working on designing an experiment, where a system can receive 5 inputs [x1, x2, x3, x4, x5] and record target data associated with this "state". Given a new input state, the system will then transition from the old to the new state with a certain speed (these are constants) and record the target value along the path. Given the constraint in total time the system can run, what is the best subset of states that can be selected and the optimal trajectory to maximize the total diversity of data points generated?

The following are the variables we use:

x1 = np.arange(5, 37, 2)
x2 = np.arange(5, 53, 3)
x3 = np.arange(0, 3, 1)
x4 = np.arange(0, 4.3, 0.3)
x5 = np.arange(-3, 3.2, 0.2)

There are a total of 357120 possible state combinations

Total experiment time cannot exceed 20 minutes (or 1200 seconds)

When a new state is reached, the system remains stationary for 5 seconds before beginning to move to a new state

The following are the rates of change (per 1/10 of a second) for each variable:

x1_speed = 0.1
x2_speed = 0.1
x3_speed = 0.005
x4_speed = 0.13
x5_speed = 0.1

The best strategy I could come up with so far is to randomly initialize subset of states within the constraints of total time allowed, calculate total Euclidian distance between all points in the data and record the subset of states that maximizes that distance as measure of diversity of data points. However, inspecting some interactions in 2D plane still leaves chunks of space not mapped (per picture below).

Result of random state generation & optimization for Euclidian distance

I've looked into path optimization problems, but given the number of possible states * transitions to simulate all possible edges between all possible nodes seemed like wrong approach. Given that the points selected for experiment have to be optimized and are not pre-defined complicates things as well. If it is a diversity maximization LP problem with some constraints, how do you make it recursive to map out the whole path? Alternatively, was reading more about Reinforcement Learning approach.

The code I used to accomplish the above is as follows. I skipped the part where I record the states, but there's extra lines to populate states_df, which then I use to calculate total Euclidian distance. I can add it if necessary, but please let me know if there is a better strategy/algorithm to solve this problem given some of the constraints, thanks!

import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist

def state_gen():

    var1 = np.random.choice(x1)
    var2 = np.random.choice(x2)
    var3 = round(np.random.choice(x3), 1)
    var4 = round(np.random.choice(x4), 1)
    var5 = round(np.random.choice(x5), 1)

    state = [var1, var2, var3, var4, var5]
    return state

def state_change(state_old):

    state_new = state_gen()

    #x1
    x1_travel = state_old[0] - state_new[0]
    x1_time = abs(x1_travel/x1_speed) #in seconds

    #x2
    x2_travel = state_old[1] - state_new[1]
    x2_time = abs(x2_travel/x2_speed) #in seconds

    #x3
    x3_travel = state_old[2] - state_new[2]
    x3_time = abs(x3_travel/x3_speed) #in seconds

    #x4
    x4_travel = state_old[3] - state_new[3]
    x4_time = abs(x4_travel/x4_speed) #in seconds

    #x5
    x5_travel = state_old[4] - state_new[4]
    x5_time = abs(x5_travel/x5_speed) #in seconds

    #Record values to **states_df** here, add to return statement

    t_change = max(x1_time, x2_time, x3_time, x4_time, x5_time)
    return state_new, t_change

def objective():

    #Initialize first state
    state_old = state_gen()

    t_tot = 0

    while t_tot < 11500: #Little under 20 minutes in tenths of seconds

        state_new, t_change, = state_change(state_old)

        #System stationary for 5 seconds
        t_change += 50
        t_tot += t_change
        state_init = state_new

    tot_euc = pdist(states_df.values, metric='euclidean').sum()
    return tot_euc, tot_time, states_df

iter_nums = 250000
tot_euc_max = 0

for i in range(0, iter_nums):
    tot_euc, tot_time, states_df = objective()
    if tot_euc > tot_euc_max:
        tot_euc_max = tot_euc

print('Maximum {} attained'.format(tot_euc_max))
print('Total run time: {}'.format(tot_time))


问:
How i can deal with transporter and do logic in flow chart as like resources?
[model] https://i.stack.imgur.com/7A51i.jpg
I tried to put my transporters in queue and delay in its path (during unloading), after the transporter unload the cargo and goes back to the resource (which load the transporter). i tried to model it as a resource as shown but, i got an error (type : cast) as my agent consider to be a material item type ( can't cast the delay to transporter's agent type). what is the problem, and what i can do to achieve that with transporters instead of considering it a resource type.</p>


问:
I can't get pyw file to run for some reason
I created a python file where an event loop is running.
During this event loop, pressing certain hotkeys causes interaction with another app.

If I open the file and run it through PyCharm, it works.
If I run the file in a terminal or as a .py file, the code exits prematurely for some reason so I have to run it with the python -i command or add input() at the end of the code so that the event loop keeps running for the hotkeys to work. Is there a reason why that happens?

Now I would like to autostart this file every time Windows runs. In theory it should be easy:
Change it to .pyw and run it with pythonw.

However, if I do that and click on the file to execute, it doesn't work. No idea what is happening in the background.
If I run the file in a terminal like this: python main.pyw
the script is executed in the terminal, I can see it and the hotkeys work.

Why is .pyw not working for me here? What other alternative do I have to run the file in the background so that I can always use the hotkeys whenever I boot Windows?


问:
IP Cam live video feed using server end to front end C# MVC
Im making a c# mvc app and I have ip cam which is connected via a vpn to server pc. Ip cam is only available when the vpn is connected. Without the vpn i cant code it into view becasue the client end there wont be any vpn. So is there a way to display or transfer that server generated live video feed to a mvc razor page (in client pc)?</p>


问:
Feature scaling/normalization on data which has the same unit of measurement(ex. cm)
In my understanding of feature scaling/normalization you need to do this, because of different measurement units inside the features and bring them to a uniform scale. And in my opinion this only belongs to data of different measurement units (ex. ft, quantity, kg, ...).

But I am unsecure if I can use data of the same unit of measurement (centimeters) without scaling, especially if I want to use distance measures.

The datasat which I use is the iris dataset (https://www.kaggle.com/datasets/uciml/iris) which consists of 4 features, but all of them are measured in centimeters. So do I need to scale or not?

The algorithm I want to use is the k nearest neighbor, a distance based algorithm.


问:
How to create angular dynamic component based on input parameters
I'm creating a component for typography, and I'd like to have different variants of typography classes and the way I create that component:

Component definition example

```<code><typography variant="headline1" component="h1">
    hello h1
</typography>
</code>```

output example

```<code><h1 class="mat-headline-1">
    hello h1
</h1>
</code>```

I can't figure out how to dynamically generate the component based on the component input or access the defined content

```<code> const factory = this.factoryResolver.resolveComponentFactory('p');
    const component = factory.create(this.rootViewContainer.parentInjector);
    this.rootViewContainer.insert(component.hostView);
</code>```

Body:
I'm creating a component for typography, and I'd like to have different variants of typography classes and the way I create that component:

Component definition example

<typography variant="headline1" component="h1">
    hello h1
</typography>

output example

    hello h1

I can't figure out how to dynamically generate the component based on the component input or access the defined content

 const factory = this.factoryResolver.resolveComponentFactory('p');
    const component = factory.create(this.rootViewContainer.parentInjector);
    this.rootViewContainer.insert(component.hostView);


问:
What should this piece of .properties file look like in a .yml file?
how to convert this .properties file to .yml file?

```<code>remote.security.oauth2.audiences=https://example.com
remote.security.oauth2.jwts[0].issuer-uri=https:https://example2.com
remote.security.oauth2.jwts[0].jwk-set-uri=https://example3.com
remote.security.oauth2.jwts[1].issuer-uri=https://example4.com
remote.security.oauth2.jwts[1].jwk-set-uri=https://example5.com
</code>```

and yml example file

Body:
how to convert this .properties file to .yml file?

remote.security.oauth2.audiences=https://example.com
remote.security.oauth2.jwts[0].issuer-uri=https:https://example2.com
remote.security.oauth2.jwts[0].jwk-set-uri=https://example3.com
remote.security.oauth2.jwts[1].issuer-uri=https://example4.com
remote.security.oauth2.jwts[1].jwk-set-uri=https://example5.com

and yml example file


问:
Why my code crashes after processing 29 files? (C Programming)
I don' know what is going on. First 29 files were renamed as expected but on every time code crashes on twenty-ninth file. Could you help  my solve my problem

I use v12.2.0-gcc and run Arch Linux on a laptot.

Function that i'm working with:

```<code>#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>

int renameFiles(char *files[], char *path, char *prefix) {

  int i = 0;
  FILE *f;
  char *filename;
  char *ext;
  char *buffer;
  long numbytes;

  while ( files[i] != NULL ){

    filename = files[i];

    char filepath[sizeof path + sizeof filename];
    strcpy(filepath, path);
    strcat(filepath, filename);

    f = fopen(filepath, "rb");

    if (f == NULL)
      return 1;

    fseek(f, 0L, SEEK_END);
    numbytes = ftell(f);
    fseek(f, 0L, SEEK_SET);

    buffer = (char*)calloc(numbytes, sizeof(char*));

    if (buffer == NULL)
      return 1;

    fread(buffer, sizeof(char), numbytes, f);
    fclose(f);

    remove(filepath);

    ext = strrchr(filename, '.');

    if (!ext)
      ext = "";

    char int_str[sizeof i];
    sprintf(int_str, "%d", i + 1);

    char newfilename[sizeof prefix + sizeof int_str + sizeof ext];
    strcpy(newfilename, prefix);
    strcat(newfilename, int_str);
    strcat(newfilename, ext);

    char newfilepath[sizeof path + sizeof newfilename];
    strcpy(newfilepath, path);
    strcat(newfilepath, newfilename);

    f = fopen(newfilepath, "w");

    if (f == NULL)
      return 1;

    fwrite(buffer, 1, numbytes, f);
    printf("%s\n", newfilepath);
    fclose(f);

    i++;
  }

  return 0;
}
</code>```

Main.c

```<code>#include "files.h"
#include <readline/readline.h>
#include <readline/history.h>

int main(int argc, char *argv[]) {

  char *files[1024] = {};
  getFilesList(files, argv[1]);

  int length = 0;

  while( files[length] != NULL ){
    length++;
  }

  printf("%d files found on %s\n", length + 1, argv[1]);

  char *userInput = readline("Continue (y/n): ");

  if (strcmp(userInput, "y") != 0){
    return 0;
  }

  renameFiles(files, argv[1], argv[2]);

  return 0;
}

</code>```

I was making code for commandline/terminal application that cloud get directory and renamed them with prefix and to number like (bg.jpeg, image.jpg, wallpaper.png) to (file-1.jpeg, file-2.jpg, file-3.png....) while keeping to file extension as same. My code works for smaller ammunt of files but when file amount goes above 29 it crashes on the end.

Body:
I don' know what is going on. First 29 files were renamed as expected but on every time code crashes on twenty-ninth file. Could you help  my solve my problem

I use v12.2.0-gcc and run Arch Linux on a laptot.

Function that i'm working with:

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>

int renameFiles(char *files[], char *path, char *prefix) {

  int i = 0;
  FILE *f;
  char *filename;
  char *ext;
  char *buffer;
  long numbytes;

  while ( files[i] != NULL ){

    filename = files[i];

    char filepath[sizeof path + sizeof filename];
    strcpy(filepath, path);
    strcat(filepath, filename);

    f = fopen(filepath, "rb");

    if (f == NULL)
      return 1;

    fseek(f, 0L, SEEK_END);
    numbytes = ftell(f);
    fseek(f, 0L, SEEK_SET);

    buffer = (char*)calloc(numbytes, sizeof(char*));

    if (buffer == NULL)
      return 1;

    fread(buffer, sizeof(char), numbytes, f);
    fclose(f);

    remove(filepath);

    ext = strrchr(filename, '.');

    if (!ext)
      ext = "";

    char int_str[sizeof i];
    sprintf(int_str, "%d", i + 1);

    char newfilename[sizeof prefix + sizeof int_str + sizeof ext];
    strcpy(newfilename, prefix);
    strcat(newfilename, int_str);
    strcat(newfilename, ext);

    char newfilepath[sizeof path + sizeof newfilename];
    strcpy(newfilepath, path);
    strcat(newfilepath, newfilename);

    f = fopen(newfilepath, "w");

    if (f == NULL)
      return 1;

    fwrite(buffer, 1, numbytes, f);
    printf("%s\n", newfilepath);
    fclose(f);

    i++;
  }

  return 0;
}

Main.c

#include "files.h"
#include <readline/readline.h>
#include <readline/history.h>

int main(int argc, char *argv[]) {

  char *files[1024] = {};
  getFilesList(files, argv[1]);

  int length = 0;

  while( files[length] != NULL ){
    length++;
  }

  printf("%d files found on %s\n", length + 1, argv[1]);

  char *userInput = readline("Continue (y/n): ");

  if (strcmp(userInput, "y") != 0){
    return 0;
  }

  renameFiles(files, argv[1], argv[2]);

  return 0;
}

I was making code for commandline/terminal application that cloud get directory and renamed them with prefix and to number like (bg.jpeg, image.jpg, wallpaper.png) to (file-1.jpeg, file-2.jpg, file-3.png....) while keeping to file extension as same. My code works for smaller ammunt of files but when file amount goes above 29 it crashes on the end.


问:
Unable to stop Azure My SQL instance indefinitely
Through the azure portal I am trying to STOP Azure Database for MySQL single server instance. When I click on Stop button, I get following messgae:

Server will be automatically started after 7 days if you do not perform a manual start operation. The server is not in use and we want to stop it indefinitely.

How can I stop Azure Database for MySQL single server indefinitely? I do not want to Azure to restart the server after 7 days.


问:
When debugging flutter web app using the logger I just get useless error messages like "Expected a …patch/async_patch.dart 166:15 "
When debugging flutter web app in idea I just get useless error messages.

Here an example:

```<code>  Locale? loadSelectedLocale() {
    Locale lo = Hive.box(_storage).get(_locale);
    return lo;
  }
</code>```

the problem here is lo can be null.

The error I get is:

```<code>Expected a …patch/async_patch.dart 166:15               <fn>
</code>```

and I do the logging at this time:

```<code>runZonedGuarded<Future<void>>(() async {
    await _runApp(configuration);
  }, (Object error, StackTrace stackTrace) {
    if(error is TimeoutException){
     }else {
      new Logger("MyApp").severe(error.toString() + "\n" + stackTrace.toString());
    }
  });
</code>```

Using print instead of the logger I would get a better errormessage.
What do I have to do to get better error messages using the logger as prints are visible f. e. in the developerconsle?

Body:
When debugging flutter web app in idea I just get useless error messages.

Here an example:

  Locale? loadSelectedLocale() {
    Locale lo = Hive.box(_storage).get(_locale);
    return lo;
  }

the problem here is lo can be null.

The error I get is:

Expected a …patch/async_patch.dart 166:15               <fn>

and I do the logging at this time:

runZonedGuarded<Future<void>>(() async {
    await _runApp(configuration);
  }, (Object error, StackTrace stackTrace) {
    if(error is TimeoutException){
     }else {
      new Logger("MyApp").severe(error.toString() + "\n" + stackTrace.toString());
    }
  });

Using print instead of the logger I would get a better errormessage.
What do I have to do to get better error messages using the logger as prints are visible f. e. in the developerconsle?


问:
Connection Reset Error When Trying to Connect to Devops Repo Using TFS Plugin in RAD (Eclipse)
Currently in a work effort to convert code from CVS to TFS. I have TFS, EGIT and Maven. Getting the "Connect Reset" error when trying to connect to the devops site.

I had to use an old version of TFS TEE Plugin that works with our IDE, Rational Application Developer 8.5.1, which is based off of Eclipse (Platform 3.6.3 I believe). At the moment, we cannot upgrade our RAD version as there are internal dependencies for it.

Not really sure what to do here. Please advise.

-I have another version of Eclipse with another version of the TFS TEE Plugin and there is no issue, I can connect to the repo there.

-Research online indicated that it is a TLS network issue.

-Able to connect to web using Internal Web Browser in RAD.

-Uninstalled TFS plugin and reinstalled it.

-I saw a Microsoft post that mentioned it could've been an IIS setting on the server but I confirmed that the setting was as it should be.

-Tried changing to java 1.7 and 1.8 just in case it was a jdk issue but same error.


问:
Animation: How to make a stateful widget depends on the widget parameter?
The SoC parameter of the widget is not available from the start.
So, I'd like my animation tween to actually takes the SoC when it is no longer null.

But because I construct my animation within the initState() I don't get a chance to do so.

What would be the best architecture for this widget?

class SocGaugeWidget extends StatefulWidget {
  final double? soc;

  SocGaugeWidget({Key? key, required this.soc}) : super(key: key);

  State<SocGaugeWidget> createState() => _SocGaugeWidget();
}

class _SocGaugeWidget extends State<SocGaugeWidget>
    with SingleTickerProviderStateMixin {
  late final Animation<double> animation;
  late final AnimationController controller;

  @override
  void initState() {

    // == The animation
    controller =
        AnimationController(vsync: this, duration: Duration(seconds: 1));
    animation =
        Tween<double>(begin: 0, end: widget.soc ?? 10).animate(controller)
          ..addListener(() {
            setState(() {});
          })
          ..addStatusListener((status) {
            if (status == AnimationStatus.completed) {
              controller.reverse();
            } else if (status == AnimationStatus.dismissed) {
              controller.forward();
            }
          });

    controller.forward();

    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Text("${animation.value}");
  }
}
```


问:
Expo Av- saving recording on app closed on iOS
I am developing a recording app with expo av. I would like to save the recording in case the user closes the app completely while recording. I managed to solve that problem on Android by calling stopRecording in componentWillUnmount

```<code>  componentWillUnmount() {
    if (isRecording) stopRecording();
  }
</code>```

However, on iOS componentWillUnmount doesn't get executed on the app closed. Any idea what to do about it?

Body:
I am developing a recording app with expo av. I would like to save the recording in case the user closes the app completely while recording. I managed to solve that problem on Android by calling stopRecording in componentWillUnmount

  componentWillUnmount() {
    if (isRecording) stopRecording();
  }

However, on iOS componentWillUnmount doesn't get executed on the app closed. Any idea what to do about it?


问:
Why doesn't React.js display my local font?
I'm trying to change my Font import from a link to a local import.
The Chrome developer tools say Roboto is the Font Family, but it displays the standard Font.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto';
}

.app {
    background-color: $white-color;
    position: fixed;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;

    z-index: 1;
    flex-direction: column;
}

.linkRoute {
    color: $fontGrey02-color;
    text-decoration: none;
}

//remove scrollbar space to hide Scrollbar
::-webkit-scrollbar {
    width: 0px;
}

/* roboto-regular - latin */
@font-face {
    font-family: 'Roboto';
    font-style: normal;
    font-weight: 400;
    src: url('.././fonts/roboto-v30-latin-regular.eot'); /* IE9 Compat Modes */
    src: local(''),
         url('.././fonts/roboto-v30-latin-regular.eot') format('embedded-opentype'), /* IE6-IE8 */
         url('.././fonts/roboto-v30-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
         url('.././fonts/roboto-v30-latin-regular.woff') format('woff'), /* Modern Browsers */
         url('.././fonts/roboto-v30-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */
         url('.././fonts/roboto-v30-latin-regular.svg') format('svg'); /* Legacy iOS */
}
```


问:
Is overly used RAM a bottleneck
We have a MySQL DB server with the below configuration.

Capacity:

CPU - 4 cores

RAM - 16 GB

Memory - 150 GB

We are having performance issues with queries that work fine in the local development environment but take more time in the PROD environment. Upon investigation, I found around 800 connections opened from multiple services (about 12), and the RAM is 93% used. Do those 800 connections have bloated RAM, causing any performance issues?

Utilisation:

CPU usage is around 20-30%

Used RAM Memory - 93%

Used SWAP - 95%

Title: Is overly used RAM a bottleneck


问:
Signal Protocol in Flutter
I am building a chat application with flutter. I am using the libsignal_protocol_hive_store package which depends on the libsignal_protocol_dart package to encrypt messages. An encrypted message looks something like this:

{"msg":"MwohBfSQtKNmgh7qokkM4dGqxILAtj5CBqqDPYw9fxrLNaowEAEYACJQ9fcdabyIawEWsciqTsOFIMkITi4big3ASqZU28P33KF+/kYJ+B7u50njYrbYn/F4l9ab/k4lBZe1Ps2bk4DYd5a56VxfvHPcdxTuwINBzSSSh+ECjZ0kIg==","type":2}

My question would be, does this encrypted message provide Confidentiality, Integrity, and Authenticity?

Or does it only provide Confidentiality and I need to send a signature of the message together with the encrypted message?

This is how I get a encrypted message.

```<code>  Future<String?> getEncryptedMessage() async {
    Box<HiveSignalKeyStoreModel> keysBox = await Hive.openBox<HiveSignalKeyStoreModel>("signalKeysBox");

    HiveSignalKeyStoreModel? tempMe = keysBox!.get(me);
    if (tempMe == null) {
      tempMe = HiveSignalKeyStoreModel.generateFreshKeys(preKeysCount: 10);
      await keysBox!.put(me, tempMe);
    }

    SignalHelperModel myModel = SignalHelperModel(
      name: me,
      signalStore: HiveSignalProtocolStore(tempMe),
      senderKeyStore: HiveSenderKeyStore(tempMe),
    );

   String? encryptedMessage = await myModel.getEncryptedText(messageData.toString(), "friend");

   return encryptedMessage;
  }

</code>```

Thanks!

Title: Signal Protocol in Flutter

Body:
I am building a chat application with flutter. I am using the libsignal_protocol_hive_store package which depends on the libsignal_protocol_dart package to encrypt messages. An encrypted message looks something like this:

{"msg":"MwohBfSQtKNmgh7qokkM4dGqxILAtj5CBqqDPYw9fxrLNaowEAEYACJQ9fcdabyIawEWsciqTsOFIMkITi4big3ASqZU28P33KF+/kYJ+B7u50njYrbYn/F4l9ab/k4lBZe1Ps2bk4DYd5a56VxfvHPcdxTuwINBzSSSh+ECjZ0kIg==","type":2}

My question would be, does this encrypted message provide Confidentiality, Integrity, and Authenticity?

Or does it only provide Confidentiality and I need to send a signature of the message together with the encrypted message?

This is how I get a encrypted message.

  Future<String?> getEncryptedMessage() async {
    Box<HiveSignalKeyStoreModel> keysBox = await Hive.openBox<HiveSignalKeyStoreModel>("signalKeysBox");

    HiveSignalKeyStoreModel? tempMe = keysBox!.get(me);
    if (tempMe == null) {
      tempMe = HiveSignalKeyStoreModel.generateFreshKeys(preKeysCount: 10);
      await keysBox!.put(me, tempMe);
    }

    SignalHelperModel myModel = SignalHelperModel(
      name: me,
      signalStore: HiveSignalProtocolStore(tempMe),
      senderKeyStore: HiveSenderKeyStore(tempMe),
    );

   String? encryptedMessage = await myModel.getEncryptedText(messageData.toString(), "friend");

   return encryptedMessage;
  }

Thanks!


问:
Fragment doesnt show back arrow
So, I have a project where it shows a list of anime and a detailed screen. At first, when I'm using a single module, everything works fine. The Detail Fragment Shows the back arrow as normal like this:

And now I need to migrate my project into a multi-module due to my submission, but it's no longer working as it is. Instead, it shows the burger menu like the one on the list screen like this.

Here is my repository : Repository

Title: Fragment doesnt show back arrow


问:
Vuex orm - which relationship to use
I am currently using Vuex ORM alongside the json api plugin to query an api, transform the json api data into the orm and then save it.

I am having an issue where I am trying to get a property called fileables which returns an array of either tasks or projects or both.

This is the line it uses in the schema - it uses LaravelJsonApi

```<code>MorphToMany::make('fileables', [
    BelongsToMany::make('project', 'project')->type('projects'),
    BelongsToMany::make('task', 'task')->type('tasks'),
]),
</code>```

I've tried using a few relationships but the issue is the orm library or the plugin throws errors depending on which ones I use - the errors make sense but I am wondering what the core issue is.

If I try to use morphTo like this:

```<code>fileables_id: this.attr(null),
fileables_type: this.attr(null),
fileables: this.morphTo('fileables_id', 'fileables_type'),
</code>```

The orm plugin says 'Expected relation data to be an object' as it of course only works on a one to one basis.

I've tried the other relationships as well like morphToMany and hasManyBy but all of them error saying that it's expecting the data to have a certain type. For example if I define the model to be Tasks like so:

```<code>fileables: this.hasManyBy(Task, 'fileables_ids', 'id'),
</code>```

And the api returns a project, it complains because it's expecting a task instead as defined above.

Is there some way to fix this? I am looking for a morphTo relationship that works with an array of different types

Title: Vuex orm - which relationship to use

Body:
I am currently using Vuex ORM alongside the json api plugin to query an api, transform the json api data into the orm and then save it.

I am having an issue where I am trying to get a property called fileables which returns an array of either tasks or projects or both.

This is the line it uses in the schema - it uses LaravelJsonApi

MorphToMany::make('fileables', [
    BelongsToMany::make('project', 'project')->type('projects'),
    BelongsToMany::make('task', 'task')->type('tasks'),
]),

I've tried using a few relationships but the issue is the orm library or the plugin throws errors depending on which ones I use - the errors make sense but I am wondering what the core issue is.

If I try to use morphTo like this:

fileables_id: this.attr(null),
fileables_type: this.attr(null),
fileables: this.morphTo('fileables_id', 'fileables_type'),

The orm plugin says 'Expected relation data to be an object' as it of course only works on a one to one basis.

I've tried the other relationships as well like morphToMany and hasManyBy but all of them error saying that it's expecting the data to have a certain type. For example if I define the model to be Tasks like so:

fileables: this.hasManyBy(Task, 'fileables_ids', 'id'),

And the api returns a project, it complains because it's expecting a task instead as defined above.

Is there some way to fix this? I am looking for a morphTo relationship that works with an array of different types


问:
Voronoi diagram region colors
Do I understand the "voronoi_color" parameter of the function "plot_voronoi_polys_with_points_in_area" correctly? Because I'm trying to choose specific regions to have the same color, and I'm using this dict that I created:

```<code>dict_voronoi =

{0: 'red',
 1: 'red',
 2: 'red',
 3: 'red',
 4: 'red',
 5: 'red',
 6: 'red',
 7: 'red',
 8: 'red',
 9: 'red',
 10: 'red',
etc...
}
</code>```

They are 4355 keys and I put all values to red just to try to make it work, but I still get the following map when passing the parameter voronoi_color = dict_voronoi:

Voronoi Europe

Why won't the regions be filled with red?

Title: Voronoi diagram region colors

Body:
Do I understand the "voronoi_color" parameter of the function "plot_voronoi_polys_with_points_in_area" correctly? Because I'm trying to choose specific regions to have the same color, and I'm using this dict that I created:

dict_voronoi =

{0: 'red',
 1: 'red',
 2: 'red',
 3: 'red',
 4: 'red',
 5: 'red',
 6: 'red',
 7: 'red',
 8: 'red',
 9: 'red',
 10: 'red',
etc...
}

They are 4355 keys and I put all values to red just to try to make it work, but I still get the following map when passing the parameter voronoi_color = dict_voronoi:

Voronoi Europe

Why won't the regions be filled with red?


问:
error: [Hilt] Null element: java.lang.NullPointerException: Null element [Hilt]
I was writing unit tests for my room db operations, everything was working great but, I decided to write  and inject the DataBaseBuilder within TestAppModule using Hilt, but seems like I am getting the following error when i run the tests. I also created a custom HiltRunnerClass and used it in gradle as testInstrumentationRunner "com.rimapps.wisetest.HiltTestRunner"
here is full error

error: [Hilt]
  Null element: java.lang.NullPointerException: Null element
    at dagger.hilt.processor.internal.root.AutoValue_Root.<init>(AutoValue_Root.java:19)
    at dagger.hilt.processor.internal.root.Root.createDefaultRoot(Root.java:46)
    at
  [Hilt] Processing did not complete. See error above for details.
1 error```
</div>
</div>
</p>
<p>here is the code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>HiltTestRunner.kt
class HiltTestRunner:AndroidJUnitRunner() {

    override fun newApplication(
        cl: ClassLoader?,
        className: String?,
        context: Context?
    ): Application {
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }

}</code>```

NewsArticleDaoTest.kt
@RunWith(AndroidJUnit4::class)
@SmallTest
@HiltAndroidTest
class NewsArticleDaoTest{

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Inject
    @Named("test_db")
    lateinit var database: NewsArticleDatabase

    //private lateinit var database: NewsArticleDatabase
    private lateinit var dao: NewsArticleDao

    @Before
    fun setup(){
        hiltRule.inject()
        dao = database.newsArticleDao()

//        database = Room.inMemoryDatabaseBuilder(
//            ApplicationProvider.getApplicationContext(),
//            NewsArticleDatabase::class.java
//        ).allowMainThreadQueries().build()
        dao = database.newsArticleDao()

    }

    @After
    fun teardown(){
        database.close()
    }
    @Test
    fun insertNewsArticle() = runTest {
        val testArticle = NewsArticle("Time traveller shares footage from three weeks in the future showing who wins the World Cup","https://www.ladbible.com/sport/time-traveller-who-wins-world-cup-2022-20221128","https://images.ladbible.com/resize?type=webp&quality=70&width=671&fit=contain&gravity=null&dpr=2&url=https://eu-images.contentstack.com/v3/assets/bltcd74acc1d0a99f3a/bltb6064933a4b82b9c/6384c84adb8e364b186bfb6c/Most_prolific_speed_camera_in_the_UK_has_caught_almost_50_000_drivers_this_year_(42).png")
        val testItem = listOf(testArticle)
        dao.insertArticles(testItem)
        val testFeed = NewsFeed(testArticle.url)
        val feedTestItem = listOf(testFeed)
        dao.insertNewsFeed(feedTestItem)

        val allNewsArticles = dao.getAllNewsArticles().first()

        assertThat(allNewsArticles).contains(testArticle)
    }

    @Test
    fun deleteAllArticles()= runTest {

        val testArticle = NewsArticle("Time traveller claims discovery of mysterious sea creature will change world","https://www.dailystar.co.uk/news/weird-news/time-traveller-claims-discovery-mysterious-28766022","https://i2-prod.dailystar.co.uk/incoming/article28766081.ece/ALTERNATES/s615b/1_A-SELF-proclaimed-time-traveller-from-2198-claims-experts-will-soon-make-a-chilling-ocean-discovery.jpg")
        val testItem = listOf(testArticle)
        dao.insertArticles(testItem)
        val testFeed = NewsFeed(testArticle.url)
        val feedTestItem = listOf(testFeed)
        dao.insertNewsFeed(feedTestItem)

        dao.deleteAllNewsFeed()
        val allArticles = dao.getAllNewsArticles().first()

        assertThat(allArticles).doesNotContain(testArticle)

    }

}```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>TestAppModule.kt

@Module
@InstallIn(SingletonComponent::class)
object TestAppModule {
    @Provides
    @Named("test_db")
    fun provideInMemoryDb(@ApplicationContext context: Context) =
        Room.inMemoryDatabaseBuilder(context,NewsArticleDatabase::class.java )
            .allowMainThreadQueries()
            .build()
}</code>```

gladle(app)
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
    id 'kotlin-parcelize'
    id 'androidx.navigation.safeargs'
}

android {
    compileSdkVersion 33
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.rimapps.wisetest"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"

        //testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        testInstrumentationRunner "com.rimapps.wisetest.HiltTestRunner"

        buildConfigField("String", "NEWS_API_ACCESS_KEY", news_api_access_key)
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
        freeCompilerArgs += "-Xopt-in=androidx.paging.ExperimentalPagingApi"
        freeCompilerArgs += "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    //noinspection GradleDependency
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
    implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'
    testImplementation 'org.junit.jupiter:junit-jupiter'

    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    // Glide
    implementation "com.github.bumptech.glide:glide:4.14.2"

    // Dagger Hilt
    implementation "com.google.dagger:hilt-android:2.44.2"
    kapt "com.google.dagger:hilt-android-compiler:2.44.2"

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'

    // Retrofit + GSON
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"

    // Room
    implementation "androidx.room:room-runtime:2.5.0-rc01"
    kapt "androidx.room:room-compiler:2.5.0-rc01"
    implementation "androidx.room:room-ktx:2.5.0-rc01"

    // SwipeRefreshLayout
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

    // Paging 3
    implementation "androidx.paging:paging-runtime-ktx:3.2.0-alpha03"

    // Fragment
    implementation 'androidx.fragment:fragment-ktx:1.6.0-alpha04'

    // Local Unit Tests
    implementation "androidx.test:core:1.5.0"
    testImplementation "junit:junit:4.13.2"
    testImplementation "org.hamcrest:hamcrest-all:1.3"
    testImplementation "androidx.arch.core:core-testing:2.1.0"
    testImplementation "org.robolectric:robolectric:4.3.1"
    testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
    testImplementation "com.google.truth:truth:1.0.1"
    testImplementation "org.mockito:mockito-core:3.4.6"

    // Instrumented Unit Tests
    androidTestImplementation "junit:junit:4.13.2"
    androidTestImplementation "org.mockito:mockito-android:2.25.0"
    androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
    androidTestImplementation "androidx.arch.core:core-testing:2.1.0"
    androidTestImplementation "com.google.truth:truth:1.0.1"
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
    androidTestImplementation "org.mockito:mockito-core:3.4.6"
    androidTestImplementation 'com.google.dagger:hilt-android-testing:2.28-alpha'
    kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.44.2'
    debugImplementation "androidx.fragment:fragment-testing:1.5.5"
}
kapt {
    correctErrorTypes true
}```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>gradle(project)

buildscript {
    ext.kotlin_version = "1.7.20"
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.6.0-alpha04"
        classpath "com.google.dagger:hilt-android-gradle-plugin:2.44.2"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}</code>```

Body:
I was writing unit tests for my room db operations, everything was working great but, I decided to write  and inject the DataBaseBuilder within TestAppModule using Hilt, but seems like I am getting the following error when i run the tests. I also created a custom HiltRunnerClass and used it in gradle as testInstrumentationRunner "com.rimapps.wisetest.HiltTestRunner"
here is full error

error: [Hilt]
  Null element: java.lang.NullPointerException: Null element
    at dagger.hilt.processor.internal.root.AutoValue_Root.<init>(AutoValue_Root.java:19)
    at dagger.hilt.processor.internal.root.Root.createDefaultRoot(Root.java:46)
    at
  [Hilt] Processing did not complete. See error above for details.
1 error

here is the code

HiltTestRunner.kt
class HiltTestRunner:AndroidJUnitRunner() {

    override fun newApplication(
        cl: ClassLoader?,
        className: String?,
        context: Context?
    ): Application {
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }

}

NewsArticleDaoTest.kt
@RunWith(AndroidJUnit4::class)
@SmallTest
@HiltAndroidTest
class NewsArticleDaoTest{

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Inject
    @Named("test_db")
    lateinit var database: NewsArticleDatabase

    //private lateinit var database: NewsArticleDatabase
    private lateinit var dao: NewsArticleDao

    @Before
    fun setup(){
        hiltRule.inject()
        dao = database.newsArticleDao()

//        database = Room.inMemoryDatabaseBuilder(
//            ApplicationProvider.getApplicationContext(),
//            NewsArticleDatabase::class.java
//        ).allowMainThreadQueries().build()
        dao = database.newsArticleDao()

    }

    @After
    fun teardown(){
        database.close()
    }
    @Test
    fun insertNewsArticle() = runTest {
        val testArticle = NewsArticle("Time traveller shares footage from three weeks in the future showing who wins the World Cup","https://www.ladbible.com/sport/time-traveller-who-wins-world-cup-2022-20221128","https://images.ladbible.com/resize?type=webp&quality=70&width=671&fit=contain&gravity=null&dpr=2&url=https://eu-images.contentstack.com/v3/assets/bltcd74acc1d0a99f3a/bltb6064933a4b82b9c/6384c84adb8e364b186bfb6c/Most_prolific_speed_camera_in_the_UK_has_caught_almost_50_000_drivers_this_year_(42).png")
        val testItem = listOf(testArticle)
        dao.insertArticles(testItem)
        val testFeed = NewsFeed(testArticle.url)
        val feedTestItem = listOf(testFeed)
        dao.insertNewsFeed(feedTestItem)

        val allNewsArticles = dao.getAllNewsArticles().first()

        assertThat(allNewsArticles).contains(testArticle)
    }

    @Test
    fun deleteAllArticles()= runTest {

        val testArticle = NewsArticle("Time traveller claims discovery of mysterious sea creature will change world","https://www.dailystar.co.uk/news/weird-news/time-traveller-claims-discovery-mysterious-28766022","https://i2-prod.dailystar.co.uk/incoming/article28766081.ece/ALTERNATES/s615b/1_A-SELF-proclaimed-time-traveller-from-2198-claims-experts-will-soon-make-a-chilling-ocean-discovery.jpg")
        val testItem = listOf(testArticle)
        dao.insertArticles(testItem)
        val testFeed = NewsFeed(testArticle.url)
        val feedTestItem = listOf(testFeed)
        dao.insertNewsFeed(feedTestItem)

        dao.deleteAllNewsFeed()
        val allArticles = dao.getAllNewsArticles().first()

        assertThat(allArticles).doesNotContain(testArticle)

    }

}

TestAppModule.kt

@Module
@InstallIn(SingletonComponent::class)
object TestAppModule {
    @Provides
    @Named("test_db")
    fun provideInMemoryDb(@ApplicationContext context: Context) =
        Room.inMemoryDatabaseBuilder(context,NewsArticleDatabase::class.java )
            .allowMainThreadQueries()
            .build()
}

gladle(app)
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
    id 'kotlin-parcelize'
    id 'androidx.navigation.safeargs'
}

android {
    compileSdkVersion 33
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.rimapps.wisetest"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"

        //testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        testInstrumentationRunner "com.rimapps.wisetest.HiltTestRunner"

        buildConfigField("String", "NEWS_API_ACCESS_KEY", news_api_access_key)
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
        freeCompilerArgs += "-Xopt-in=androidx.paging.ExperimentalPagingApi"
        freeCompilerArgs += "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    //noinspection GradleDependency
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
    implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'
    testImplementation 'org.junit.jupiter:junit-jupiter'

    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    // Glide
    implementation "com.github.bumptech.glide:glide:4.14.2"

    // Dagger Hilt
    implementation "com.google.dagger:hilt-android:2.44.2"
    kapt "com.google.dagger:hilt-android-compiler:2.44.2"

    // Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'

    // Retrofit + GSON
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"

    // Room
    implementation "androidx.room:room-runtime:2.5.0-rc01"
    kapt "androidx.room:room-compiler:2.5.0-rc01"
    implementation "androidx.room:room-ktx:2.5.0-rc01"

    // SwipeRefreshLayout
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

    // Paging 3
    implementation "androidx.paging:paging-runtime-ktx:3.2.0-alpha03"

    // Fragment
    implementation 'androidx.fragment:fragment-ktx:1.6.0-alpha04'

    // Local Unit Tests
    implementation "androidx.test:core:1.5.0"
    testImplementation "junit:junit:4.13.2"
    testImplementation "org.hamcrest:hamcrest-all:1.3"
    testImplementation "androidx.arch.core:core-testing:2.1.0"
    testImplementation "org.robolectric:robolectric:4.3.1"
    testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
    testImplementation "com.google.truth:truth:1.0.1"
    testImplementation "org.mockito:mockito-core:3.4.6"

    // Instrumented Unit Tests
    androidTestImplementation "junit:junit:4.13.2"
    androidTestImplementation "org.mockito:mockito-android:2.25.0"
    androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
    androidTestImplementation "androidx.arch.core:core-testing:2.1.0"
    androidTestImplementation "com.google.truth:truth:1.0.1"
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
    androidTestImplementation "org.mockito:mockito-core:3.4.6"
    androidTestImplementation 'com.google.dagger:hilt-android-testing:2.28-alpha'
    kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.44.2'
    debugImplementation "androidx.fragment:fragment-testing:1.5.5"
}
kapt {
    correctErrorTypes true
}

gradle(project)

buildscript {
    ext.kotlin_version = "1.7.20"
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.3.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.6.0-alpha04"
        classpath "com.google.dagger:hilt-android-gradle-plugin:2.44.2"
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Python strings assignment
I know that Python strings are immutable.
I was wondering if there was a more memory efficient in doing this (grid is a 2d list) instead of having to create a whole other list and copying everything over.

```<code>def replace(grid, firstchar, secondchar):
    for row in range(len(grid)):
        for col in range(len(grid[row])):
            if grid[row][col] == firstchar:
                grid[row][col] = secondchar
</code>```

Tried implementing .join()

Title: Python strings assignment

Body:
I know that Python strings are immutable.
I was wondering if there was a more memory efficient in doing this (grid is a 2d list) instead of having to create a whole other list and copying everything over.

def replace(grid, firstchar, secondchar):
    for row in range(len(grid)):
        for col in range(len(grid[row])):
            if grid[row][col] == firstchar:
                grid[row][col] = secondchar

Tried implementing .join()


问:
Framework import into Swift + Expo cocoapod doesn't find the header
So I have an expo project, which is my main root. I have some native code nested into the project written in Swift and the Expo Module lib. All works fine until I try to import a Framework into it that sits inside the native module.

ExpoApp (with podfile)

NativeModule in swift - (with podspec)

Framework containing header files written in objectC

When I run expo run:ios I get the following error:

```<code>#import <XFramework/XDefines.h>
     |         ^ 'XFramework/XDefines.h' file not found
</code>```

In the framework I have an umbrella header that imports all the headers with the same namespaces address. This error is coming from one of the other headers.

Is this something that I can set in the NativeModule's podspec?

Tried to add USER_HEADER_SEARCH_PATHS to the podspec in the NativeModule.

Body:
So I have an expo project, which is my main root. I have some native code nested into the project written in Swift and the Expo Module lib. All works fine until I try to import a Framework into it that sits inside the native module.

ExpoApp (with podfile)

NativeModule in swift - (with podspec)

Framework containing header files written in objectC

When I run expo run:ios I get the following error:

#import <XFramework/XDefines.h>
     |         ^ 'XFramework/XDefines.h' file not found

In the framework I have an umbrella header that imports all the headers with the same namespaces address. This error is coming from one of the other headers.

Is this something that I can set in the NativeModule's podspec?

Tried to add USER_HEADER_SEARCH_PATHS to the podspec in the NativeModule.


问:
How can I simplify the fields january_cost to december_cost with an array?
I am using Python with Django and PostGres db. Is there a way to make my 12 rows into 1 ?

I tried to use ArrayField from django.contrib... but the result was not relevant.

```<code>class Services(models.Model):
    po = models.CharField(max_length=15, unique=True, verbose_name="Purchase_Order")
    type_of_services = models.CharField(max_length=80)
    slug = models.SlugField(max_length=80, unique=True, blank=True)
    opex = models.BooleanField(default=True)
    capex = models.BooleanField(default=False)
    mrc = models.BooleanField(default=False)
    annual_cost = models.FloatField()
    january_cost = models.FloatField(default=0)
    february_cost = models.FloatField(default=0)
    march_cost = models.FloatField(default=0)
    april_cost = models.FloatField(default=0)
    may_cost = models.FloatField(default=0)
    june_cost = models.FloatField(default=0)
    july_cost = models.FloatField(default=0)
    august_cost = models.FloatField(default=0)
    september_cost = models.FloatField(default=0)
    october_cost = models.FloatField(default=0)
    november_cost = models.FloatField(default=0)
    december_cost = models.FloatField(default=0)
    last_updated = models.DateField(auto_now=True)
    created_on = models.DateField(blank=True, null=True)
    fiscal_year = models.IntegerField()
    invest_month = models.IntegerField(choices=MonthT, verbose_name="Month starting point in the financial year")
    idSuppliers = models.ForeignKey(Suppliers, on_delete=models.SET_NULL, null=True, blank=True)
    note = models.TextField(default="none", max_length=2048)

</code>```

Body:
I am using Python with Django and PostGres db. Is there a way to make my 12 rows into 1 ?

I tried to use ArrayField from django.contrib... but the result was not relevant.

class Services(models.Model):
    po = models.CharField(max_length=15, unique=True, verbose_name="Purchase_Order")
    type_of_services = models.CharField(max_length=80)
    slug = models.SlugField(max_length=80, unique=True, blank=True)
    opex = models.BooleanField(default=True)
    capex = models.BooleanField(default=False)
    mrc = models.BooleanField(default=False)
    annual_cost = models.FloatField()
    january_cost = models.FloatField(default=0)
    february_cost = models.FloatField(default=0)
    march_cost = models.FloatField(default=0)
    april_cost = models.FloatField(default=0)
    may_cost = models.FloatField(default=0)
    june_cost = models.FloatField(default=0)
    july_cost = models.FloatField(default=0)
    august_cost = models.FloatField(default=0)
    september_cost = models.FloatField(default=0)
    october_cost = models.FloatField(default=0)
    november_cost = models.FloatField(default=0)
    december_cost = models.FloatField(default=0)
    last_updated = models.DateField(auto_now=True)
    created_on = models.DateField(blank=True, null=True)
    fiscal_year = models.IntegerField()
    invest_month = models.IntegerField(choices=MonthT, verbose_name="Month starting point in the financial year")
    idSuppliers = models.ForeignKey(Suppliers, on_delete=models.SET_NULL, null=True, blank=True)
    note = models.TextField(default="none", max_length=2048)


问:
using onclck to pass button id and using switch case to determine what to do based on the button clicked. what should this code look like?
Looking for sample code to capture a button id, pass it to a jscript function and use one of many switch case statements based on the button clicked (id).

Looking for sample code.


问:
Are there anyways to write an integer to a file in MIPS?
I had an assignment and I almost completed. But I found it tough to write integer to a file in MIPS. Are there anyways to write Int to a file in MIPS?</p>


问:
Can I easily port a Rails API to use GrahQL?
I'm building a project where there's an already implemented REST API running in Rails but we want to start using GraphQL. I'm using the 'graphql' gem but everywhere I look seems to imply that I should implement everything all over again in GraphQL, is that so or is there a way to tell GraphQL to use the Rails controllers?

I have queries working but by implementing them straight in GraphQL, I have looked a lot of places but some of the workarounds don't seem to work.

For example:

module Types
  class QueryType < Types::BaseObject
    include GraphQL::Types::Relay::HasNodeField
    include GraphQL::Types::Relay::HasNodesField

    # Add root-level fields here.
    # They will be entry points for queries on your schema.
    field :users, [Types::UserType]

    def users
      User.all
    end

  end
end
```

Is there a way to use something like users#index for example?

Body:
I'm building a project where there's an already implemented REST API running in Rails but we want to start using GraphQL. I'm using the 'graphql' gem but everywhere I look seems to imply that I should implement everything all over again in GraphQL, is that so or is there a way to tell GraphQL to use the Rails controllers?

I have queries working but by implementing them straight in GraphQL, I have looked a lot of places but some of the workarounds don't seem to work.

For example:

module Types
  class QueryType < Types::BaseObject
    include GraphQL::Types::Relay::HasNodeField
    include GraphQL::Types::Relay::HasNodesField

    # Add root-level fields here.
    # They will be entry points for queries on your schema.
    field :users, [Types::UserType]

    def users
      User.all
    end

  end
end

Is there a way to use something like users#index for example?