问:
Processing speed changes turtle animation speed
I was learning python turtle module.

And I was trying to make a simple pong game.

Here is the code:

```<code>import turtle
import win32api

wind = turtle.Screen()
wind.title("Pong game")
wind.bgcolor("black")
wind.setup(width=800, height=500)
wind.tracer(0) # stops window from updating automaticly

# racket1
racket1 = turtle.Turtle()
racket1.speed(0)
racket1.penup()
racket1.color("blue")
racket1.shape("square")
racket1.goto(-370, 0)
racket1.shapesize(stretch_wid=5, stretch_len=1)

# racket2
racket2 = turtle.Turtle()
racket2.speed(0)
racket2.penup()
racket2.color("red")
racket2.shape("square")
racket2.goto(370, 0)
racket2.shapesize(stretch_wid=5, stretch_len=1)

# ball
ball = turtle.Turtle()
ball.speed(0)
ball.penup()
ball.color("white")
ball.shape("circle")
ball.goto(0, 0)
ball.dx = 0.2
ball.dy = 0.2

# score writer
scw = turtle.Turtle()
scw.penup()
scw.speed(0)
scw.hideturtle()
scw.goto(0, 210)
scw.color("white")
scw.write("Blue: 0                  Red: 0", font=("Arial", 24, "bold"), align="center")

# racket 1 functions
def racket1_up():
  y = racket1.ycor()
  if y < 200:
    y += 0.3
    racket1.sety(y)

def racket1_down():
  y = racket1.ycor()
  if y > -200:
    y -= 0.3
    racket1.sety(y)

# racket 2 functions
def racket2_up():
  y = racket2.ycor()
  if y < 200:
    y += 0.3
    racket2.sety(y)

def racket2_down():
  y = racket2.ycor()
  if y > -200:
    y -= 0.3
    racket2.sety(y)

# scores
p1 = 0
p2 = 0

while True:
  wind.update()

  # ball move
  ball.setx(ball.xcor() + ball.dx)
  ball.sety(ball.ycor() + ball.dy)

  # border check
  if ball.ycor() > 239: #240
    ball.dy *= -1

  if ball.ycor() < -239: #-240
    ball.dy *= -1

  if ball.xcor() > 389: #390
    ball.goto(0, 0)
    p1 += 1
    ball.dx *= -1
    scw.clear()
    scw.write(f"Blue: {p1}                  Red: {p2}", font=("Arial", 24, "bold"), align="center")

  if ball.xcor() < -389: #-390
    ball.goto(0, 0)
    p2 += 1
    ball.dx *= -1
    scw.clear()
    scw.write(f"Blue: {p1}                  Red: {p2}", font=("Arial", 24, "bold"), align="center")

  # ball and madareb collision
  if ball.xcor() > 350 and ball.ycor() < racket2.ycor()+60 and ball.ycor() > racket2.ycor()-60:
    ball.dx *= -1

  if ball.xcor() < -350 and ball.ycor() < racket1.ycor()+60 and ball.ycor() > racket1.ycor()-60:
    ball.dx *= -1

  # racket 1 movement
  w = win32api.GetKeyState(0x57)
  s = win32api.GetKeyState(0x53)

  if w < 0:
    racket1_up()
  if s < 0:
    racket1_down()

  # racket 2 movement
  u = win32api.GetKeyState(0x26)
  d = win32api.GetKeyState(0x28)

  if u < 0:
    racket2_up()
  if d < 0:
    racket2_down()
</code>```

The game worked properly but the ball speed changes, I think that this is due to the change of the processing speed changes.

So is it possible to make the speed not change with the changing of the processing speed?

Body:
I was learning python turtle module.

And I was trying to make a simple pong game.

Here is the code:

import turtle
import win32api

wind = turtle.Screen()
wind.title("Pong game")
wind.bgcolor("black")
wind.setup(width=800, height=500)
wind.tracer(0) # stops window from updating automaticly

# racket1
racket1 = turtle.Turtle()
racket1.speed(0)
racket1.penup()
racket1.color("blue")
racket1.shape("square")
racket1.goto(-370, 0)
racket1.shapesize(stretch_wid=5, stretch_len=1)

# racket2
racket2 = turtle.Turtle()
racket2.speed(0)
racket2.penup()
racket2.color("red")
racket2.shape("square")
racket2.goto(370, 0)
racket2.shapesize(stretch_wid=5, stretch_len=1)

# ball
ball = turtle.Turtle()
ball.speed(0)
ball.penup()
ball.color("white")
ball.shape("circle")
ball.goto(0, 0)
ball.dx = 0.2
ball.dy = 0.2

# score writer
scw = turtle.Turtle()
scw.penup()
scw.speed(0)
scw.hideturtle()
scw.goto(0, 210)
scw.color("white")
scw.write("Blue: 0                  Red: 0", font=("Arial", 24, "bold"), align="center")

# racket 1 functions
def racket1_up():
  y = racket1.ycor()
  if y < 200:
    y += 0.3
    racket1.sety(y)

def racket1_down():
  y = racket1.ycor()
  if y > -200:
    y -= 0.3
    racket1.sety(y)

# racket 2 functions
def racket2_up():
  y = racket2.ycor()
  if y < 200:
    y += 0.3
    racket2.sety(y)

def racket2_down():
  y = racket2.ycor()
  if y > -200:
    y -= 0.3
    racket2.sety(y)

# scores
p1 = 0
p2 = 0

while True:
  wind.update()

  # ball move
  ball.setx(ball.xcor() + ball.dx)
  ball.sety(ball.ycor() + ball.dy)

  # border check
  if ball.ycor() > 239: #240
    ball.dy *= -1

  if ball.ycor() < -239: #-240
    ball.dy *= -1

  if ball.xcor() > 389: #390
    ball.goto(0, 0)
    p1 += 1
    ball.dx *= -1
    scw.clear()
    scw.write(f"Blue: {p1}                  Red: {p2}", font=("Arial", 24, "bold"), align="center")

  if ball.xcor() < -389: #-390
    ball.goto(0, 0)
    p2 += 1
    ball.dx *= -1
    scw.clear()
    scw.write(f"Blue: {p1}                  Red: {p2}", font=("Arial", 24, "bold"), align="center")

  # ball and madareb collision
  if ball.xcor() > 350 and ball.ycor() < racket2.ycor()+60 and ball.ycor() > racket2.ycor()-60:
    ball.dx *= -1

  if ball.xcor() < -350 and ball.ycor() < racket1.ycor()+60 and ball.ycor() > racket1.ycor()-60:
    ball.dx *= -1

  # racket 1 movement
  w = win32api.GetKeyState(0x57)
  s = win32api.GetKeyState(0x53)

  if w < 0:
    racket1_up()
  if s < 0:
    racket1_down()

  # racket 2 movement
  u = win32api.GetKeyState(0x26)
  d = win32api.GetKeyState(0x28)

  if u < 0:
    racket2_up()
  if d < 0:
    racket2_down()

The game worked properly but the ball speed changes, I think that this is due to the change of the processing speed changes.

So is it possible to make the speed not change with the changing of the processing speed?


来源: stackexchange

问:
Are binding redirects aka dependentassembly tags ordered
Does the order of the binding redirects in the web.config or app.config file matter?  Or is each considered completely independent of the others?</p>

ContentLicense: CC BY-SA 4.0


问:
putting transform:scale() in js
How would I put

```<code> transform:scale(0.5);
</code>```

in css to javascript

I have tried

```<code>document.getElementById().style.transform = "scale(0.5)";
</code>```

It didn't work.

Title: putting transform:scale() in js

Body:
How would I put

 transform:scale(0.5);

in css to javascript

I have tried

document.getElementById().style.transform = "scale(0.5)";

It didn't work.


问:
Authenticate using your email OR username in Firebase authentication system
I am having a hard time in integrating the username as another way for the users to login in firebase. Is there a way for me to do that or am I stuck with only using .signInWithEmailAndPassword? I have read one of a document from firebase regarding signing in with custom token but not really sure if my understanding about it is correct.

```<code>const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [error, setError] = useState(null);
  const navigate = useNavigate();
  const user = useSelector((state) => state.user);
  const handleEmailChange = (event) => {
    setEmail(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    firebase
      .auth()
       /*I have a feeling i need to have this changed*/
      .signInWithEmailAndPassword(email, password) || .signInWithEmailAndPassword(email, password)
      .catch((error) => {
        setError(error.message);
      });
  };

  useEffect(() => {
    if (user) {
      // if user is logged in, redirect to home page
      navigate('/');
    }
  }, [user]);

</code>```

I hope you can help. Your advice would be greatly appreciated!

Body:
I am having a hard time in integrating the username as another way for the users to login in firebase. Is there a way for me to do that or am I stuck with only using .signInWithEmailAndPassword? I have read one of a document from firebase regarding signing in with custom token but not really sure if my understanding about it is correct.

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [error, setError] = useState(null);
  const navigate = useNavigate();
  const user = useSelector((state) => state.user);
  const handleEmailChange = (event) => {
    setEmail(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    firebase
      .auth()
       /*I have a feeling i need to have this changed*/
      .signInWithEmailAndPassword(email, password) || .signInWithEmailAndPassword(email, password)
      .catch((error) => {
        setError(error.message);
      });
  };

  useEffect(() => {
    if (user) {
      // if user is logged in, redirect to home page
      navigate('/');
    }
  }, [user]);

I hope you can help. Your advice would be greatly appreciated!


问:
Maximum Average Subarray I
Problem Description: Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value

My Solution:

```<code>    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """

        curr = 0

        #get average of the first window
        for i in range(k):
            curr+=nums[i]
        ans = curr

        #slide window to find largest sum
        for i in range(k, len(nums)):
            curr+=nums[i]-nums[i-k]
            ans = max(curr, ans)

        #return the largest sum divided by k to get the max average
        return ans/k

</code>```

When I submit my answer, the output seems to be rounded down even though I'm using a single division operator? For example, for the test case...

nums = [1,12,-5,-6,50,3], k = 4

The answer should be 12.75, but my output is 12.00

Title: Maximum Average Subarray I

Body:
Problem Description: Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value

My Solution:

    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """

        curr = 0

        #get average of the first window
        for i in range(k):
            curr+=nums[i]
        ans = curr

        #slide window to find largest sum
        for i in range(k, len(nums)):
            curr+=nums[i]-nums[i-k]
            ans = max(curr, ans)

        #return the largest sum divided by k to get the max average
        return ans/k

When I submit my answer, the output seems to be rounded down even though I'm using a single division operator? For example, for the test case...

nums = [1,12,-5,-6,50,3], k = 4

The answer should be 12.75, but my output is 12.00


问:
How to load a saved model for a Hoggingface T5 model where the tokenizer was extended in the training phase?
I use the following code to load the saved model:

```<code> config = T5Config.from_pretrained(
        model_name_or_path,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )
    config.train_task_adapters = adapter_args.train_task_adapters
 # Set tokenizer
    tokenizer = AutoTokenizer.from_pretrained(
        model_name_or_path,
        cache_dir=model_args.cache_dir,
        use_fast=model_args.use_fast_tokenizer,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )

    # Initialize the model
    model = T5ForConditionalGeneration.from_pretrained(
        model_name_or_path,
        from_tf=bool(".ckpt" in model_name_or_path),
        config=config,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
        adapter_config=adapter_config
    )
</code>```

However I recieive the following error:

```<code>RuntimeError: Error(s) in loading state_dict for T5ForConditionalGeneration:
    size mismatch for encoder.model_embeddings.weight: copying a param with shape torch.Size([32128, 768]) from checkpoint, the shape in current model is torch.Size([32138, 768]).
    size mismatch for decoder.model_embeddings.weight: copying a param with shape torch.Size([32128, 768]) from checkpoint, the shape in current model is torch.Size([32138, 768]).
exit 1
</code>```

Body:
I use the following code to load the saved model:

 config = T5Config.from_pretrained(
        model_name_or_path,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )
    config.train_task_adapters = adapter_args.train_task_adapters
 # Set tokenizer
    tokenizer = AutoTokenizer.from_pretrained(
        model_name_or_path,
        cache_dir=model_args.cache_dir,
        use_fast=model_args.use_fast_tokenizer,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )

    # Initialize the model
    model = T5ForConditionalGeneration.from_pretrained(
        model_name_or_path,
        from_tf=bool(".ckpt" in model_name_or_path),
        config=config,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
        adapter_config=adapter_config
    )

However I recieive the following error:

RuntimeError: Error(s) in loading state_dict for T5ForConditionalGeneration:
    size mismatch for encoder.model_embeddings.weight: copying a param with shape torch.Size([32128, 768]) from checkpoint, the shape in current model is torch.Size([32138, 768]).
    size mismatch for decoder.model_embeddings.weight: copying a param with shape torch.Size([32128, 768]) from checkpoint, the shape in current model is torch.Size([32138, 768]).
exit 1


问:
CoreMIDI MIDIInputPortCreateWithProtocol problem with more than 2 keys pressed
I'm studying CoreMIDI to connect a musical keyboard to get keys pressed and mount chord.

After few days I don't know why sometimes the block from MIDIInputPortCreateWithProtocol not receive some events.

For example:

If I press one key an release it, the events received normally.

If I press two keys simultaneously sometimes I receive two events with one packet in each one or receive one event with two packets, but sometimes one key event pressed not reach the block, registering just one key pressed or released.

If I press three key normally one event or one packet from one key not reach the block

But when I press one key separately and not release it I receive all keys pressed.

My MIDIInputPortCreateWithProtocol code is

```<code>func createInputPort(midiClient: MIDIClientRef) {
        MIDIInputPortCreateWithProtocol(midiClient, "Input Port" as CFString, MIDIProtocolID._1_0, &self.inputPort) {  [weak self] eventList, srcConnRefCon in
            print("=== event received")

            guard let strogSelf = self else {
                return
            }

            let midiEventList: MIDIEventList = eventList.pointee
            var packet = midiEventList.packet

            for _ in 1...midiEventList.numPackets {
                let words = Mirror(reflecting: packet.words).children
                for word in words {
                    guard let uint32 = word.value as? UInt32,
                          uint32 > 0 else { return }

                    let messageType = (uint32 & 0xF0000000) >> 28

                    if (messageType == 0x02) {
                        let status = (uint32 & 0x00FF0000) >> 16
                        let midiCommand = status >> 4
                        if midiCommand == strogSelf.NOTE_ON {
                            strogSelf.noteAdd(noteInfo: MidiPacket(data: uint32, command: midiCommand, timeStamp: packet.timeStamp))
                            break
                        } else if midiCommand == strogSelf.NOTE_OFF {
                            strogSelf.noteRemove(noteInfo: MidiPacket(data: uint32, command: midiCommand, timeStamp: packet.timeStamp))
                            break
                        }
                    }
                }
                packet = MIDIEventPacketNext(&packet).pointee
            }
        }

        MIDIPortConnectSource(self.inputPort, self.endpoint ?? MIDIGetSource(MIDIGetNumberOfSources()-1), &self.connRefCon)
}
</code>```

The ideia is receive all key pressed like in garageband.

If I open garageband together with my project, when I press three keys simultaneously the garage band detect all of them and my project sometimes not.

Anyone have some ideia what is happen here?

Thanks a lot

Body:
I'm studying CoreMIDI to connect a musical keyboard to get keys pressed and mount chord.

After few days I don't know why sometimes the block from MIDIInputPortCreateWithProtocol not receive some events.

For example:

If I press one key an release it, the events received normally.

If I press two keys simultaneously sometimes I receive two events with one packet in each one or receive one event with two packets, but sometimes one key event pressed not reach the block, registering just one key pressed or released.

If I press three key normally one event or one packet from one key not reach the block

But when I press one key separately and not release it I receive all keys pressed.

My MIDIInputPortCreateWithProtocol code is

func createInputPort(midiClient: MIDIClientRef) {
        MIDIInputPortCreateWithProtocol(midiClient, "Input Port" as CFString, MIDIProtocolID._1_0, &self.inputPort) {  [weak self] eventList, srcConnRefCon in
            print("=== event received")

            guard let strogSelf = self else {
                return
            }

            let midiEventList: MIDIEventList = eventList.pointee
            var packet = midiEventList.packet

            for _ in 1...midiEventList.numPackets {
                let words = Mirror(reflecting: packet.words).children
                for word in words {
                    guard let uint32 = word.value as? UInt32,
                          uint32 > 0 else { return }

                    let messageType = (uint32 & 0xF0000000) >> 28

                    if (messageType == 0x02) {
                        let status = (uint32 & 0x00FF0000) >> 16
                        let midiCommand = status >> 4
                        if midiCommand == strogSelf.NOTE_ON {
                            strogSelf.noteAdd(noteInfo: MidiPacket(data: uint32, command: midiCommand, timeStamp: packet.timeStamp))
                            break
                        } else if midiCommand == strogSelf.NOTE_OFF {
                            strogSelf.noteRemove(noteInfo: MidiPacket(data: uint32, command: midiCommand, timeStamp: packet.timeStamp))
                            break
                        }
                    }
                }
                packet = MIDIEventPacketNext(&packet).pointee
            }
        }

        MIDIPortConnectSource(self.inputPort, self.endpoint ?? MIDIGetSource(MIDIGetNumberOfSources()-1), &self.connRefCon)
}

The ideia is receive all key pressed like in garageband.

If I open garageband together with my project, when I press three keys simultaneously the garage band detect all of them and my project sometimes not.

Anyone have some ideia what is happen here?

Thanks a lot


问:
ASP.NET Core 6 / Entity Framework Core: relationships don't work
I can't deal with this problem and I hope you can help me.

I have two models User and Friendship. In Friendship if I relate to RequestUser or ReceiveUser, I get the correct data.

But RequestedFriendships and ReceivedFriendships in User is always null (there are rows in the database that should correlate with these lists). Is it possible at all to achieve that?

```<code>public class User
{
    public int Id { get; set; }
    public string? Email { get; set; }
    public string? Password { get; set; }

    public virtual ICollection<Friendship> RequestedFriendships { get; set; }
    public virtual ICollection<Friendship> ReceivedFriendships { get; set; }
}

public class Friendship
{
    public int Id { get; set; }

    public int? RequestUserId { get; set; }
    public int? ReceiveUserId { get; set; }

    public FriendshipStatus Status { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime? UpdatedDate { get; set; }
    public virtual User RequestUser { get; set; }
    public virtual User ReceiveUser { get; set; }
}
</code>```
```<code>modelBuilder.Entity<Friendship>()
            .HasOne(f => f.RequestUser)
            .WithMany(u => u.RequestedFriendships)
            .HasForeignKey(f => f.RequestUserId)
            .OnDelete(DeleteBehavior.ClientSetNull);

modelBuilder.Entity<Friendship>()
            .HasOne(f => f.ReceiveUser)
            .WithMany(u => u.ReceivedFriendships)
            .HasForeignKey(f => f.ReceiveUserId)
            .OnDelete(DeleteBehavior.ClientSetNull);
</code>```

This is my code for now.

Body:
I can't deal with this problem and I hope you can help me.

I have two models User and Friendship. In Friendship if I relate to RequestUser or ReceiveUser, I get the correct data.

But RequestedFriendships and ReceivedFriendships in User is always null (there are rows in the database that should correlate with these lists). Is it possible at all to achieve that?

public class User
{
    public int Id { get; set; }
    public string? Email { get; set; }
    public string? Password { get; set; }

    public virtual ICollection<Friendship> RequestedFriendships { get; set; }
    public virtual ICollection<Friendship> ReceivedFriendships { get; set; }
}

public class Friendship
{
    public int Id { get; set; }

    public int? RequestUserId { get; set; }
    public int? ReceiveUserId { get; set; }

    public FriendshipStatus Status { get; set; }
    public DateTime CreationDate { get; set; }
    public DateTime? UpdatedDate { get; set; }
    public virtual User RequestUser { get; set; }
    public virtual User ReceiveUser { get; set; }
}

modelBuilder.Entity<Friendship>()
            .HasOne(f => f.RequestUser)
            .WithMany(u => u.RequestedFriendships)
            .HasForeignKey(f => f.RequestUserId)
            .OnDelete(DeleteBehavior.ClientSetNull);

modelBuilder.Entity<Friendship>()
            .HasOne(f => f.ReceiveUser)
            .WithMany(u => u.ReceivedFriendships)
            .HasForeignKey(f => f.ReceiveUserId)
            .OnDelete(DeleteBehavior.ClientSetNull);

This is my code for now.


问:
Ionic MediaCapture : Types of parameters 'data' and 'value' are incompatible
I've been trying to capture images on my ionic android application.
I need to capture many images, like one or two per seconds and use them to feed an algorithm. I can't use the camera plugin since it's only one image at the time.

I'm trying to make MediaCapture works.

I've been using the documentation and links :
https://ionicframework.com/docs/v5/native/media-capture
https://www.ionicanddjangotutorial.com/how-to-capture-multiple-photo-with-ionic-and-capacitor/

They all give the same way to do it :

home.page.ts

```<code>import { Component } from '@angular/core';
import { PhotoService } from '../services/photo.service';

import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@awesome-cordova-plugins/media-capture/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private mediaCapture: MediaCapture) { }

  openCamera(){
    let options: CaptureImageOptions = { limit: 3 }
    this.mediaCapture.captureImage(options).then((data: MediaFile[]) => {
      console.log(data)
    },
    (err: CaptureError) => {
      console.error(err)
    });
  }

}
</code>```

Unfortunately this doesn't seems to work anymore.

```<code>Error: src/app/home/home.page.ts:17:50 - error TS2345: Argument of type '(data: MediaFile[]) => void' is not assignable to parameter of type '(value: MediaFile[] | CaptureError)
=> void | PromiseLike<void>'.
[ng]   Types of parameters 'data' and 'value' are incompatible.
[ng]     Type 'MediaFile[] | CaptureError' is not assignable to type 'MediaFile[]'.
[ng]       Type 'CaptureError' is missing the following properties from type 'MediaFile[]': length, pop, push, concat, and 26 more.
[ng]
[ng] 17     this.mediaCapture.captureImage(options).then((data: MediaFile[]) => {
[ng]                                                     ~~~~~~~~~~~~~~~~~~~~~~~~
[ng]
[ng]
[ng]
[ng] × Failed to compile.
</code>```

Link to the plugin github : https://github.com/apache/cordova-plugin-media-capture

How could I make it work ?

Many thanks

Body:
I've been trying to capture images on my ionic android application.
I need to capture many images, like one or two per seconds and use them to feed an algorithm. I can't use the camera plugin since it's only one image at the time.

I'm trying to make MediaCapture works.

I've been using the documentation and links :
https://ionicframework.com/docs/v5/native/media-capture
https://www.ionicanddjangotutorial.com/how-to-capture-multiple-photo-with-ionic-and-capacitor/

They all give the same way to do it :

home.page.ts

import { Component } from '@angular/core';
import { PhotoService } from '../services/photo.service';

import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@awesome-cordova-plugins/media-capture/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private mediaCapture: MediaCapture) { }

  openCamera(){
    let options: CaptureImageOptions = { limit: 3 }
    this.mediaCapture.captureImage(options).then((data: MediaFile[]) => {
      console.log(data)
    },
    (err: CaptureError) => {
      console.error(err)
    });
  }

}

Unfortunately this doesn't seems to work anymore.

Error: src/app/home/home.page.ts:17:50 - error TS2345: Argument of type '(data: MediaFile[]) => void' is not assignable to parameter of type '(value: MediaFile[] | CaptureError)
=> void | PromiseLike<void>'.
[ng]   Types of parameters 'data' and 'value' are incompatible.
[ng]     Type 'MediaFile[] | CaptureError' is not assignable to type 'MediaFile[]'.
[ng]       Type 'CaptureError' is missing the following properties from type 'MediaFile[]': length, pop, push, concat, and 26 more.
[ng]
[ng] 17     this.mediaCapture.captureImage(options).then((data: MediaFile[]) => {
[ng]                                                     ~~~~~~~~~~~~~~~~~~~~~~~~
[ng]
[ng]
[ng]
[ng] × Failed to compile.

Link to the plugin github : https://github.com/apache/cordova-plugin-media-capture

How could I make it work ?

Many thanks


问:
sqlalchemy MutableList remove() not working
I have a has_bubble_in_countries column in the Subscription model that is an ARRAY of enums:

```<code>has_bubble_in_countries = sa.Column(MutableList.as_mutable(ARRAY(sa.Enum(Country))), nullable=False, default=[])
</code>```

The append() function on it is working, but the remove() function seems that is not consistent and it doesn't actually update its value in the database.

This is how I'm trying to remove an element from it:

```<code>subscription.has_bubble_in_countries.remove(Country.NL)
db.session.commit()
</code>```

Am I doing something wrong or it requires additional implementation of the MutableList class? Or what are the possible reasons that this is not working properly?

Thanks in advance

Body:
I have a has_bubble_in_countries column in the Subscription model that is an ARRAY of enums:

has_bubble_in_countries = sa.Column(MutableList.as_mutable(ARRAY(sa.Enum(Country))), nullable=False, default=[])

The append() function on it is working, but the remove() function seems that is not consistent and it doesn't actually update its value in the database.

This is how I'm trying to remove an element from it:

subscription.has_bubble_in_countries.remove(Country.NL)
db.session.commit()

Am I doing something wrong or it requires additional implementation of the MutableList class? Or what are the possible reasons that this is not working properly?

Thanks in advance


问:
AttributeError: 'GoogleDrive' object has no attribute 'files'
I was running a program where, the code sends a Folder ID, a folder name, an Image name and an Image to a function. The folder ID is the ID of Parent folder. The Folder name is the name of Child folder. The save_image`` code will check if there exist a child folder in the parent by that name and if it does it will save the image with the given name.  However I am getting attribute error. I was using Google Collab while doing this.

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-180-6db51ad10c39> in <module>
----> 1 process_images()

1 frames
<ipython-input-179-3abcafca36b1> in save_image(img_name, subfolder_name, img_data, dataset2_id)
     12
     13             # Send a request to the Drive API to upload the image
---> 14             file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute()
     15
     16             # Print a message to confirm that the file was saved

AttributeError: 'GoogleDrive' object has no attribute 'files'
</code>```

One of the solutions present was using path, however, that is out of the question for this code. The aim of this code is to read a dataset, modify it and paste the modified dataset in a separate folder using the same structure and name. Hence the folder where dataset is and where the dataset can be stored is known. However, for the child folder it will change depending on image. For image A01.png in Folder A inside Dataset, it's modified image is sent as img_data, while its name and name of folder A is sent to this save_image function. It will be stored in A folder inside Dataset2 folder as A01.png. That was my plan. The rest of the code is working fine. Its creating all the child folders, accessing all the images, modifying the images as needed. However, saving them is where I am stuck at.

```<code>def save_image(img_name, subfolder_name, img_data, dataset2_id):
    drive = GoogleDrive(gauth)
    dataset2_file_list = drive.ListFile({'q': f"'{dataset2_id}' in parents and trashed = false"}).GetList()
    # Iterate through the subfolders in the Dataset2 folder
    for subfolder in dataset2_file_list:
        # Check if the subfolder name matches the name of the subfolder in the Dataset folder
        if subfolder['title'] == subfolder_name:
            # Get the ID of the subfolder
            subfolder_id = subfolder.metadata['id']
            # Create the file metadata
            file_metadata = {'name': img_name, 'parents': [subfolder_id]}

            # Send a request to the Drive API to upload the image
            file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute()

            # Print a message to confirm that the file was saved
            print(f'File ID: {file.get("id")}')
</code>```

The issue is only in this region. It is getting proper string inputs. Other then the image which is numpy array all the other parameters are string variable in the function.

One solution suggested to add the following line. As you can see in this code, I already implemented that. It didn't work

Here is all my imports

```<code># Install the PyDrive wrapper & import libraries.
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
import io
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, toolsd

import cv2
from matplotlib.image import imread
import matplotlib.pyplot as plt
import numpy as np
import requests
from imhist import imhist, imcdf
from scipy.fftpack import fft2, ifft2
from skimage import filters
from mpl_toolkits.mplot3d import Axes3D
</code>```

Body:
I was running a program where, the code sends a Folder ID, a folder name, an Image name and an Image to a function. The folder ID is the ID of Parent folder. The Folder name is the name of Child folder. The save_image`` code will check if there exist a child folder in the parent by that name and if it does it will save the image with the given name.  However I am getting attribute error. I was using Google Collab while doing this.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-180-6db51ad10c39> in <module>
----> 1 process_images()

1 frames
<ipython-input-179-3abcafca36b1> in save_image(img_name, subfolder_name, img_data, dataset2_id)
     12
     13             # Send a request to the Drive API to upload the image
---> 14             file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute()
     15
     16             # Print a message to confirm that the file was saved

AttributeError: 'GoogleDrive' object has no attribute 'files'

One of the solutions present was using path, however, that is out of the question for this code. The aim of this code is to read a dataset, modify it and paste the modified dataset in a separate folder using the same structure and name. Hence the folder where dataset is and where the dataset can be stored is known. However, for the child folder it will change depending on image. For image A01.png in Folder A inside Dataset, it's modified image is sent as img_data, while its name and name of folder A is sent to this save_image function. It will be stored in A folder inside Dataset2 folder as A01.png. That was my plan. The rest of the code is working fine. Its creating all the child folders, accessing all the images, modifying the images as needed. However, saving them is where I am stuck at.

def save_image(img_name, subfolder_name, img_data, dataset2_id):
    drive = GoogleDrive(gauth)
    dataset2_file_list = drive.ListFile({'q': f"'{dataset2_id}' in parents and trashed = false"}).GetList()
    # Iterate through the subfolders in the Dataset2 folder
    for subfolder in dataset2_file_list:
        # Check if the subfolder name matches the name of the subfolder in the Dataset folder
        if subfolder['title'] == subfolder_name:
            # Get the ID of the subfolder
            subfolder_id = subfolder.metadata['id']
            # Create the file metadata
            file_metadata = {'name': img_name, 'parents': [subfolder_id]}

            # Send a request to the Drive API to upload the image
            file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute()

            # Print a message to confirm that the file was saved
            print(f'File ID: {file.get("id")}')

The issue is only in this region. It is getting proper string inputs. Other then the image which is numpy array all the other parameters are string variable in the function.

One solution suggested to add the following line. As you can see in this code, I already implemented that. It didn't work

Here is all my imports

# Install the PyDrive wrapper & import libraries.
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
import io
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, toolsd

import cv2
from matplotlib.image import imread
import matplotlib.pyplot as plt
import numpy as np
import requests
from imhist import imhist, imcdf
from scipy.fftpack import fft2, ifft2
from skimage import filters
from mpl_toolkits.mplot3d import Axes3D


问:
PhantomJS - Download xlsx from site
I need to download a specific file from a website by clicking on the image that fire the javascript event. There is no url link to get the xls file.I'm using phantomjs to do this but i'm not getting.

Below, piece of the code from the site

where src="Resources/WorkWithPlusBootstrapResponsiveTheme/ActionExport.png" is the image that fire the JS event.

I'm trying to use phantojs to that task whit PHP and I'm at linux environment. I am not able to access the element's data from the below code. When I run the command I receive the output below:

Command: //home//cma//TesteJSon//phantomjs --ignore-ssl-errors=true --ssl-protocol=any TesteWiki.js

Output:
Using jquery from GX distr.
global $ is jquery1.9.1
element is [object Object]
[object Object]

Title: PhantomJS - Download xlsx from site


问:
How can i get cardholder name in Laravel Cashier
I am trying to store a card holder name when purchasing a product, it does work however it shows model User name not the actual card holder name that we type in the form, any help please?

name: cardHolderName.value -> shows user model name

```<code>const { setupIntent, error } = await stripe.confirmCardSetup(
            cardButton.dataset.secret, {
                payment_method: {
                    card: cardElement,
                    billing_details: {
                        name: cardHolderName.value
                    }
                }
            }
        )
</code>```

Body:
I am trying to store a card holder name when purchasing a product, it does work however it shows model User name not the actual card holder name that we type in the form, any help please?

name: cardHolderName.value -> shows user model name

const { setupIntent, error } = await stripe.confirmCardSetup(
            cardButton.dataset.secret, {
                payment_method: {
                    card: cardElement,
                    billing_details: {
                        name: cardHolderName.value
                    }
                }
            }
        )


问:
implement ngx-tui-image-editor in angular 13
I am working on angular Application for logo creating and image editor. I have found one working solution https://stackblitz.com/edit/angular-11-new-xuyjtj?file=src%2Fapp%2Fapp.component.ts
which i have download and it works as standalone application.

Now i am trying to merge these two application because i need image editor module in my parent application but i am getting errors specifically inside the the module of tui-image-editor/dist files

Error: node_modules/ngx-tui-image-editor/lib/toast-ui-image-editor.component.d.ts:2:25 - error TS2306: File 'C:/ProgramminCodes/TechnoAdd 12-28-2022/node_modules/tui-image-editor/index.d.ts' is not a module.

./node_modules/tui-image-editor/dist/svg/icon-d.svg:1:0 - Error: Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

error TS2411: Property 'fontFamily' of type 'string | undefined' is not assignable to 'string' index type 'string | number | boolean'.

I have tried to merge the code from both App

first download the application which is built in angular 7 and then copy its specific dependencies filder and pasted in the node module of parent application


问:
Runtime error "Uncaught TypeError: x.inherits is not a function" In angular v15
I using Angular15 to create a website. I can build the project properly. But when I launch localhost:4200 on my browser I am getting following error. This is same for all browsers as well.

```<code>Uncaught TypeError: x.inherits is not a function
    at 9086 (main.js:1:1553548)
    at a (runtime.js:1:143)
    at 9526 (main.js:1:1298648)
    at a (runtime.js:1:143)
    at 5885 (main.js:1:1272423)
    at a (runtime.js:1:143)
    at 9281 (main.js:1:1277111)
    at a (runtime.js:1:143)
    at 1538 (main.js:1:1272278)
    at a (runtime.js:1:143)
</code>```

I tried installing Vita and Snowpack which serves source file over native ES module. Nothing worked. I don't know what is the issue. Please any help is appreciated.

Body:
I using Angular15 to create a website. I can build the project properly. But when I launch localhost:4200 on my browser I am getting following error. This is same for all browsers as well.

Uncaught TypeError: x.inherits is not a function
    at 9086 (main.js:1:1553548)
    at a (runtime.js:1:143)
    at 9526 (main.js:1:1298648)
    at a (runtime.js:1:143)
    at 5885 (main.js:1:1272423)
    at a (runtime.js:1:143)
    at 9281 (main.js:1:1277111)
    at a (runtime.js:1:143)
    at 1538 (main.js:1:1272278)
    at a (runtime.js:1:143)

I tried installing Vita and Snowpack which serves source file over native ES module. Nothing worked. I don't know what is the issue. Please any help is appreciated.


问:
Position: absolute breaks Ionic onChange event
I'm using Ionic's datetime component with an (onChange) event. I'm trying to poistion another component on top of it with position: absolute and z-index. However, if I use position: aboslute anywhere near the component, the event isn't emitted. However, when I remove display: flex from the parent div, the issue goes away. So it's a combination of absolute and flex that's causing this.

```<code><div style="display: flex;">
  <ion-datetime presentation="time"
                minuteValues="0,15,30,45"
                (ionChange)="timeChanged($event)"
                >
  </ion-datetime>
  <div class="card-time-container"
       style="min-width: 30px; margin-left: auto; margin-right: auto;
  position: absolute; z-index: 5;">
    <ion-card class="option-card ion-no-padding ion-no-margin">
      <div class="ion-text-center ion-no-padding">
        <ion-text>:</ion-text>
      </div>
    </ion-card>
  </div>
</div>
</code>```

Body:
I'm using Ionic's datetime component with an (onChange) event. I'm trying to poistion another component on top of it with position: absolute and z-index. However, if I use position: aboslute anywhere near the component, the event isn't emitted. However, when I remove display: flex from the parent div, the issue goes away. So it's a combination of absolute and flex that's causing this.

  <ion-datetime presentation="time"
                minuteValues="0,15,30,45"
                (ionChange)="timeChanged($event)"
                >
  </ion-datetime>

    <ion-card class="option-card ion-no-padding ion-no-margin">

        <ion-text>:</ion-text>

    </ion-card>


问:
videojs player seek buttons works in other browsers but not in chrome. The video starts again on clicking the progress bar
I'm fetching a video from s3 bucket using django(backend) and then playing the video in react (frontend) but the seek controls work in other browsers but not in chrome. The video starts again on clicking the progress bar or clicking the arrow keys. I don't understand what seems to be the problem.

here is my django code for fetching video

```<code>class GenericFileOperation(APIView):
    def get(self, request, material_type=None, course_id=None, format=None):
        key = request.GET.get('key')
        download = request.GET.get('download')

        if key is not None:
            s3_obj = download_assessment_file(key)
            splited_path = key.split("/")
            file_name = splited_path[len(splited_path)-1]
            contents = s3_obj['Body'].read()
            temp = tempfile.TemporaryFile()
            temp.write(contents)
            temp.seek(0)
            mime_type, _ = mimetypes.guess_type(key)
            response = HttpResponse(temp, content_type=mime_type)
            if download is not None:
                response['Content-Disposition'] = "attachment; filename=%s" % (
                    file_name)
            response['X-Frame-Options'] = "*"
            return response
</code>```

here is my code for videojs in react

```<code>import React, { useEffect, useRef } from 'react'
import VideoJs from 'video.js'
import 'video.js/dist/video-js.css';
import "videojs-hotkeys";
import 'videojs-seek-buttons'

const videoJsOptions = {
    controls: true,
    autoplay: false,
    fluid: true,
    loop: false,
    playbackRates: [0.5, 1, 1.5, 2],
    aspectRatio: '12:5',
    plugins: {
        seekButtons: {
            forward: 30,
            back: 10
        },
        hotkeys: {}
    }
}

const VideoPlayer = ({ url, fileType }) => {
    const videoContainer = useRef()

    useEffect(() => {
        videoContainer.current.innerHTML = `
      <div data-vjs-player>
        <video data-setup='{"fluid": true, "autoplay":true,"html5": {"vhs":
        {"overrideNative": true}, "nativeAudioTracks": false, "nativeVideoTracks": false}}' class="video-js" />
      </div>
    `

        const player = VideoJs(videoContainer.current.querySelector('video'), videoJsOptions, async () => {
            player.src({ src: url, type: fileType })
        })

        //  When destruct dispose the player
        return () => player.dispose()
    }, [url, fileType])

    return <div ref={videoContainer} />
}

export default VideoPlayer
</code>```

Thank you in advance

I tried using different plugins of videojs but nothing solves the problem. Please help if you have any idea

Body:
I'm fetching a video from s3 bucket using django(backend) and then playing the video in react (frontend) but the seek controls work in other browsers but not in chrome. The video starts again on clicking the progress bar or clicking the arrow keys. I don't understand what seems to be the problem.

here is my django code for fetching video

class GenericFileOperation(APIView):
    def get(self, request, material_type=None, course_id=None, format=None):
        key = request.GET.get('key')
        download = request.GET.get('download')

        if key is not None:
            s3_obj = download_assessment_file(key)
            splited_path = key.split("/")
            file_name = splited_path[len(splited_path)-1]
            contents = s3_obj['Body'].read()
            temp = tempfile.TemporaryFile()
            temp.write(contents)
            temp.seek(0)
            mime_type, _ = mimetypes.guess_type(key)
            response = HttpResponse(temp, content_type=mime_type)
            if download is not None:
                response['Content-Disposition'] = "attachment; filename=%s" % (
                    file_name)
            response['X-Frame-Options'] = "*"
            return response

here is my code for videojs in react

import React, { useEffect, useRef } from 'react'
import VideoJs from 'video.js'
import 'video.js/dist/video-js.css';
import "videojs-hotkeys";
import 'videojs-seek-buttons'

const videoJsOptions = {
    controls: true,
    autoplay: false,
    fluid: true,
    loop: false,
    playbackRates: [0.5, 1, 1.5, 2],
    aspectRatio: '12:5',
    plugins: {
        seekButtons: {
            forward: 30,
            back: 10
        },
        hotkeys: {}
    }
}

const VideoPlayer = ({ url, fileType }) => {
    const videoContainer = useRef()

    useEffect(() => {
        videoContainer.current.innerHTML = `

        <video data-setup='{"fluid": true, "autoplay":true,"html5": {"vhs":
        {"overrideNative": true}, "nativeAudioTracks": false, "nativeVideoTracks": false}}' class="video-js" />

    `

        const player = VideoJs(videoContainer.current.querySelector('video'), videoJsOptions, async () => {
            player.src({ src: url, type: fileType })
        })

        //  When destruct dispose the player
        return () => player.dispose()
    }, [url, fileType])

    return

}

export default VideoPlayer

Thank you in advance

I tried using different plugins of videojs but nothing solves the problem. Please help if you have any idea


问:
modify fields in mongoose
I have two schemas in my db

const user = new Schema({
    name:String,
    batch:{type:Number,ref:'batch'},
    sec:Number,
    id:Number
});

// ....

const batch = new Schema({
    no:Number,
    code:String
});
// ...
```
<p>let say i have</p>
<pre class="lang-js prettyprint-override"><code>const batch1 = batchModel.create({no:1, code:'A'})
const batch2 = batchModel.create({no:2, code:'B'})
</code>```

const user1 = userModel.create({name:'Jhon', batch:1, sec:12, id:1})
const user2 = userModel.create({name:'Jhon', batch:2, sec:12, id:1})

user1.id // here i need the id field should be B121 [BATCH_CODE][SEC][ACTUAL_ID]
user2.id // here i need the id field should be A121 [BATCH_CODE][SEC][ACTUAL_ID]
```

how can i achive this ?

I tried it using virtuals but since it has ref (batch) it was not worked

Title: modify fields in mongoose

Body:
I have two schemas in my db

const user = new Schema({
    name:String,
    batch:{type:Number,ref:'batch'},
    sec:Number,
    id:Number
});

// ....

const batch = new Schema({
    no:Number,
    code:String
});
// ...

let say i have

const batch1 = batchModel.create({no:1, code:'A'})
const batch2 = batchModel.create({no:2, code:'B'})

const user1 = userModel.create({name:'Jhon', batch:1, sec:12, id:1})
const user2 = userModel.create({name:'Jhon', batch:2, sec:12, id:1})

user1.id // here i need the id field should be B121 [BATCH_CODE][SEC][ACTUAL_ID]
user2.id // here i need the id field should be A121 [BATCH_CODE][SEC][ACTUAL_ID]

how can i achive this ?

I tried it using virtuals but since it has ref (batch) it was not worked


问:
Turkish characters in pyautogui?
How can I add Turkish characters to pyautogui typewrite function?

I am copying the Turkish word and then using the pyautogui.hotkey('ctrl', 'v') to write Turkish characters but is there any other way?

Title: Turkish characters in pyautogui?


问:
How to get full GCP GCR image name using Golang to use in container-analysis for vulnerabilities
I would like to get a compiled list of image vulnerabilities from GCP similar to what shows in the console but in an automated report-type fashion. Using Golang, my thought process was to get the list of images and then get the vulnerabilities for each image.

I've got bits and pieces of this working but haven't been able to get the entire solution to work because one function only seems to work if I provide an image SHA value but I don't know how to acquire that programmatically.

I'm using this function to retrieve a list of images, which returns the image name as projectid/reponame/image:

```<code>func GetImageURLs() ([]string, error) {
    auth, err := google.NewGcloudAuthenticator()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(auth)
    registry, err := gcr.NewRegistry("gcr.io")
    if err != nil {
        log.Fatal(err)
    }
    ctx := context.Background()
    repos, err := remote.Catalog(ctx, registry, remote.WithAuthFromKeychain(authn.DefaultKeychain))
    if err != nil {
        log.Fatal(err)
    }
    return repos, nil
}
</code>```

My container-analysis function looks like:

```<code>func findVulnerabilityOccurrencesForImage(resourceURL, projectID string) ([]*grafeaspb.Occurrence, error) {
    // Use this style of URL when you use Google Container Registry.
    // resourceURL := "https://gcr.io/my-project/my-repo/my-image"
    // Use this style of URL when you use Google Artifact Registry.
    // resourceURL := "https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image"
    ctx := context.Background()
    client, err := containeranalysis.NewClient(ctx)
    if err != nil {
        return nil, fmt.Errorf("NewClient: %v", err)
    }
    defer client.Close()

    req := &grafeaspb.ListOccurrencesRequest{
        Parent: fmt.Sprintf("projects/%s", projectID),
        Filter: fmt.Sprintf("resourceUrl = %q kind = %q", resourceURL, "VULNERABILITY"),
    }

    var occurrenceList []*grafeaspb.Occurrence
    it := client.GetGrafeasClient().ListOccurrences(ctx, req)
    for {
        occ, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            return nil, fmt.Errorf("occurrence iteration error: %v", err)
        }
        occurrenceList = append(occurrenceList, occ)
    }
    return occurrenceList, nil
}
</code>```

The problem is, if I use the image name as returned from GetImageURLs function, I get no response, but if I add the SHA value at the end of the image like this:
https://gcr.io/project/repo/image@sha256:lotsofshastuffhere
then I will get a response back like this:

```<code>name:"projects/projectID/occurrences/occurenceID"
resource_uri:"https://gcr.io/project/repo/image@@sha256:lotsofshastuffhere"
note_name:"projects/goog-vulnz/notes/CVE-2022-22822"
kind:VULNERABILITY
create_time:{seconds:1642427592 nanos:121248000}
update_time:{seconds:1656480316 nanos:956141000}
vulnerability:{severity:HIGH cvss_score:7.5
cvssv3:{base_score:9.8 exploitability_score:3.9 impact_score:5.9
attack_vector:ATTACK_VECTOR_NETWORK attack_complexity:ATTACK_COMPLEXITY_LOW
privileges_required:PRIVILEGES_REQUIRED_NONE user_interaction:USER_INTERACTION_NONE
scope:SCOPE_UNCHANGED confidentiality_impact:IMPACT_HIGH integrity_impact:IMPACT_HIGH
availability_impact:IMPACT_HIGH}
package_issue:{affected_cpe_uri:"cpe:/o:alpine:alpine_linux:3.12" affected_package:"expat"
affected_version:{name:"2.2.9" revision:"r1" kind:NORMAL full_name:"2.2.9-r1"}
fixed_cpe_uri:"cpe:/o:alpine:alpine_linux:3.12" fixed_package:"expat"
fixed_version:{name:"2.2.10" revision:"r0" kind:NORMAL full_name:"2.2.10-r0"}
fix_available:true package_type:"OS" effective_severity:HIGH}
short_description:"CVE-2022-22822"
long_description:"NIST vectors: AV:N/AC:L/Au:N/C:P/I:P/A:P"
effective_severity:HIGH
fix_available:true}
</code>```

How can I get the SHA value for an image so that I can use it to get a proper response for container-analysis?

Go Play example: https://go.dev/play/p/Dv1ZJF9n1RX

Eventually I want to be able to do something like this:

```<code>    var vlist []vulnerabilities
    for i := range urls {
        v := findVulnerabilityOccurencesForImage(i)
        vlist = append(vlist, v)
    }
// do stuff like export to csv
</code>```

resources:

https://cloud.google.com/container-analysis/docs/automated-scanning-howto#viewing_vulnerability_occurrences

https://github.com/GoogleCloudPlatform/golang-samples/tree/793a4c2378ca1c56b1c066dd2077c100a3b1995f/container_registry/container_analysis

Body:
I would like to get a compiled list of image vulnerabilities from GCP similar to what shows in the console but in an automated report-type fashion. Using Golang, my thought process was to get the list of images and then get the vulnerabilities for each image.

I've got bits and pieces of this working but haven't been able to get the entire solution to work because one function only seems to work if I provide an image SHA value but I don't know how to acquire that programmatically.

I'm using this function to retrieve a list of images, which returns the image name as projectid/reponame/image:

func GetImageURLs() ([]string, error) {
    auth, err := google.NewGcloudAuthenticator()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(auth)
    registry, err := gcr.NewRegistry("gcr.io")
    if err != nil {
        log.Fatal(err)
    }
    ctx := context.Background()
    repos, err := remote.Catalog(ctx, registry, remote.WithAuthFromKeychain(authn.DefaultKeychain))
    if err != nil {
        log.Fatal(err)
    }
    return repos, nil
}

My container-analysis function looks like:

func findVulnerabilityOccurrencesForImage(resourceURL, projectID string) ([]*grafeaspb.Occurrence, error) {
    // Use this style of URL when you use Google Container Registry.
    // resourceURL := "https://gcr.io/my-project/my-repo/my-image"
    // Use this style of URL when you use Google Artifact Registry.
    // resourceURL := "https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image"
    ctx := context.Background()
    client, err := containeranalysis.NewClient(ctx)
    if err != nil {
        return nil, fmt.Errorf("NewClient: %v", err)
    }
    defer client.Close()

    req := &grafeaspb.ListOccurrencesRequest{
        Parent: fmt.Sprintf("projects/%s", projectID),
        Filter: fmt.Sprintf("resourceUrl = %q kind = %q", resourceURL, "VULNERABILITY"),
    }

    var occurrenceList []*grafeaspb.Occurrence
    it := client.GetGrafeasClient().ListOccurrences(ctx, req)
    for {
        occ, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            return nil, fmt.Errorf("occurrence iteration error: %v", err)
        }
        occurrenceList = append(occurrenceList, occ)
    }
    return occurrenceList, nil
}

The problem is, if I use the image name as returned from GetImageURLs function, I get no response, but if I add the SHA value at the end of the image like this:
https://gcr.io/project/repo/image@sha256:lotsofshastuffhere
then I will get a response back like this:

name:"projects/projectID/occurrences/occurenceID"
resource_uri:"https://gcr.io/project/repo/image@@sha256:lotsofshastuffhere"
note_name:"projects/goog-vulnz/notes/CVE-2022-22822"
kind:VULNERABILITY
create_time:{seconds:1642427592 nanos:121248000}
update_time:{seconds:1656480316 nanos:956141000}
vulnerability:{severity:HIGH cvss_score:7.5
cvssv3:{base_score:9.8 exploitability_score:3.9 impact_score:5.9
attack_vector:ATTACK_VECTOR_NETWORK attack_complexity:ATTACK_COMPLEXITY_LOW
privileges_required:PRIVILEGES_REQUIRED_NONE user_interaction:USER_INTERACTION_NONE
scope:SCOPE_UNCHANGED confidentiality_impact:IMPACT_HIGH integrity_impact:IMPACT_HIGH
availability_impact:IMPACT_HIGH}
package_issue:{affected_cpe_uri:"cpe:/o:alpine:alpine_linux:3.12" affected_package:"expat"
affected_version:{name:"2.2.9" revision:"r1" kind:NORMAL full_name:"2.2.9-r1"}
fixed_cpe_uri:"cpe:/o:alpine:alpine_linux:3.12" fixed_package:"expat"
fixed_version:{name:"2.2.10" revision:"r0" kind:NORMAL full_name:"2.2.10-r0"}
fix_available:true package_type:"OS" effective_severity:HIGH}
short_description:"CVE-2022-22822"
long_description:"NIST vectors: AV:N/AC:L/Au:N/C:P/I:P/A:P"
effective_severity:HIGH
fix_available:true}

How can I get the SHA value for an image so that I can use it to get a proper response for container-analysis?

Go Play example: https://go.dev/play/p/Dv1ZJF9n1RX

Eventually I want to be able to do something like this:

    var vlist []vulnerabilities
    for i := range urls {
        v := findVulnerabilityOccurencesForImage(i)
        vlist = append(vlist, v)
    }
// do stuff like export to csv

resources:

https://cloud.google.com/container-analysis/docs/automated-scanning-howto#viewing_vulnerability_occurrences

https://github.com/GoogleCloudPlatform/golang-samples/tree/793a4c2378ca1c56b1c066dd2077c100a3b1995f/container_registry/container_analysis


问:
Wrong colors in Toggle button widget icons
I have a toggle button widget added to the appbar in the actions section. This is how it looks:

As you see icon colors are not correct. The selected one color is the same color as the appbar and the other icons show black. Oddly, the other icon added to the appbar outside the Toggle button widget is white:

```<code>import 'package:flutter/material.dart';

void main() async {

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Project',
      home: Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
              title: Text("Game Manager"),
              actions: [
                Row(children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ToggleButtons(
                        borderRadius: const BorderRadius.all(Radius.circular(8)),
                        /*borderColor: Colors.blue,
                        selectedBorderColor: Colors.blue[200],
                        selectedColor: Colors.white,
                        fillColor: Colors.blue[300],
                        color: Colors.blue[300],*/
                        onPressed: (int i) => print("pressed!"),
                        isSelected: const [true,false,false],
                        children: [
                          Tooltip(message: "sort_by_name", child: const Icon(Icons.receipt)),
                          Tooltip(message: "sort_by_status", child: const Icon(Icons.stars)),
                          Tooltip(message: "sort_by_size", child: const Icon(Icons.storage))
                        ]),
                  ),

                  IconButton(
                    onPressed: () {
                      print("Yeah");
                    },
                    icon: const Icon(Icons.unfold_less),
                    tooltip: "fold_all",
                  ),
                  IconButton(
                    onPressed: null,
                    icon: Icon(Icons.refresh),
                    tooltip: "refresh",
                  ),
                ]
                )
              ]),
          body: Container()

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

PubSpec.yaml:

```<code>name: project
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.4 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
  - assets/images/logo.png
  - assets/translations/
</code>```

Body:
I have a toggle button widget added to the appbar in the actions section. This is how it looks:

As you see icon colors are not correct. The selected one color is the same color as the appbar and the other icons show black. Oddly, the other icon added to the appbar outside the Toggle button widget is white:

import 'package:flutter/material.dart';

void main() async {

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Project',
      home: Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
              title: Text("Game Manager"),
              actions: [
                Row(children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ToggleButtons(
                        borderRadius: const BorderRadius.all(Radius.circular(8)),
                        /*borderColor: Colors.blue,
                        selectedBorderColor: Colors.blue[200],
                        selectedColor: Colors.white,
                        fillColor: Colors.blue[300],
                        color: Colors.blue[300],*/
                        onPressed: (int i) => print("pressed!"),
                        isSelected: const [true,false,false],
                        children: [
                          Tooltip(message: "sort_by_name", child: const Icon(Icons.receipt)),
                          Tooltip(message: "sort_by_status", child: const Icon(Icons.stars)),
                          Tooltip(message: "sort_by_size", child: const Icon(Icons.storage))
                        ]),
                  ),

                  IconButton(
                    onPressed: () {
                      print("Yeah");
                    },
                    icon: const Icon(Icons.unfold_less),
                    tooltip: "fold_all",
                  ),
                  IconButton(
                    onPressed: null,
                    icon: Icon(Icons.refresh),
                    tooltip: "refresh",
                  ),
                ]
                )
              ]),
          body: Container()

      ),
    );
  }
}

PubSpec.yaml:

name: project
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.4 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
  - assets/images/logo.png
  - assets/translations/


问:
Is it possible to change the working directory in VSCode for a golang project?
I have such a project structure:

```<code>app
   -configs
      -config.yaml
   -server
      -cmd
         -app
            -main.go
         -internal
            -config
               -config.go
</code>```

Inside config.go I want to read the config from configs/config.yaml.

But as I understand it, due to the fact that my working directory is equal to the path to the main file, I get an error file not found when I pass such a path "configs/config.yaml".

I saw that in intellij idea (if I'm not mistaken) in a similar situation, they just changed the working directory to some_path/app and everything worked fine . Is it possible in VSCode as well? that is, to change the working directory or is there any other way to achieve this?

Body:
I have such a project structure:

app
   -configs
      -config.yaml
   -server
      -cmd
         -app
            -main.go
         -internal
            -config
               -config.go

Inside config.go I want to read the config from configs/config.yaml.

But as I understand it, due to the fact that my working directory is equal to the path to the main file, I get an error file not found when I pass such a path "configs/config.yaml".

I saw that in intellij idea (if I'm not mistaken) in a similar situation, they just changed the working directory to some_path/app and everything worked fine . Is it possible in VSCode as well? that is, to change the working directory or is there any other way to achieve this?


问:
How to debug javascript errors thrown from content after write() to iframe? No/missing "VM" sources
I'm writing to the content of an iframe as such:

```<code>iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
</code>```

where html is an entire document with some javascript. The javascript in that iframe sometimes encounters an error but the console is not helpful enough. The following is but one example but they all act the same: It gives a line number but is not able to show it in context/source. This is in Chrome.

Error message:

Empty source:

I'd hope to see something in the source page but I understand it could be some limitation or security measure from the browser.

The only thing I've found to help sometimes is to put lots of unique console.log()'s throughout the code so I can see where it last worked.

What's weird is it sometimes gives me the appropriate source. For example I just encountered the expected behavior but can't fathom how or why.

Working! But why?

Note: Google Chrome Version 109.0.5414.75 (Official Build) (64-bit)

Body:
I'm writing to the content of an iframe as such:

iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

where html is an entire document with some javascript. The javascript in that iframe sometimes encounters an error but the console is not helpful enough. The following is but one example but they all act the same: It gives a line number but is not able to show it in context/source. This is in Chrome.

Error message:

Empty source:

I'd hope to see something in the source page but I understand it could be some limitation or security measure from the browser.

The only thing I've found to help sometimes is to put lots of unique console.log()'s throughout the code so I can see where it last worked.

What's weird is it sometimes gives me the appropriate source. For example I just encountered the expected behavior but can't fathom how or why.

Working! But why?

Note: Google Chrome Version 109.0.5414.75 (Official Build) (64-bit)


问:
Apollo GraphQL Reactjs Caching, going to the cache for certain fields, querying the server for other fields of the same query
Currently, I have a query that initially fires containing two chunks of data.

```<code>gql`
  query GetWorkSummaryTiles(
    $type: WorkSummaryType!
    $assignedTo: [ID]
    $clientId: ID
    $tileIds: [String!]
  ) {
    workSummary(type: $type, assignedTo: $assignedTo, clientId: $clientId, tileIds: $tileIds) {
      tiles {
        id
        metricType
        value
        listDataType
        group
        groupOrder
        title
        subtitle
        color
        order
      }
      averageRating
      ratingCount
    }
  }
`
</code>```

The tiles field is subject to be changed when the assignedTo field changes due to user input. On the other hand, the averageRating and ratingCount fields both will never be different due to assignedTo being different.

Is there anyway to go to the cache for averageRating and ratingCount when assignedTo changes, but still requery my server for tiles? One solution I have is breaking this up into two seperate queries, but I don't know if that is subject to make my app slower/ cause unnecessary rerenders on the initial load.

Any help is appreciated!

Body:
Currently, I have a query that initially fires containing two chunks of data.

gql`
  query GetWorkSummaryTiles(
    $type: WorkSummaryType!
    $assignedTo: [ID]
    $clientId: ID
    $tileIds: [String!]
  ) {
    workSummary(type: $type, assignedTo: $assignedTo, clientId: $clientId, tileIds: $tileIds) {
      tiles {
        id
        metricType
        value
        listDataType
        group
        groupOrder
        title
        subtitle
        color
        order
      }
      averageRating
      ratingCount
    }
  }
`

The tiles field is subject to be changed when the assignedTo field changes due to user input. On the other hand, the averageRating and ratingCount fields both will never be different due to assignedTo being different.

Is there anyway to go to the cache for averageRating and ratingCount when assignedTo changes, but still requery my server for tiles? One solution I have is breaking this up into two seperate queries, but I don't know if that is subject to make my app slower/ cause unnecessary rerenders on the initial load.

Any help is appreciated!


问:
Edge_size not working with ggVennDiagram on only one computer
We are attempting to use ggVennDiagram to plot a few Venn diagrams for a research project, and the simple code I wrote works on my MacBook laptop and my Acer PC, but not on my ASUS laptop (using windows). The code does not return any errors, but does not accurately reflect the edge_size argument. Basically, the edge size will not change regardless of what is entered and I am wondering if anyone has any idea what to do to get it to work on the ASUS laptop. RStudio was updated to the newest version before we tried running the code. I have attached the lines of code for the Venn below,  note it also utilizes the tidyverse package.

```<code>p<- ggVennDiagram(lapply(Data[2:5], function(x) which(x==1)), label="count",edge_lty= "solid", edge_size = 2)
p + scale_fill_distiller(palette = "Blues", direction = 1)
</code>```

Things we've tried:

Tried changing edge size to 0, 1, 2, 10, 100, 20, etc..  but the edge size would not change when attempting it on the ASUS laptop, the Venn would still work and no errors were returned.

Tried the code on a MacBook and acer PC and it worked properly (edge size changes when code is used on same version of RStudio on PC and Mac), just wouldn't work on a ASUS laptop.

Body:
We are attempting to use ggVennDiagram to plot a few Venn diagrams for a research project, and the simple code I wrote works on my MacBook laptop and my Acer PC, but not on my ASUS laptop (using windows). The code does not return any errors, but does not accurately reflect the edge_size argument. Basically, the edge size will not change regardless of what is entered and I am wondering if anyone has any idea what to do to get it to work on the ASUS laptop. RStudio was updated to the newest version before we tried running the code. I have attached the lines of code for the Venn below,  note it also utilizes the tidyverse package.

p<- ggVennDiagram(lapply(Data[2:5], function(x) which(x==1)), label="count",edge_lty= "solid", edge_size = 2)
p + scale_fill_distiller(palette = "Blues", direction = 1)

Things we've tried:

Tried changing edge size to 0, 1, 2, 10, 100, 20, etc..  but the edge size would not change when attempting it on the ASUS laptop, the Venn would still work and no errors were returned.

Tried the code on a MacBook and acer PC and it worked properly (edge size changes when code is used on same version of RStudio on PC and Mac), just wouldn't work on a ASUS laptop.


问:
Handling passwords in R and Shiny app in .Renviron file as a secure production environment
Why is keeping your password, port, host, and all secrets of a database (e.g. PostgreSQL) in the .Renviron file safe for Shiny apps and R scripts?

I have a question about the .Renviron file and its security password. Although the .Renviron file is a hidden file in our file system, how does it guarantee the security of passwords (key, token) and information?

I hope to understand the security against malicious hacking of the .Renviron file to guard the passwords and secrets important of the PostgreSQL database connection. In addition to omitting the explicit password in the R script.


问:
Vaadin 23 PageNotFound route returns 200ok instead of 404
This is my custom PageNotFound route:

```<code>@ParentLayout(MainLayout.class)
@AnonymousAllowed
public class PageNotFound extends RouteNotFoundError {

    @Override
    public int setErrorParameter(BeforeEnterEvent event, ErrorParameter<NotFoundException> parameter) {
        VerticalLayout verticalLayout = new VerticalLayout();

        // some logic

        getElement().insertChild(0, verticalLayout.getElement());

        return HttpServletResponse.SC_NOT_FOUND;
    }

}
</code>```

Despite the fact I return HttpServletResponse.SC_NOT_FOUND the page still returns 200ok instead of 404. What am I doing wrong and how to fix it?

Body:
This is my custom PageNotFound route:

@ParentLayout(MainLayout.class)
@AnonymousAllowed
public class PageNotFound extends RouteNotFoundError {

    @Override
    public int setErrorParameter(BeforeEnterEvent event, ErrorParameter<NotFoundException> parameter) {
        VerticalLayout verticalLayout = new VerticalLayout();

        // some logic

        getElement().insertChild(0, verticalLayout.getElement());

        return HttpServletResponse.SC_NOT_FOUND;
    }

}

Despite the fact I return HttpServletResponse.SC_NOT_FOUND the page still returns 200ok instead of 404. What am I doing wrong and how to fix it?


问:
Copy ALL directories & files to new directory
Hi I'm trying to copy a folder to a new folder (recursively), I've found a working example however it only copies one child directory within the parent, the last directory to be exact.

(this is the copyDir func I copied: https://stackoverflow.com/a/26038979/10949890)

I have about 7+ folders within the parent I want to copy them all within a new directory.

Perhaps I need to change something on my input?

```<code><input
   type="file"
   id="file-picker"
   // eslint-disable-next-line @typescript-eslint/ban-ts-comment
   // @ts-ignore
   webkitdirectory="true"
   directory="true"
   onChange={handleSelectedFiles}
/>
</code>```

Body:
Hi I'm trying to copy a folder to a new folder (recursively), I've found a working example however it only copies one child directory within the parent, the last directory to be exact.

(this is the copyDir func I copied: https://stackoverflow.com/a/26038979/10949890)

I have about 7+ folders within the parent I want to copy them all within a new directory.

Perhaps I need to change something on my input?

<input
   type="file"
   id="file-picker"
   // eslint-disable-next-line @typescript-eslint/ban-ts-comment
   // @ts-ignore
   webkitdirectory="true"
   directory="true"
   onChange={handleSelectedFiles}
/>


问:
Rendering Oracle BLOBs in R Shiny Datatable
I am new to both BLOBs and image rendering in Shiny, but I am wondering if it is possible to render images stored as BLOBs in an Oracle table via datatables in Shiny? Unfortunately I don't have code to share, but am wondering if anyone has attempted or been successful doing something like this?

Basically, I am wanting to have a table stored in Oracle that has a product picture, and then several more columns with other information about the product. Then, I would like to be able to read that table in via R and display the full table with the images as a datatable in a Shiny application.


问:
Center div is not centered in Owl Carousel when the center div is enlarged
I have used this solution to enlarge a div in the center of the owl carousel:

How do I add classes to items in Owl Carousel 2?

However if I set the width of the 'big' class , it stretches right and does not center in the carousel.
Setting the height is fine, but setting the width causes me heartache. Any suggestions would be much appreciated.

PS: Ive also tried transform:scale(1.3) on the big class, but I ended up getting an overlap. I then tried setting the margins on the big class (left and right), but this created unequal lengths to the 'item' class.

How do I add classes to items in Owl Carousel 2?


问:
Body is too large (content gets out of box) and enables right scroll
Tried a lot of ways and a lot of Codes, but its not working website width does not stay in screen. Always enables space to the right side and content is bigger than screen.

tried width and height 100vw; max-width: 100%;
also tried giving the body a specific width

```<code>`body, html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
body {
  margin: 0;
  overflow-x: hidden;
  border: solid;
  padding-left: 2px;
}

* {
  box-sizing: inherit;
}

.container {
  display: grid;
  grid-template-columns: 1fr;
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
  width: 100%;
  padding: 0 0px;
}`
</code>```
```<code><
</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Try</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="galery.css">

                Home

                Stuff

                About

                    href="contact.html">contact

```

Body:
Tried a lot of ways and a lot of Codes, but its not working website width does not stay in screen. Always enables space to the right side and content is bigger than screen.

tried width and height 100vw; max-width: 100%;
also tried giving the body a specific width

`body, html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
body {
  margin: 0;
  overflow-x: hidden;
  border: solid;
  padding-left: 2px;
}

* {
  box-sizing: inherit;
}

.container {
  display: grid;
  grid-template-columns: 1fr;
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
  width: 100%;
  padding: 0 0px;
}`

<

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Try</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="galery.css">

                Home

                Stuff

                About

                    contact


问:
Calculating and Drawing a Triangle - Python Beginner
Please Please Please help :)
The objective of this program is to randomly generate three side lengths of a triangle, check if those side lengths can make a triangle, calculate the angles of the triangle, and then draw the triangle with turtle.

My code runs! But I am having an issue with my logic haha. Because when I draw my triangle, the sides do not connect. I am having trouble pin pointing my problem though. Any help would be really appreciated!!!

Also- Because im randomly generating from a wide range of variables and using the law of cosines to find the angles...I am often getting a math domain error. Would absolute value solve this problem for me? I am a little fuzzy on the math on why im getting this error (a negative value I presume?). I would also like guidance on how and where in my code to fix this. (Im just learning and I dont have a teacher.)

This is my code:

```<code># import statements
import random
import math
import turtle

# set turtle
window = turtle.Screen()
writer = turtle.Turtle()
writer.pensize(3)
writer.pencolor("pink")
writer.pendown

def checkTriangle():
  side1 = random.randint(5,100)
  side2 = random.randint(5,100)
  side3 = random.randint(5,100)

  sum1and2 = side1 + side2
  sum1and3 = side1 + side3
  sum2and3 = side2 + side3

  angle1 = angle(side1, side2, side3)
  angle2 = angle(side2, side3, side1)
  angle3 = angle(side3, side1, side2)

  if side3 <= sum1and2 and side2 <= sum1and3 and side1 <= sum2and3:
    print ("true")
    print(side1, side2, side3)
    print(angle1, angle2, angle3)
    drawTriangle(side1, side2, side3, angle1, angle2, angle3)

  else:
    print ("false")

def angle(side1, side2, side3):
  return math.degrees(math.acos((side3**2 - side2**2 - side1**2) /(-2.0 * side1 * side2)))

def drawTriangle(side1, side2, side3, angle1, angle2, angle3):
  writer.forward(side1)
  writer.left(angle3)
  writer.forward(side2)
  writer.left(angle1)
  writer.forward(side3)
  writer.left(angle2)

checkTriangle()
</code>```

Thanks again.

Body:
Please Please Please help :)
The objective of this program is to randomly generate three side lengths of a triangle, check if those side lengths can make a triangle, calculate the angles of the triangle, and then draw the triangle with turtle.

My code runs! But I am having an issue with my logic haha. Because when I draw my triangle, the sides do not connect. I am having trouble pin pointing my problem though. Any help would be really appreciated!!!

Also- Because im randomly generating from a wide range of variables and using the law of cosines to find the angles...I am often getting a math domain error. Would absolute value solve this problem for me? I am a little fuzzy on the math on why im getting this error (a negative value I presume?). I would also like guidance on how and where in my code to fix this. (Im just learning and I dont have a teacher.)

This is my code:

# import statements
import random
import math
import turtle

# set turtle
window = turtle.Screen()
writer = turtle.Turtle()
writer.pensize(3)
writer.pencolor("pink")
writer.pendown

def checkTriangle():
  side1 = random.randint(5,100)
  side2 = random.randint(5,100)
  side3 = random.randint(5,100)

  sum1and2 = side1 + side2
  sum1and3 = side1 + side3
  sum2and3 = side2 + side3

  angle1 = angle(side1, side2, side3)
  angle2 = angle(side2, side3, side1)
  angle3 = angle(side3, side1, side2)

  if side3 <= sum1and2 and side2 <= sum1and3 and side1 <= sum2and3:
    print ("true")
    print(side1, side2, side3)
    print(angle1, angle2, angle3)
    drawTriangle(side1, side2, side3, angle1, angle2, angle3)

  else:
    print ("false")

def angle(side1, side2, side3):
  return math.degrees(math.acos((side3**2 - side2**2 - side1**2) /(-2.0 * side1 * side2)))

def drawTriangle(side1, side2, side3, angle1, angle2, angle3):
  writer.forward(side1)
  writer.left(angle3)
  writer.forward(side2)
  writer.left(angle1)
  writer.forward(side3)
  writer.left(angle2)

checkTriangle()

Thanks again.


问:
React Native - When I open a new screen, the bottom tab navigator is dismissed but screen page is not full height
Lets say I am in the tab - ChatStack and I am on the screen stack - AllChatRooms. Then when I click on one of the chat rows, I am then navigated to the chat room. I have it coded that, when in the ChatRoom screen, don't display nav bar and that works. But the ChatRoom screen does not reach full height and it acts like the nav bar is still there. I attached an image with colors so you can see what I am talking about.

Would really appreciate some help if anyone knows how to get the screen to reach the bottom of the phone screen.

So I am using a bottom tab navigator like this (simplified version):

Tabs.js

const getRouteName = (route) => {
    const routeName = getFocusedRouteNameFromRoute(route);
    if (routeName?.includes("HomeAllCategories") || routeName === "ChatRoom") {
        return "none";
    }
    return "flex";
}

return (
  <Tab.Navigator screenOptions={{ tabBarShowLabel: false }}>
        <Tab.Screen name="Home" component={HomeStack}/>
        <Tab.Screen name="Bookmarks" component={BookmarkStack}/>
        <Tab.Screen name="Chats" component={ChatStack} options={({route}) => ({
            tabBarStyle: {display: getRouteName(route)},
        })}/>
        <Tab.Screen name="Settings" component={SettingsStack}/>
  </Tab.Navigator>
)```
</div>
</div>
</p>
<p><strong>ChatStack.js</strong></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-js lang-js prettyprint-override"><code><Stack.Navigator>
    <Stack.Screen name="AllChatRooms" component={AllChatRooms} />
    <Stack.Screen name="ChatRoom" component={ChatRoom} />
</Stack.Navigator></code>```

ChatRoom.js

  return (
    <SafeAreaView className="flex-1 bg-slate-900">

        <KeyboardAvoidingView
            behavior={Platform.OS === "ios" ? "padding" : "height"}
            className="flex-1"
            keyboardVerticalOffset={10}
        >
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <FlatList
                data={messages}
                className="pl-4"
                keyExtractor={item => item.id}
                renderItem={({ item }) =>
                item.from === user.name ? (
                    <ReceiverMessage message={item} />
                ) : (
                    <SenderMessage message={item} />
                )
            }
            />
        </TouchableWithoutFeedback>

        {/* Text Box */}
        <View className="bg-white flex-row justify-between items-center border border-gray-200 px-5 py-2">
            <TextInput
                className="h-10 text-lg w-4/5"
                placeholder="Send Message..."
            />
            <Button title="Send" color="#6ECCAF"/>
        </View>
        </KeyboardAvoidingView>

    </SafeAreaView>
  )```
</div>
</div>
</p>
<p>and I'm using:</p>
```"@react-navigation/bottom-tabs": "^6.5.2",
"@react-navigation/native": "^6.1.1",
"@react-navigation/native-stack": "^6.9.7",
```

But sometimes it does have the full height and I don't know why? On launch, the height of the screen is never working but after leaving and opening the chat room several times, the height of the screen does reach the bottom. Why is that?

Body:
Lets say I am in the tab - ChatStack and I am on the screen stack - AllChatRooms. Then when I click on one of the chat rows, I am then navigated to the chat room. I have it coded that, when in the ChatRoom screen, don't display nav bar and that works. But the ChatRoom screen does not reach full height and it acts like the nav bar is still there. I attached an image with colors so you can see what I am talking about.

Would really appreciate some help if anyone knows how to get the screen to reach the bottom of the phone screen.

So I am using a bottom tab navigator like this (simplified version):

Tabs.js

const getRouteName = (route) => {
    const routeName = getFocusedRouteNameFromRoute(route);
    if (routeName?.includes("HomeAllCategories") || routeName === "ChatRoom") {
        return "none";
    }
    return "flex";
}

return (
  <Tab.Navigator screenOptions={{ tabBarShowLabel: false }}>
        <Tab.Screen name="Home" component={HomeStack}/>
        <Tab.Screen name="Bookmarks" component={BookmarkStack}/>
        <Tab.Screen name="Chats" component={ChatStack} options={({route}) => ({
            tabBarStyle: {display: getRouteName(route)},
        })}/>
        <Tab.Screen name="Settings" component={SettingsStack}/>
  </Tab.Navigator>
)

ChatStack.js

<Stack.Navigator>
    <Stack.Screen name="AllChatRooms" component={AllChatRooms} />
    <Stack.Screen name="ChatRoom" component={ChatRoom} />
</Stack.Navigator>

ChatRoom.js

  return (
    <SafeAreaView className="flex-1 bg-slate-900">

        <KeyboardAvoidingView
            behavior={Platform.OS === "ios" ? "padding" : "height"}
            className="flex-1"
            keyboardVerticalOffset={10}
        >
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <FlatList
                data={messages}
                className="pl-4"
                keyExtractor={item => item.id}
                renderItem={({ item }) =>
                item.from === user.name ? (
                    <ReceiverMessage message={item} />
                ) : (
                    <SenderMessage message={item} />
                )
            }
            />
        </TouchableWithoutFeedback>

        {/* Text Box */}
        <View className="bg-white flex-row justify-between items-center border border-gray-200 px-5 py-2">
            <TextInput
                className="h-10 text-lg w-4/5"
                placeholder="Send Message..."
            />
            <Button title="Send" color="#6ECCAF"/>
        </View>
        </KeyboardAvoidingView>

    </SafeAreaView>
  )

and I'm using:

"@react-navigation/bottom-tabs": "^6.5.2",
"@react-navigation/native": "^6.1.1",
"@react-navigation/native-stack": "^6.9.7",

But sometimes it does have the full height and I don't know why? On launch, the height of the screen is never working but after leaving and opening the chat room several times, the height of the screen does reach the bottom. Why is that?


问:
gitignore cannot ignore folders from last commit
I try to ignore .idea directory when commit and push to remote repository. I set my .gitignore file in following way:

```<code>### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
</code>```

But when I committed and pushed to tfs repository, I found the .idea folder is still pushed to repo.

Is there anyway to remove .idea folder from repository and ignore it in future commit and push?

Note: I have already committed and pushed to remote repository without setting up .gitignore file. I think the .idea folder in repo is from last commit.

Body:
I try to ignore .idea directory when commit and push to remote repository. I set my .gitignore file in following way:

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

But when I committed and pushed to tfs repository, I found the .idea folder is still pushed to repo.

Is there anyway to remove .idea folder from repository and ignore it in future commit and push?

Note: I have already committed and pushed to remote repository without setting up .gitignore file. I think the .idea folder in repo is from last commit.