问:
Authentication in goBuffalo
I have followed the steps according to the documentation(https://gobuffalo.io/documentation/guides/auth/) to install the $ buffalo plugins install github.com/gobuffalo/buffalo-auth@latest.Yet,it did not work.

I tried using the middleware authorize for some of the routes but I could still access without having to login. Where could I have gone wrong?

Title: Authentication in goBuffalo


来源: stackexchange

问:
Virtual machine in KVM failing to connect http server running on the same vm network when firewall is stopped on KVM host
I am running a multiple VMs in kvm configured on Fedora37.
Ip provided to the VMs by a dhcp server running on the same kvm network.
I cannot reach http service running on the on the same dhcp server if firewall is up on KVM host.
On the other hand, I cannot reach internet service from KVM hosts if firewall is up on KVM host.
Output from KVM host</p>
```<code># firewall-cmd --list-all
FedoraWorkstation (active)
  target: default
  icmp-block-inversion: no
  interfaces: wlp5s0
  sources:
  services: dhcpv6-client http mdns samba-client ssh
  ports: 1025-65535/udp 1025-65535/tcp
  protocols:
  forward: yes
  masquerade: no
  forward-ports:
  source-ports:

# brctl show
bridge name     bridge id               STP enabled     interfaces
kubenet         8000.525400a685f6           yes         vnet0
                                                        vnet1
                                                        vnet10
                                                        vnet3
                                                        vnet4
                                                        vnet5
                                                        vnet6
                                                        vnet7
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am running a multiple VMs in kvm configured on Fedora37.
Ip provided to the VMs by a dhcp server running on the same kvm network.
I cannot reach http service running on the on the same dhcp server if firewall is up on KVM host.
On the other hand, I cannot reach internet service from KVM hosts if firewall is up on KVM host.
Output from KVM host

# firewall-cmd --list-all
FedoraWorkstation (active)
  target: default
  icmp-block-inversion: no
  interfaces: wlp5s0
  sources:
  services: dhcpv6-client http mdns samba-client ssh
  ports: 1025-65535/udp 1025-65535/tcp
  protocols:
  forward: yes
  masquerade: no
  forward-ports:
  source-ports:

# brctl show
bridge name     bridge id               STP enabled     interfaces
kubenet         8000.525400a685f6           yes         vnet0
                                                        vnet1
                                                        vnet10
                                                        vnet3
                                                        vnet4
                                                        vnet5
                                                        vnet6
                                                        vnet7


问:
Desktop.getDesktop().open(file) doesn't work when jar is running in background as windows service
As the title, when my jar is running in the background as a windows service, Desktop.getDesktop().open(file) does not work(I configured -Djava.awt.headless=false). It works fine if I run the jar in the foreground as java -jar

Please how can I solve this problem, or there is a better API to replace it (API needs to be compatible with mac and windows), thanks in advance.


问:
Only get data when click on mat-select
I used several dropdown lists on UI.

If we load data on initial, it will impact to perfomance to load all of them.

I want to only load data (from API) to mat-select after click or focus on them.

I tried to use (click) or (focus) event but it didn't show up the drop down because there is no data to show up (system still needs to have time to get data from API).

I also used async pipe but it didn't work too:

```<code>event: (click)="getData()"

binding: *ngFor="let o of filtered$ | async"

load data:  getData() {
    return this.filtered$ = this.fileService.GetData().pipe(map((result: ApiJsonResponse) => {
      return result.data;
    }));;
  }
</code>```

How can I solve this issue? can we use async to bind to mat-select?

Title: Only get data when click on mat-select

Body:
I used several dropdown lists on UI.

If we load data on initial, it will impact to perfomance to load all of them.

I want to only load data (from API) to mat-select after click or focus on them.

I tried to use (click) or (focus) event but it didn't show up the drop down because there is no data to show up (system still needs to have time to get data from API).

I also used async pipe but it didn't work too:

event: (click)="getData()"

binding: *ngFor="let o of filtered$ | async"

load data:  getData() {
    return this.filtered$ = this.fileService.GetData().pipe(map((result: ApiJsonResponse) => {
      return result.data;
    }));;
  }

How can I solve this issue? can we use async to bind to mat-select?


问:
TypeError: create_sql() got an unexpected keyword argument 'concurrently'
I'm trying to add a GIN Index to my usernames on my user model for better trigram similarity search:

```<code>class User(models.Model):
    ...
    class Meta:
        ordering = ["-created_at"]
        indexes = [
            UpperGinIndex(
                fields=["username"],
                name="user_username_gintrgm",
                opclasses=["gin_trgm_ops"],
            )
        ]

</code>```

And when I run python manage.py makemigrations, no error is produced:

```<code># Generated by Django 3.2.7 on 2023-01-06 03:00

from django.db import migrations
import myproj.db

class Migration(migrations.Migration):

    dependencies = [
        ...
    ]

    operations = [
        migrations.AddIndex(
            model_name="user",
            index=myproj.db.UpperGinIndex(
                fields=["username"],
                name="user_username_gintrgm",
                opclasses=["gin_trgm_ops"],
            ),
        ),
    ]
</code>```

However, when I run python manage.py migrate, I get this error which doesn't seem to have any easy-to-google fixes. I've already tried updating Django to 3.2.16:

```<code>  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/operations/models.py", line 761, in database_forwards
    schema_editor.add_index(model, self.index)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/backends/postgresql/schema.py", line 218, in add_index
    self.execute(index.create_sql(model, self, concurrently=concurrently), params=None)
TypeError: create_sql() got an unexpected keyword argument 'concurrently'
</code>```

Any ideas on how to fix this?

Body:
I'm trying to add a GIN Index to my usernames on my user model for better trigram similarity search:

class User(models.Model):
    ...
    class Meta:
        ordering = ["-created_at"]
        indexes = [
            UpperGinIndex(
                fields=["username"],
                name="user_username_gintrgm",
                opclasses=["gin_trgm_ops"],
            )
        ]

And when I run python manage.py makemigrations, no error is produced:

# Generated by Django 3.2.7 on 2023-01-06 03:00

from django.db import migrations
import myproj.db

class Migration(migrations.Migration):

    dependencies = [
        ...
    ]

    operations = [
        migrations.AddIndex(
            model_name="user",
            index=myproj.db.UpperGinIndex(
                fields=["username"],
                name="user_username_gintrgm",
                opclasses=["gin_trgm_ops"],
            ),
        ),
    ]

However, when I run python manage.py migrate, I get this error which doesn't seem to have any easy-to-google fixes. I've already tried updating Django to 3.2.16:

  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/migrations/operations/models.py", line 761, in database_forwards
    schema_editor.add_index(model, self.index)
  File "/home/codespace/.cache/pypoetry/virtualenvs/myproj-NbYkgl4C-py3.8/lib/python3.8/site-packages/django/db/backends/postgresql/schema.py", line 218, in add_index
    self.execute(index.create_sql(model, self, concurrently=concurrently), params=None)
TypeError: create_sql() got an unexpected keyword argument 'concurrently'

Any ideas on how to fix this?


问:
Why doesn't cv2.VideoCapture() work on raspberry pi?
I was getting this error:

```<code>Gtk-ERROR **: GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported

</code>```

until I added

```<code>import gi
gi.require_version('Gtk', '3.0')
</code>```

to the top.  But now my script hangs on

```<code>cv2.VideoCapture(0)

</code>```

and eventually it says

```<code>select timeout

</code>```

I think the problem has something to do with the gtk thing but I'm at a loss for what to try... any advice?

Body:
I was getting this error:

Gtk-ERROR **: GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported

until I added

import gi
gi.require_version('Gtk', '3.0')

to the top.  But now my script hangs on

cv2.VideoCapture(0)

and eventually it says

select timeout

I think the problem has something to do with the gtk thing but I'm at a loss for what to try... any advice?


问:
How to rotate the android "back" button, like for the open keyboard
By default android has the back button as an arrow pointing left.
Also by default when I open the Android keyboard, the back button "rotates" now pointing downwards (this is normal, because at that moment the back button would close the keyboard).

I created my own custom keyboard, which has nothing to do with that of the Android system. And now I don't know how to program that back button, so that it "rotate" like it's the system keyboard.

From what I've read, WillPopScope should programmatically override the button, but the crux of the rotation remains, I don't know if it can, or possibly how to rotate that back button so that it points downwards.

// How is the back button when my keyboard opens

//How I would like the back button when my keyboard opens


问:
Any idea why ScrollView isn't appearing at all within my view?
For some reason, my entire scroll view is not appearing in my Inbox View. I thought it had something to do with the UI but after trying a bunch of re-arranging I've had no luck. I'm starting to think it has something to do with actually fetching the vm.recentMessage data but I really don't know.</p>
```<code>import SwiftUI
import FirebaseFirestoreSwift
import FirebaseFirestore
import FirebaseAuth
import Kingfisher

struct RecentMessage: Identifiable {

    var id: String { documentId }

    let documentId: String
    let text, fullname: String
    let fromId, toId: String
    let profileImageUrl: String
    let timestamp: Timestamp

    init(documentId: String, data: [String: Any]) {
        self.documentId = documentId
        self.text = data["text"] as? String ?? ""
        self.fullname = data["fullname"] as? String ?? ""
        self.fromId = data["fromId"] as? String ?? ""
        self.toId = data["toId"] as? String ?? ""
        self.profileImageUrl = data["profileImageUrl"] as? String ?? ""
        self.timestamp = data["timestamp"] as? Timestamp ?? Timestamp(date: Date())
    }
}

class MainMessagesViewModel: ObservableObject {
    @Published var recentMessages = [RecentMessage]()
    @ObservedObject var authViewModel = AuthViewModel()
    @Published var errorMessage = ""

    init() {
        fetchRecentMessages()
    }

    private func fetchRecentMessages() {
        guard let uid = authViewModel.currentUser?.uid else { return }

        Firestore.firestore().collection("recent_messages").document(uid).collection("recent_messages")
            .document(uid)
            .collection("messages")
            .order(by: "timestamp")
            .addSnapshotListener { querySnapshot, error in
                if let error = error {
                    self.errorMessage = "Failed to listen for recent messages: \(error)"
                    print(error)
                    return
                }

                querySnapshot?.documentChanges.forEach({ change in
                    let docId = change.document.documentID

                    if let index = self.recentMessages.firstIndex(where: { rm in
                        return rm.documentId == docId
                    }) {
                        self.recentMessages.remove(at: index)
                    }

                    self.recentMessages.insert(.init(documentId: docId, data: change.document.data()), at: 0)

                })

        }
    }
}

struct InboxView: View {
    @ObservedObject var searchViewModel = SearchViewModel()
    @ObservedObject var vm = MainMessagesViewModel()
    @State private var selectedFilter: InboxViewModel = .messages
    @Namespace var animation
    @State var shouldShowNewMessageScreen = false
    @State var shouldNavigateToChatLogView = false
    @State var user: User?

    var body: some View {
        VStack (alignment: .leading) {
            NavigationLink("", isActive: $shouldNavigateToChatLogView) {
                ChatLogView(user: user)
            }
            Text("Inbox")
                .font(.title)
            HStack (alignment: .center) {
                SearchBar(text: $searchViewModel.searchText)
                Button {
                    shouldShowNewMessageScreen.toggle()
                } label: {
                    Image(systemName: "square.and.pencil")
                        .resizable()
                        .frame(width: 24, height: 24)
                }
            }
            ScrollView {
                LazyVStack {
                    ForEach(vm.recentMessages) { recentMessage in
                        NavigationLink {
                            ChatLogView(user: user)
                        } label: {
                            HStack(spacing: 12) {
                                KFImage(URL(string: recentMessage.profileImageUrl))
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: 48, height: 48)
                                    .cornerRadius(8)
                                    .scaledToFit()

                                VStack(alignment: .leading, spacing: 8) {
                                    Text(recentMessage.fullname)
                                        .font(.subheadline)
                                        .foregroundColor(Color(.label))
                                    Text(recentMessage.text)
                                        .font(.subheadline)
                                        .foregroundColor(.gray)
                                        .multilineTextAlignment(.leading)
                                        .lineLimit(2)
                                }

                                Spacer()

                                Text("22d")
                                    .font(.system(size: 14, weight: .semibold))
                            }
                        }
                    }
                }
            }
        }
        .fullScreenCover(isPresented: $shouldShowNewMessageScreen) {
            CreateNewMessageView(didSelectNewUser: {user in
                print(user.fullname)
                self.shouldNavigateToChatLogView.toggle()
                self.user = user
            })
        }
        .padding(.horizontal)
    }
}

struct InboxView_Previews: PreviewProvider {
    static var previews: some View {
        InboxView()
    }
}
</code>```

Body:
For some reason, my entire scroll view is not appearing in my Inbox View. I thought it had something to do with the UI but after trying a bunch of re-arranging I've had no luck. I'm starting to think it has something to do with actually fetching the vm.recentMessage data but I really don't know.

import SwiftUI
import FirebaseFirestoreSwift
import FirebaseFirestore
import FirebaseAuth
import Kingfisher

struct RecentMessage: Identifiable {

    var id: String { documentId }

    let documentId: String
    let text, fullname: String
    let fromId, toId: String
    let profileImageUrl: String
    let timestamp: Timestamp

    init(documentId: String, data: [String: Any]) {
        self.documentId = documentId
        self.text = data["text"] as? String ?? ""
        self.fullname = data["fullname"] as? String ?? ""
        self.fromId = data["fromId"] as? String ?? ""
        self.toId = data["toId"] as? String ?? ""
        self.profileImageUrl = data["profileImageUrl"] as? String ?? ""
        self.timestamp = data["timestamp"] as? Timestamp ?? Timestamp(date: Date())
    }
}

class MainMessagesViewModel: ObservableObject {
    @Published var recentMessages = [RecentMessage]()
    @ObservedObject var authViewModel = AuthViewModel()
    @Published var errorMessage = ""

    init() {
        fetchRecentMessages()
    }

    private func fetchRecentMessages() {
        guard let uid = authViewModel.currentUser?.uid else { return }

        Firestore.firestore().collection("recent_messages").document(uid).collection("recent_messages")
            .document(uid)
            .collection("messages")
            .order(by: "timestamp")
            .addSnapshotListener { querySnapshot, error in
                if let error = error {
                    self.errorMessage = "Failed to listen for recent messages: \(error)"
                    print(error)
                    return
                }

                querySnapshot?.documentChanges.forEach({ change in
                    let docId = change.document.documentID

                    if let index = self.recentMessages.firstIndex(where: { rm in
                        return rm.documentId == docId
                    }) {
                        self.recentMessages.remove(at: index)
                    }

                    self.recentMessages.insert(.init(documentId: docId, data: change.document.data()), at: 0)

                })

        }
    }
}

struct InboxView: View {
    @ObservedObject var searchViewModel = SearchViewModel()
    @ObservedObject var vm = MainMessagesViewModel()
    @State private var selectedFilter: InboxViewModel = .messages
    @Namespace var animation
    @State var shouldShowNewMessageScreen = false
    @State var shouldNavigateToChatLogView = false
    @State var user: User?

    var body: some View {
        VStack (alignment: .leading) {
            NavigationLink("", isActive: $shouldNavigateToChatLogView) {
                ChatLogView(user: user)
            }
            Text("Inbox")
                .font(.title)
            HStack (alignment: .center) {
                SearchBar(text: $searchViewModel.searchText)
                Button {
                    shouldShowNewMessageScreen.toggle()
                } label: {
                    Image(systemName: "square.and.pencil")
                        .resizable()
                        .frame(width: 24, height: 24)
                }
            }
            ScrollView {
                LazyVStack {
                    ForEach(vm.recentMessages) { recentMessage in
                        NavigationLink {
                            ChatLogView(user: user)
                        } label: {
                            HStack(spacing: 12) {
                                KFImage(URL(string: recentMessage.profileImageUrl))
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: 48, height: 48)
                                    .cornerRadius(8)
                                    .scaledToFit()

                                VStack(alignment: .leading, spacing: 8) {
                                    Text(recentMessage.fullname)
                                        .font(.subheadline)
                                        .foregroundColor(Color(.label))
                                    Text(recentMessage.text)
                                        .font(.subheadline)
                                        .foregroundColor(.gray)
                                        .multilineTextAlignment(.leading)
                                        .lineLimit(2)
                                }

                                Spacer()

                                Text("22d")
                                    .font(.system(size: 14, weight: .semibold))
                            }
                        }
                    }
                }
            }
        }
        .fullScreenCover(isPresented: $shouldShowNewMessageScreen) {
            CreateNewMessageView(didSelectNewUser: {user in
                print(user.fullname)
                self.shouldNavigateToChatLogView.toggle()
                self.user = user
            })
        }
        .padding(.horizontal)
    }
}

struct InboxView_Previews: PreviewProvider {
    static var previews: some View {
        InboxView()
    }
}


问:
Force my client to use TLS1.2 to access my web application, if not then return an error message
TLS 1.0,1.1,1.2 are enabled in my web server now.
TLS1.0,1.1 cannot be disabled because I have a mobile app that will call my API through TLS1.0,1.1.
I would like to enforce my clients to use TLS1.2 to access my web portal, and if they don't, I would return an error message to them.
Is there a way to do it programmatically?

Both of my web application & mobile app are already in production and they are using same port 443.
Someone suggest me to clone my web application and host in another server that disabled TLS1.0,1.1. But I cannot change the link of my website & the API URL since they were already in production.


问:
React.js Framer-motion Usestate laggy
I'm currently creating a slider in next.js and react.js. While my animation is not laggy, I have found that there is a serious (1-3 sec) delay between the time someone clicks the button and the time it animates (and when the page opens). Here is my component's code:
(PS: I think the problem is useState, although I may be wrong. Is there a faster alternative?)

import {motion, useMotionValue, animate, useTransform} from 'framer-motion'
import * as React from 'react'
import { useState, useEffect } from 'react'
import { getIndex, useFlubber } from "./use-flubber";
import {paths} from './paths.jsx'

const colors = [
  '#000000',
  '#000000'
]

export default function AnimationBar(){
  const [isLong, setIsLong] = useState(false)
  const [color, setColor] = useState('black')

  const [pathIndex, setPathIndex] = useState(1);
  const progress = useMotionValue(pathIndex);
  const fill = useTransform(progress, paths.map(getIndex), colors);
  const path = useFlubber(progress, paths);

  return(

    <motion.svg
      width="300"
      height="100"
      viewBox="0 0 300 100"
      initial="hidden"
      animate="visible"
      className="justify-center mx-auto">

      <motion.line
      x1 = "50"
      y1 = "30"
      x2 ="250"
      y2 = "30"
      stroke="#570df8"
      variants={{
        short: {
          x2: 50
        },
        long: {
          x2: 200
        }
      }}
      animate={isLong ? "long" : "short"}
        />

      <motion.g
        transform="translate(40 18)"
      clip-path="url(#_clipPath_rwZJXlpW1ubtVOGd58AkztYmsTFUvvCx)"
        >
      <motion.path
       d={path}
      fill={fill}
        stroke="none"
        />
      </motion.g>

      <motion.text
        x={75}
        y={40}
        fontSize={24}
        fill={fill}
        animate={isLong ? "black" : "white"}

      >
        {isLong ? "Stop" : "Start"}
      </motion.text>
      <motion.line
      x1 = "50"
      y1 = "30"
      x2 ="50"
      y2 = "30"
      stroke="black"
      opacity="0"

      onClick={() => {
//invisible button that sets if it should be long or not
        setIsLong(!isLong)

        const animation = animate(progress, pathIndex, {
          duration: 0.3,
          ease: "easeInOut",
          onComplete: () => {
            if (isLong == false) {
              progress.set(0);
              setPathIndex(1);
            } else {
              setPathIndex(0);
            }
          }
        });

        return () => animation.stop();

      }}
        />
    </motion.svg>

  )
}```

Thanks!

Title: React.js Framer-motion Usestate laggy

Body:
I'm currently creating a slider in next.js and react.js. While my animation is not laggy, I have found that there is a serious (1-3 sec) delay between the time someone clicks the button and the time it animates (and when the page opens). Here is my component's code:
(PS: I think the problem is useState, although I may be wrong. Is there a faster alternative?)

import {motion, useMotionValue, animate, useTransform} from 'framer-motion'
import * as React from 'react'
import { useState, useEffect } from 'react'
import { getIndex, useFlubber } from "./use-flubber";
import {paths} from './paths.jsx'

const colors = [
  '#000000',
  '#000000'
]

export default function AnimationBar(){
  const [isLong, setIsLong] = useState(false)
  const [color, setColor] = useState('black')

  const [pathIndex, setPathIndex] = useState(1);
  const progress = useMotionValue(pathIndex);
  const fill = useTransform(progress, paths.map(getIndex), colors);
  const path = useFlubber(progress, paths);

  return(

    <motion.svg
      width="300"
      height="100"
      viewBox="0 0 300 100"
      initial="hidden"
      animate="visible"
      className="justify-center mx-auto">

      <motion.line
      x1 = "50"
      y1 = "30"
      x2 ="250"
      y2 = "30"
      stroke="#570df8"
      variants={{
        short: {
          x2: 50
        },
        long: {
          x2: 200
        }
      }}
      animate={isLong ? "long" : "short"}
        />

      <motion.g
        transform="translate(40 18)"
      clip-path="url(#_clipPath_rwZJXlpW1ubtVOGd58AkztYmsTFUvvCx)"
        >
      <motion.path
       d={path}
      fill={fill}
        stroke="none"
        />
      </motion.g>

      <motion.text
        x={75}
        y={40}
        fontSize={24}
        fill={fill}
        animate={isLong ? "black" : "white"}

      >
        {isLong ? "Stop" : "Start"}
      </motion.text>
      <motion.line
      x1 = "50"
      y1 = "30"
      x2 ="50"
      y2 = "30"
      stroke="black"
      opacity="0"

      onClick={() => {
//invisible button that sets if it should be long or not
        setIsLong(!isLong)

        const animation = animate(progress, pathIndex, {
          duration: 0.3,
          ease: "easeInOut",
          onComplete: () => {
            if (isLong == false) {
              progress.set(0);
              setPathIndex(1);
            } else {
              setPathIndex(0);
            }
          }
        });

        return () => animation.stop();

      }}
        />
    </motion.svg>

  )
}

Thanks!


问:
How to properly add inline label and logarithmic colour scale on 2D lien plot?
I am looking for a 2Dline plot with inline labels and logarithmic color bar scale.
So far, I plot the inline label, but the problem is each line showing more than one label.

Here is my script:

```<code>num=np.linspace(2, 10, 15)
en=[0.000001,0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]
dis=[]
for i in en:
    for j in num:
        dist=0.48*j -0.33*np.log10(i)  -1.4
        r=10**dist
        dis.append(r)
dd=np.array(dis)
AA=dd.reshape(10, 15)
D=pd.DataFrame(AA)
D=np.transpose(D)
m=pd.DataFrame(num)
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(m[0], D[0], label='$0.000001{J/m^3}$',color='b', lw=2.5, linestyle='solid')
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[1], label='$0.00001$',color='b', lw=2.5, linestyle='solid', alpha=0.8)
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[2],label='$0.0001$',color='b', lw=2.5, linestyle='solid', alpha=0.6)
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[3],label='$0.001$',color='b', lw=2.5, linestyle='solid', alpha=0.4)
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[4],label='$0.01$',color='b', lw=2.5, linestyle='solid', alpha=0.4)
ax.plot(m[0], D[5],label='$0.1$',color='r', lw=2.5, linestyle='solid', alpha=0.2)
ax.plot(m[0], D[6], label='$1$',color='r', lw=2.5, linestyle='solid', alpha=0.4)
ax.plot(m[0], D[7], label='$10$',color='r', lw=2.5, linestyle='solid', alpha=0.6)
ax.plot(m[0], D[8], label='$100$',color='r', lw=2.5, linestyle='solid', alpha=0.8)
ax.plot(m[0], D[9],  label='$01000$',color='r', lw=2.5, linestyle='solid')
#ax.legend(inline=True, fontsize=10)
ax.set_yscale('log')
ax.set_xlim(2, 10)
ax.set_ylim(1, 20000)
ax.xaxis.set_tick_params(labelsize=14)
ax.yaxis.set_tick_params(labelsize=14)

for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_linewidth(2)
plt.show()

</code>```

Here is what I get so far

Body:
I am looking for a 2Dline plot with inline labels and logarithmic color bar scale.
So far, I plot the inline label, but the problem is each line showing more than one label.

Here is my script:

num=np.linspace(2, 10, 15)
en=[0.000001,0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]
dis=[]
for i in en:
    for j in num:
        dist=0.48*j -0.33*np.log10(i)  -1.4
        r=10**dist
        dis.append(r)
dd=np.array(dis)
AA=dd.reshape(10, 15)
D=pd.DataFrame(AA)
D=np.transpose(D)
m=pd.DataFrame(num)
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(m[0], D[0], label='$0.000001{J/m^3}$',color='b', lw=2.5, linestyle='solid')
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[1], label='$0.00001$',color='b', lw=2.5, linestyle='solid', alpha=0.8)
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[2],label='$0.0001$',color='b', lw=2.5, linestyle='solid', alpha=0.6)
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[3],label='$0.001$',color='b', lw=2.5, linestyle='solid', alpha=0.4)
labelLines(plt.gca().get_lines(), zorder=2, align=True, fontsize=14)
ax.plot(m[0], D[4],label='$0.01$',color='b', lw=2.5, linestyle='solid', alpha=0.4)
ax.plot(m[0], D[5],label='$0.1$',color='r', lw=2.5, linestyle='solid', alpha=0.2)
ax.plot(m[0], D[6], label='$1$',color='r', lw=2.5, linestyle='solid', alpha=0.4)
ax.plot(m[0], D[7], label='$10$',color='r', lw=2.5, linestyle='solid', alpha=0.6)
ax.plot(m[0], D[8], label='$100$',color='r', lw=2.5, linestyle='solid', alpha=0.8)
ax.plot(m[0], D[9],  label='$01000$',color='r', lw=2.5, linestyle='solid')
#ax.legend(inline=True, fontsize=10)
ax.set_yscale('log')
ax.set_xlim(2, 10)
ax.set_ylim(1, 20000)
ax.xaxis.set_tick_params(labelsize=14)
ax.yaxis.set_tick_params(labelsize=14)

for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_linewidth(2)
plt.show()

Here is what I get so far


问:
JACoP Colocalization Macro Errors Galore
 I've tried countless combinations of paths to try and get my macro working to analyze a very large set of images using JACoP. Any suggestions on what might be the issue?

this iteration got me closest (I think) to getting it to work. It even loads images, as shown in attached photos, but won't actually analyze the images themselves. Im thinking it might have something to do with me improperly setting up the loop to repeat itself? also maybe I'm designating channels incorrectly? pretty lost on what to do next, and there aren't any answers I've found on the web.

```<code>#@ File (label = "Input directory", style = "directory") input
#@ File (label = "Output directory", style = "directory") output
#@ String (label = "File suffix", value = ".nd2") suffix

// See also Process_Folder.py for a version of this code
// in the Python scripting language.

input = "/Users/alexandrapowell/Desktop/221223B31A3/"
output = "/Users/alexandrapowell/Desktop/221223B31A3batchh/"
processFolder(input);

// function to scan folders/subfolders/files to find files with correct suffix
function processFolder(input) {
    list = getFileList(input);
    fileList = Array.sort(list);
    for (i = 0; i < list.length; i++) {
        if(File.isDirectory(input + File.separator + list[i]))
            processFolder(input + File.separator + list[i]);
        if(endsWith(list[i], suffix))
            processFile(input, output, list[i]);
    }
}

function processFile(input, output, file) {
    open(list[i])
    run("JACoP ", "imga=0 imgb=1 thra=15000 thrb=3000 get_pearsons get_manders get_overlap");
    // Do the processing here by adding your own code.
    // Leave the print statements until things work, then remove them.
    print("Processing: " + input + File.separator + file);
    saveAs("Text", output + File.separator + "_coloc.txt")
    print("Saving to: " + output);
    run("Close");
    run("Close All");

}
</code>```

Body:
 I've tried countless combinations of paths to try and get my macro working to analyze a very large set of images using JACoP. Any suggestions on what might be the issue?

this iteration got me closest (I think) to getting it to work. It even loads images, as shown in attached photos, but won't actually analyze the images themselves. Im thinking it might have something to do with me improperly setting up the loop to repeat itself? also maybe I'm designating channels incorrectly? pretty lost on what to do next, and there aren't any answers I've found on the web.

#@ File (label = "Input directory", style = "directory") input
#@ File (label = "Output directory", style = "directory") output
#@ String (label = "File suffix", value = ".nd2") suffix

// See also Process_Folder.py for a version of this code
// in the Python scripting language.

input = "/Users/alexandrapowell/Desktop/221223B31A3/"
output = "/Users/alexandrapowell/Desktop/221223B31A3batchh/"
processFolder(input);

// function to scan folders/subfolders/files to find files with correct suffix
function processFolder(input) {
    list = getFileList(input);
    fileList = Array.sort(list);
    for (i = 0; i < list.length; i++) {
        if(File.isDirectory(input + File.separator + list[i]))
            processFolder(input + File.separator + list[i]);
        if(endsWith(list[i], suffix))
            processFile(input, output, list[i]);
    }
}

function processFile(input, output, file) {
    open(list[i])
    run("JACoP ", "imga=0 imgb=1 thra=15000 thrb=3000 get_pearsons get_manders get_overlap");
    // Do the processing here by adding your own code.
    // Leave the print statements until things work, then remove them.
    print("Processing: " + input + File.separator + file);
    saveAs("Text", output + File.separator + "_coloc.txt")
    print("Saving to: " + output);
    run("Close");
    run("Close All");

}


问:
Keep getting Undeclared identifier 'entry_price'
I keep geting the below error below when using my script and not sure why. I am using version 4 but it appears it isn't liking my entry_price variable for some reason contrantly saying Undeclared identifier for it.

Compilation error. Line 54: Undeclared identifier 'entry_price';
line 55: Undeclared identifier 'entry_price';
line 58: Undeclared identifier 'stopLoss';
line 58: Undeclared identifier 'takeProfit';
line 58: Variable 'stopLoss' is not found in scope 'global_#0_#0', cannot register side effect;
line 58: Variable 'takeProfit' is not found in scope 'global_#0_#0', cannot register side effect;
line 65: Undeclared identifier 'entryPrice';
line 66: Undeclared identifier 'entryPrice';
line 69: Undeclared identifier 'stopLoss';
line 69: Undeclared identifier 'takeProfit';
line 69: Variable 'stopLoss' is not found in scope 'global_#0_#1', cannot register side effect;
line 69: Variable 'takeProfit' is not found in scope 'global_#0_#1', cannot register side effect;
line 69: Variable 'stopLoss' is not found in scope 'global_#0_#0', cannot register side effect;
line 69: Variable 'takeProfit' is not found in scope 'global_#0_#0', cannot register side effect

Here if the script I wrote below

```<code>//@version=4
// Swing trading strategy for TradingView

// This strategy is designed for medium-term trades with a holding period of several days to a few weeks.

// The strategy is based on the idea of identifying trends in the market and then buying or selling
// when the price reaches certain levels of support or resistance.

// Set the parameters for the strategy
accountBalance = 5000
pipSize = .1
// The number of bars to look back when calculating the moving averages
maLookbackPeriod = 50

// The number of bars to look back when identifying support and resistance levels
srLookbackPeriod = 20

// The number of ticks to place the stop loss and take profit orders
stopLossPips = 50
takeProfitPips = 100

// The amount of capital to risk on each trade, expressed as a percentage of the account balance
riskPerTrade = 0.01
// The main strategy script

// Calculate the moving averages
maFast = sma(close, maLookbackPeriod)
maSlow = sma(close, maLookbackPeriod*2)

// Check if the fast moving average has crossed above or below the slow moving average
crossedAbove = crossover(maFast, maSlow)
crossedBelow = crossunder(maFast, maSlow)

// Calculate the support and resistance levels
support = lowest(low, srLookbackPeriod)
resistance = highest(high, srLookbackPeriod)

// Check if the price has reached the support or resistance levels
atSupport = close == support
atResistance = close == resistance

// Only enter a trade if the fast moving average has crossed the slow moving average, and the price
// has reached a support or resistance level
if (crossedAbove or crossedBelow) and (atSupport or atResistance)

    // Calculate the trade size based on the risk per trade parameter
    tradeSize = floor(riskPerTrade * accountBalance / stopLossPips / pipSize)

    // If the fast moving average has crossed above the slow moving average, and the price is at
    // the support level, enter a long trade
    if (crossedAbove and atSupport)

        // Calculate the stop loss and take profit levels
        stopLoss = (entry_price - stopLossPips * pipSize)
        takeProfit = (entry_price + takeProfitPips * pipSize)

        // Place the trade
        strategy.entry("Long", strategy.long, tradeSize, stopLoss, takeProfit)

    // If the fast moving average has crossed below the slow moving average, and the price is at
    // the resistance level, enter a short trade
    else if (crossedBelow and atResistance)

        // Calculate the stop loss and take profit levels
        stopLoss = entryPrice + stopLossPips * pipSize
        takeProfit = entryPrice - takeProfitPips * pipSize

        // Place the trade
        strategy.entry("Short", strategy.short, tradeSize, stopLoss, takeProfit)

</code>```

Is entry_price not a global variable or something?

Body:
I keep geting the below error below when using my script and not sure why. I am using version 4 but it appears it isn't liking my entry_price variable for some reason contrantly saying Undeclared identifier for it.

Compilation error. Line 54: Undeclared identifier 'entry_price';
line 55: Undeclared identifier 'entry_price';
line 58: Undeclared identifier 'stopLoss';
line 58: Undeclared identifier 'takeProfit';
line 58: Variable 'stopLoss' is not found in scope 'global_#0_#0', cannot register side effect;
line 58: Variable 'takeProfit' is not found in scope 'global_#0_#0', cannot register side effect;
line 65: Undeclared identifier 'entryPrice';
line 66: Undeclared identifier 'entryPrice';
line 69: Undeclared identifier 'stopLoss';
line 69: Undeclared identifier 'takeProfit';
line 69: Variable 'stopLoss' is not found in scope 'global_#0_#1', cannot register side effect;
line 69: Variable 'takeProfit' is not found in scope 'global_#0_#1', cannot register side effect;
line 69: Variable 'stopLoss' is not found in scope 'global_#0_#0', cannot register side effect;
line 69: Variable 'takeProfit' is not found in scope 'global_#0_#0', cannot register side effect

Here if the script I wrote below

//@version=4
// Swing trading strategy for TradingView

// This strategy is designed for medium-term trades with a holding period of several days to a few weeks.

// The strategy is based on the idea of identifying trends in the market and then buying or selling
// when the price reaches certain levels of support or resistance.

// Set the parameters for the strategy
accountBalance = 5000
pipSize = .1
// The number of bars to look back when calculating the moving averages
maLookbackPeriod = 50

// The number of bars to look back when identifying support and resistance levels
srLookbackPeriod = 20

// The number of ticks to place the stop loss and take profit orders
stopLossPips = 50
takeProfitPips = 100

// The amount of capital to risk on each trade, expressed as a percentage of the account balance
riskPerTrade = 0.01
// The main strategy script

// Calculate the moving averages
maFast = sma(close, maLookbackPeriod)
maSlow = sma(close, maLookbackPeriod*2)

// Check if the fast moving average has crossed above or below the slow moving average
crossedAbove = crossover(maFast, maSlow)
crossedBelow = crossunder(maFast, maSlow)

// Calculate the support and resistance levels
support = lowest(low, srLookbackPeriod)
resistance = highest(high, srLookbackPeriod)

// Check if the price has reached the support or resistance levels
atSupport = close == support
atResistance = close == resistance

// Only enter a trade if the fast moving average has crossed the slow moving average, and the price
// has reached a support or resistance level
if (crossedAbove or crossedBelow) and (atSupport or atResistance)

    // Calculate the trade size based on the risk per trade parameter
    tradeSize = floor(riskPerTrade * accountBalance / stopLossPips / pipSize)

    // If the fast moving average has crossed above the slow moving average, and the price is at
    // the support level, enter a long trade
    if (crossedAbove and atSupport)

        // Calculate the stop loss and take profit levels
        stopLoss = (entry_price - stopLossPips * pipSize)
        takeProfit = (entry_price + takeProfitPips * pipSize)

        // Place the trade
        strategy.entry("Long", strategy.long, tradeSize, stopLoss, takeProfit)

    // If the fast moving average has crossed below the slow moving average, and the price is at
    // the resistance level, enter a short trade
    else if (crossedBelow and atResistance)

        // Calculate the stop loss and take profit levels
        stopLoss = entryPrice + stopLossPips * pipSize
        takeProfit = entryPrice - takeProfitPips * pipSize

        // Place the trade
        strategy.entry("Short", strategy.short, tradeSize, stopLoss, takeProfit)

Is entry_price not a global variable or something?


问:
Turtle moving at random speeds
I was working on a pong game using python turtle. The ball that I am using python turtle is moving at random speeds. Sometimes it is too slow and sometimes it accelerates. I have no clue what is going on. This is the code that I have written for the pong ball -

```<code>ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.dx = 0.1
ball.dy = 0.1

while True:
window.update()
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
</code>```

I tried changing the dx and dy to a certain number to alter the speed but the ball rarely follows the command and is going too slow or fast.

Title: Turtle moving at random speeds

Body:
I was working on a pong game using python turtle. The ball that I am using python turtle is moving at random speeds. Sometimes it is too slow and sometimes it accelerates. I have no clue what is going on. This is the code that I have written for the pong ball -

ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.dx = 0.1
ball.dy = 0.1

while True:
window.update()
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)

I tried changing the dx and dy to a certain number to alter the speed but the ball rarely follows the command and is going too slow or fast.


问:
SMB2 QUERY_DIRECTORY Compounded Response
Im trying to implement a lightweight SMB2 server on a very low resource system (no dynamic memory allocation).  The system also only allows me to iterate directory contents so I have no idea the total file count etc.  In response to a QUERY_DIRECTORY request, I think I have 2 options

1.) Enumerate the directory twice, firstly to calculate the total length of the response and the second time stream the results back

2.) My hope is that I can use compounded responses and return a response for each file using the NEXT_COMMAND field to indicate it is compounded however it isnt clear to me that the spec allows for this sort of behaviour or whether the compound response is ONLY to allow 2 seperate requests to be answered in one response.

My real goal is to implement a minimal functionality to be compatible with vanilla windows explorer to list/read and write files without too many bells and wistles


问:
How can I fix the error code 400600 on python-KuCoin API's?
I've been working on creating a trading bot for KuCoin using API's recently and have been getting into some small roadblocks. I overcame all except one which is an error code "400600" I've looked everywhere and can't even find a website or conversation mentioning this error message. I looked around lots of discussions and websites for my other issues and that worked but for this one, I can't find any documentation about it. The full error is

200-{"code":"400600","msg":"validation.createOrder.symbolNotAvailable"}

The symbol I'm using is 'XRP-USDT' which works for getting the price with the API's and is exactly how I've seen it in others code and bots.

this is the order part of my code.

```<code>if True:
    try:
        order = client.create_market_order('XRP-USDT', 'buy' , 'market', size='3')
        buy_XRP = m_client.get_ticker('XRP-USDT')
        print()
    except Exception as e:
        print(f'Error placing order: {e}')
</code>```

(if True is just a way to test it without having to wait for my buy limitations to be met)

Body:
I've been working on creating a trading bot for KuCoin using API's recently and have been getting into some small roadblocks. I overcame all except one which is an error code "400600" I've looked everywhere and can't even find a website or conversation mentioning this error message. I looked around lots of discussions and websites for my other issues and that worked but for this one, I can't find any documentation about it. The full error is

200-{"code":"400600","msg":"validation.createOrder.symbolNotAvailable"}

The symbol I'm using is 'XRP-USDT' which works for getting the price with the API's and is exactly how I've seen it in others code and bots.

this is the order part of my code.

if True:
    try:
        order = client.create_market_order('XRP-USDT', 'buy' , 'market', size='3')
        buy_XRP = m_client.get_ticker('XRP-USDT')
        print()
    except Exception as e:
        print(f'Error placing order: {e}')

(if True is just a way to test it without having to wait for my buy limitations to be met)


问:
Is it possible to use a GSM modem to create my own "SMS SERVER"
I am building an app which requires phone number authentication, but all the online SMS API providers are relatively expensive compared to the SMS prices I can get from Mobile Service Providers here in my country.

Let me start by saying, I KNOW it's not possible to send SMS programaticaly directly but...

My server runs on cloud, so I can't exactly plug in a GSM module to the server computer, but would it be a viable option if I create an SMS server using a GSM module and a Raspberry PI, then have the Raspberry PI have a connection to my Server so it will be notified whenever there is a new authentication to be, and then it will receive the users information and send the user the authentication SMS. Is this a viable idea, I know this will work, I'm just curious speed wise?


问:
How to create consistent time series dataset using an inconsistent time series dataset?
I am new to data science and machine learning, and I am working on a project involving time series data from wearable devices (using Python programming environment). I have the sampling frequency of each sensor modality for each device. Some of the devices have provided their sensor data as datapoints with timestamps. For example, the dataset for the accelerometer sensor of one device includes the following columns:

timestamp: a UNIX timestamp for each recorded datapoint

ax: pitch

ay: roll

az: yaw

I am planning to smooth the accelerometer signal by applying a 1-minute central moving window to the time series data.

However, I have noticed that there are sometimes gaps in the data, where there are fewer data points than expected within a given time window (based on the sampling rate). In addition, there are occasional cases where there are more data points than expected within a time window. If I apply a central moving average to this inconsistent data, it will likely produce incorrect results.

To handle gaps and extra data points in my accelerometer sensor data, I have come up with the following solution:

Create a new pandas dataframe using the date range of the first and last timestamp of the original dataset.

Round the timestamps of both datasets to the nearest second.

Select the starting timestamp of the inconsistent dataset (rounded to the nearest second), and select all data points with the same timestamp (which may be fewer or more than expected). Replace these data points in my new dataframe with the same timestamp.

Repeat this process by looping through the inconsistent dataset and adding one second to the starting time at each iteration.

```<code># Get the starting time and end time from the inconsistent dataframe
        start_time = df_temp.loc[0, 'timestamp'].replace(tzinfo=datetime.timezone.utc)
        end_time = df_temp.loc[df_temp.index[-1], 'timestamp'].replace(tzinfo=datetime.timezone.utc)

        # Create new dataframe with the datarange
        date_range = pd.date_range(start=start_time, end=end_time, freq='10ms')
        df = pd.DataFrame(index=date_range, columns=['timestamp', 'acc_x_avg', 'acc_y_avg', 'acc_z_avg', 'gyro_x_avg', 'gyro_y_avg', 'gyro_z_avg'])
        df['timestamp'] = [index for index in df.index]
        df['timestamp'] = pd.to_datetime(df['timestamp']).dt.round('S').dt.strftime('%Y-%m-%d %H:%M:%S')

        df_temp['timestamp_iso'] = df_temp['timestamp']
        df_temp['timestamp'] = pd.to_datetime(df_temp['timestamp']).dt.round('S').dt.strftime('%Y-%m-%d %H:%M:%S')

        current_second = df.loc[df.index[0], 'timestamp']
        current_second_iso = datetime.datetime.strptime(current_second, "%Y-%m-%d %H:%M:%S")
        end_second = df.loc[df.index[-1], 'timestamp']
        end_second_iso = datetime.datetime.strptime(end_second, "%Y-%m-%d %H:%M:%S")
        while current_second_iso < end_second_iso:
            progress += frequency
            # Select both dataframes current second indices
            current_second_indices = df_temp.loc[df_temp['timestamp'] == str(current_second_iso)].index #integers
            current_second_new_indices = df.loc[df['timestamp'] == str(current_second_iso)].index #datetime
            print(file_path, f'{(progress*frequency)/len(df)}%')
            for i in range(len(current_second_new_indices)):
                if (i < len(current_second_indices)):
                    df.loc[current_second_new_indices[i], 'timestamp'] = df_temp.loc[current_second_indices[i], 'timestamp']
                    df.loc[current_second_new_indices[i], 'acc_x_avg'] = df_temp.loc[current_second_indices[i], 'acc_x']
                    df.loc[current_second_new_indices[i], 'acc_y_avg'] = df_temp.loc[current_second_indices[i], 'acc_y']
                    df.loc[current_second_new_indices[i], 'acc_z_avg'] = df_temp.loc[current_second_indices[i], 'acc_z']
                    df.loc[current_second_new_indices[i], 'gyro_x_avg'] = df_temp.loc[current_second_indices[i], 'gyro_x']
                    df.loc[current_second_new_indices[i], 'gyro_y_avg'] = df_temp.loc[current_second_indices[i], 'gyro_y']
                    df.loc[current_second_new_indices[i], 'gyro_z_avg'] = df_temp.loc[current_second_indices[i], 'gyro_z']

            current_second_iso = current_second_iso + datetime.timedelta(seconds=1)
</code>```

I believe there may be faster ways to handle this issue.

Body:
I am new to data science and machine learning, and I am working on a project involving time series data from wearable devices (using Python programming environment). I have the sampling frequency of each sensor modality for each device. Some of the devices have provided their sensor data as datapoints with timestamps. For example, the dataset for the accelerometer sensor of one device includes the following columns:

timestamp: a UNIX timestamp for each recorded datapoint

ax: pitch

ay: roll

az: yaw

I am planning to smooth the accelerometer signal by applying a 1-minute central moving window to the time series data.

However, I have noticed that there are sometimes gaps in the data, where there are fewer data points than expected within a given time window (based on the sampling rate). In addition, there are occasional cases where there are more data points than expected within a time window. If I apply a central moving average to this inconsistent data, it will likely produce incorrect results.

To handle gaps and extra data points in my accelerometer sensor data, I have come up with the following solution:

Create a new pandas dataframe using the date range of the first and last timestamp of the original dataset.

Round the timestamps of both datasets to the nearest second.

Select the starting timestamp of the inconsistent dataset (rounded to the nearest second), and select all data points with the same timestamp (which may be fewer or more than expected). Replace these data points in my new dataframe with the same timestamp.

Repeat this process by looping through the inconsistent dataset and adding one second to the starting time at each iteration.

# Get the starting time and end time from the inconsistent dataframe
        start_time = df_temp.loc[0, 'timestamp'].replace(tzinfo=datetime.timezone.utc)
        end_time = df_temp.loc[df_temp.index[-1], 'timestamp'].replace(tzinfo=datetime.timezone.utc)

        # Create new dataframe with the datarange
        date_range = pd.date_range(start=start_time, end=end_time, freq='10ms')
        df = pd.DataFrame(index=date_range, columns=['timestamp', 'acc_x_avg', 'acc_y_avg', 'acc_z_avg', 'gyro_x_avg', 'gyro_y_avg', 'gyro_z_avg'])
        df['timestamp'] = [index for index in df.index]
        df['timestamp'] = pd.to_datetime(df['timestamp']).dt.round('S').dt.strftime('%Y-%m-%d %H:%M:%S')

        df_temp['timestamp_iso'] = df_temp['timestamp']
        df_temp['timestamp'] = pd.to_datetime(df_temp['timestamp']).dt.round('S').dt.strftime('%Y-%m-%d %H:%M:%S')

        current_second = df.loc[df.index[0], 'timestamp']
        current_second_iso = datetime.datetime.strptime(current_second, "%Y-%m-%d %H:%M:%S")
        end_second = df.loc[df.index[-1], 'timestamp']
        end_second_iso = datetime.datetime.strptime(end_second, "%Y-%m-%d %H:%M:%S")
        while current_second_iso < end_second_iso:
            progress += frequency
            # Select both dataframes current second indices
            current_second_indices = df_temp.loc[df_temp['timestamp'] == str(current_second_iso)].index #integers
            current_second_new_indices = df.loc[df['timestamp'] == str(current_second_iso)].index #datetime
            print(file_path, f'{(progress*frequency)/len(df)}%')
            for i in range(len(current_second_new_indices)):
                if (i < len(current_second_indices)):
                    df.loc[current_second_new_indices[i], 'timestamp'] = df_temp.loc[current_second_indices[i], 'timestamp']
                    df.loc[current_second_new_indices[i], 'acc_x_avg'] = df_temp.loc[current_second_indices[i], 'acc_x']
                    df.loc[current_second_new_indices[i], 'acc_y_avg'] = df_temp.loc[current_second_indices[i], 'acc_y']
                    df.loc[current_second_new_indices[i], 'acc_z_avg'] = df_temp.loc[current_second_indices[i], 'acc_z']
                    df.loc[current_second_new_indices[i], 'gyro_x_avg'] = df_temp.loc[current_second_indices[i], 'gyro_x']
                    df.loc[current_second_new_indices[i], 'gyro_y_avg'] = df_temp.loc[current_second_indices[i], 'gyro_y']
                    df.loc[current_second_new_indices[i], 'gyro_z_avg'] = df_temp.loc[current_second_indices[i], 'gyro_z']

            current_second_iso = current_second_iso + datetime.timedelta(seconds=1)

I believe there may be faster ways to handle this issue.


问:
Can not create a standalone EXE with all files needed inside using WinUI3
I am developing a WinUI3 application. I installed the latest Visual Studio Community 2022 and WinUI3 (Windows SDK) from the Visual Studio installer and am using Template Studio download from 2 weeks ago.

I have a couple of issues but I will explain my first issue here in this post.

What is the correct way now using latest SDK for January 5 2023.

I can not put the all required files into a single EXE. I googled and youtubed a solution but for some reason I see a bunch of files alongside the EXE. I tried self-contained, added a tag in project file, packaged and unpackaged. Published and Released format. Still no dice.


问:
How do I upload images from external URLs onto Firebase? (using next.js)
Basically I'm using next.js and I'm making a program that generates images using Openai's Dalle2 API (artificial intelligence), and then uploads it onto my firebase storage. How do I download these images when they are generated and upload them to the firebase storage? Everytime i try, I just end up getting a 'application/octet-stream' file type uploaded and it doesn't work.

This is my code:

    const [selectedFile, setSelectedFile] = useState(null);

    const generateImage = async () => {
        console.log('openai image start')
        const prompt = captionRef.current.value

        try {
            const response = await openai.createImage({
                prompt: prompt,
                n: 1,
                size: "256x256",
            })

            const imageUrl = response.data.data[0].url
            console.log('openai image generated')
            setSelectedFile(imageUrl)
            console.log(selectedFile)

        } catch (error) {
            if (error.response) {
                console.log(error.response.status);
                console.log(error.response.data);
            } else {
                console.log(error.message);
            }
        }
    }

    const uploadPost = async () => {
        if (loading) return;
        setLoading(true);
        //create post and add to firestore posts collection
        //get post id for new post
        //upload image to firebase storage with post id
        //get a download url from firebase storage and update original post with image

        const docRef = await addDoc(collection(db, 'posts'), {
            username: session.user.username,
            caption: captionRef.current.value,
            profileImg: session.user.image,
            timestamp: serverTimestamp()
        })

        console.log("New doc added with ID", docRef.id);
        console.log(selectedFile)

        //**PROBLEM**
        const imageRef = ref(storage, `posts/${docRef.id}/image`)
        await uploadBytes(imageRef, selectedFile).then(async snapshot => {
            const downloadURL = await getDownloadURL(imageRef)
            await updateDoc(doc(db, 'posts', docRef.id), {
                image: downloadURL
            })
        })

        setLoading(false)
        setSelectedFile(null)
    }
```


问:
how to use dynamic table rowspan in vue?
It should be merged according to the category with the same product. If merged, the total price is calculated. I've tried nested v-for loops but it turn out wrong.

What is the best way to go about it?

The expected table structure-

The data-

```<code>[{
    category: 'category_1',
    product: '1',
    price: 1000,
    qty: 2,
  },
  {
    category: 'category_1',
    product: '1',
    price: 1000,
    qty: 1,
  },
  {
    category: 'category_2',
    product: '2',
    price: 2000,
    qty: 2,
  },
  {
    category: 'category_1',
    product: '3',
    price: 3000,
    qty: 1,
  },
  {
    category: 'category_2',
    product: '4',
    price: 4000,
    qty: 1,
  },
  {
    category: 'category_1',
    product: '5',
    price: 5000,
    qty: 1,
  },
  {
    category: 'category_1',
    product: '6',
    price: 1000,
    qty: 1,
  },
];
</code>```

Example Jsfiddle

https://jsfiddle.net/kw28tnm5/1/

NOTE-

The format of the data is okay to change.

Body:
It should be merged according to the category with the same product. If merged, the total price is calculated. I've tried nested v-for loops but it turn out wrong.

What is the best way to go about it?

The expected table structure-

The data-

[{
    category: 'category_1',
    product: '1',
    price: 1000,
    qty: 2,
  },
  {
    category: 'category_1',
    product: '1',
    price: 1000,
    qty: 1,
  },
  {
    category: 'category_2',
    product: '2',
    price: 2000,
    qty: 2,
  },
  {
    category: 'category_1',
    product: '3',
    price: 3000,
    qty: 1,
  },
  {
    category: 'category_2',
    product: '4',
    price: 4000,
    qty: 1,
  },
  {
    category: 'category_1',
    product: '5',
    price: 5000,
    qty: 1,
  },
  {
    category: 'category_1',
    product: '6',
    price: 1000,
    qty: 1,
  },
];

Example Jsfiddle

https://jsfiddle.net/kw28tnm5/1/

NOTE-

The format of the data is okay to change.


问:
Flutter app crashes just after wallpaper is set
flutter android application goes to hang state and immediately crashes just after wallpaper is set from the app.The wallpaper changes automatically every minute.
This crash issue was not found on my nokia device this error was found on a redmi device
This is my code below....

also this code is called in a periodic function using

await AndroidAlarmManager.periodic(
const Duration(minutes: 1), 1, myfunction);

```<code>``
  static Future<void> myfunction()async{
 final response = await http.get(Uri.parse(
            "my url here"));
        var jsonData = json.decode(response.body);
        results = jsonData;
        var url = results["urls"]["full"];
        String result;
        var progressString = Wallpaper.imageDownloadProgress(url);

        progressString.listen((data) {
          print("DataReceived: " + data);
        }, onDone: () async {
          if (Globals.selectedScreen.toString() == 'home') {
            try {
              await Wallpaper.homeScreen();
            } catch (e) {
              debugPrint(e);
            }
          } else if (Globals.selectedScreen.toString() == 'lock') {
            try {
              await Wallpaper.lockScreen();
            } catch (e) {
              debugPrint(e);
            }
          } else {
            try {
              await Wallpaper.bothScreen();
            } catch (e) {
              debugPrint(e);
            }
          }
        }}`
`
</code>```

`this is my terminal output when app got crashed

`
DataReceived: 100%

W/MIUIScout App(13194): Enter APP_SCOUT_WARNING State W/MIUIScout
App(13194): Event:APP_SCOUT_WARNING Thread:main backtrace: W/MIUIScout
App(13194):     at android.graphics.Bitmap.nativeCompress(Native
Method) W/MIUIScout App(13194):     at
android.graphics.Bitmap.compress(Bitmap.java:1445) W/MIUIScout
App(13194):     at
android.app.WallpaperManager.setBitmap(WallpaperManager.java:1535)
W/MIUIScout App(13194):     at
android.app.WallpaperManager.setBitmap(WallpaperManager.java:1506)
W/MIUIScout App(13194):     at
com.prateektimer.wallpaper.WallpaperPlugin.setHomeLockScreen(WallpaperPlugin.java:182)
W/MIUIScout App(13194):     at
com.prateektimer.wallpaper.WallpaperPlugin.onMethodCall(WallpaperPlugin.java:91)
W/MIUIScout App(13194):     at
io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
W/MIUIScout App(13194):     at
io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
W/MIUIScout App(13194):     at
io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:319)
W/MIUIScout App(13194):     at
io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown
Source:12) W/MIUIScout App(13194):     at
android.os.Handler.handleCallback(Handler.java:938) W/MIUIScout
App(13194):     at android.os.Handler.dispatchMessage(Handler.java:99)
W/MIUIScout App(13194):     at
android.os.Looper.loopOnce(Looper.java:210) W/MIUIScout App(13194):

at android.os.Looper.loop(Looper.java:299) W/MIUIScout App(13194):

at android.app.ActivityThread.main(ActivityThread.java:8168)
W/MIUIScout App(13194):     at java.lang.reflect.Method.invoke(Native
Method) W/MIUIScout App(13194):     at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
W/MIUIScout App(13194):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037) I/libc

(13194): Requested dump for tid 13194 (ample.app)`

Body:
flutter android application goes to hang state and immediately crashes just after wallpaper is set from the app.The wallpaper changes automatically every minute.
This crash issue was not found on my nokia device this error was found on a redmi device
This is my code below....

also this code is called in a periodic function using

await AndroidAlarmManager.periodic(
const Duration(minutes: 1), 1, myfunction);

``
  static Future<void> myfunction()async{
 final response = await http.get(Uri.parse(
            "my url here"));
        var jsonData = json.decode(response.body);
        results = jsonData;
        var url = results["urls"]["full"];
        String result;
        var progressString = Wallpaper.imageDownloadProgress(url);

        progressString.listen((data) {
          print("DataReceived: " + data);
        }, onDone: () async {
          if (Globals.selectedScreen.toString() == 'home') {
            try {
              await Wallpaper.homeScreen();
            } catch (e) {
              debugPrint(e);
            }
          } else if (Globals.selectedScreen.toString() == 'lock') {
            try {
              await Wallpaper.lockScreen();
            } catch (e) {
              debugPrint(e);
            }
          } else {
            try {
              await Wallpaper.bothScreen();
            } catch (e) {
              debugPrint(e);
            }
          }
        }}`
`

`this is my terminal output when app got crashed

`
DataReceived: 100%

W/MIUIScout App(13194): Enter APP_SCOUT_WARNING State W/MIUIScout
App(13194): Event:APP_SCOUT_WARNING Thread:main backtrace: W/MIUIScout
App(13194):     at android.graphics.Bitmap.nativeCompress(Native
Method) W/MIUIScout App(13194):     at
android.graphics.Bitmap.compress(Bitmap.java:1445) W/MIUIScout
App(13194):     at
android.app.WallpaperManager.setBitmap(WallpaperManager.java:1535)
W/MIUIScout App(13194):     at
android.app.WallpaperManager.setBitmap(WallpaperManager.java:1506)
W/MIUIScout App(13194):     at
com.prateektimer.wallpaper.WallpaperPlugin.setHomeLockScreen(WallpaperPlugin.java:182)
W/MIUIScout App(13194):     at
com.prateektimer.wallpaper.WallpaperPlugin.onMethodCall(WallpaperPlugin.java:91)
W/MIUIScout App(13194):     at
io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
W/MIUIScout App(13194):     at
io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
W/MIUIScout App(13194):     at
io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:319)
W/MIUIScout App(13194):     at
io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown
Source:12) W/MIUIScout App(13194):     at
android.os.Handler.handleCallback(Handler.java:938) W/MIUIScout
App(13194):     at android.os.Handler.dispatchMessage(Handler.java:99)
W/MIUIScout App(13194):     at
android.os.Looper.loopOnce(Looper.java:210) W/MIUIScout App(13194):

at android.os.Looper.loop(Looper.java:299) W/MIUIScout App(13194):

at android.app.ActivityThread.main(ActivityThread.java:8168)
W/MIUIScout App(13194):     at java.lang.reflect.Method.invoke(Native
Method) W/MIUIScout App(13194):     at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
W/MIUIScout App(13194):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037) I/libc

(13194): Requested dump for tid 13194 (ample.app)`


问:
autoprefixer: Replace color-adjust to print-color-adjust. The color-adjust shorthand is currently deprecated- Angular
I'm working on the Angular project and  getting this error when I run the ng serve , any solution for this

./src/styles.scss.webpack[javascript/auto]!=!./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[6].rules[0].oneOf[0].use[1]!./node_modules/@angular-devkit/build-angular/node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[6]. rules[0].oneOf[0].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[6].rules[1].use[0]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[6].rules[1].use[1]!./src/styles.scss

Warning: Module Warning (from ./no de_modules/@angular-devkit/build-angular/node_modules/postcss-loader/dist/cjs.js):
Warning

(3746:3) autoprefixer: Replace color-adjust to print-color-adjust. The
color-adjust shorthand is currently deprecated.


问:
Add watermark to image/video taken from flutter camera
I am trying to make a live streaming app out of flutter and I am live streaming video captured from camera and I want to add water mark on video. So basically what I want is to integrate watermark on Camera.</p>


问:
AnyDesk Trace Logs issue
So i left my PC Unattended for few hours, and when i came back, i saw an called Anydesk was randomly running. I never downloaded or installed. I quickly close the app, traced to its root location and deleted the exe. Rebooted my PC and added rules in Firewall to avoid this app running again. Ran ESET and Malware bytes and all came back clean. I then did some search on the net and able to get the trace logs. these were the log lines before i closed the app.

info 2023-01-06 02:14:58.056       back  47640  39608            capture.dda_stream_capture - Starting capture on . info 2023-01-06 02:14:58.254       back  47640  13384             desk_rt.capture_component - Keyboard layout changed to: en_us info 2023-01-06 02:14:58.358       back  47640  50284                   app.backend_session - Received new mouse cursor parameters (2). info 2023-01-06 02:14:58.358       back  47640  46964                   app.backend_session - Received new gui feedback parameters (0). info 2023-01-06 02:14:58.358       back  47640  38512                   app.backend_session - Received new video quality (20). info 2023-01-06 02:14:58.358       back  47640  13384                   app.backend_session - Received new image quality (7). info 2023-01-06 02:14:58.358       back  47640  50284           desk_rt.system_event_source - Enabled mouse cursor info 2023-01-06 02:14:58.358       back  47640  39388                   app.backend_session - Received new audio parameters (1). info 2023-01-06 02:14:58.358       back  47640  46964           desk_rt.system_event_source - Disabled gui feedback info 2023-01-06 02:14:58.358       back  47640  41880                   app.backend_session - Received new auto-quality preset (1). info 2023-01-06 02:14:58.358       back  47640  41880                   desk_rt.auto_adjust - New preset: 0. info 2023-01-06 02:14:58.365       back  47640  46444                   app.backend_session - Enabling capture. info 2023-01-06 02:14:58.383       back  47640  34928                       desk_rt.encoder - Format changed to 1920x1080 (X8R8G8B8). info 2023-01-06 02:14:58.383       back  47640  34928                       desk_rt.encoder - Subsampling changed to 420 info 2023-01-06 02:15:00.418       back  47640  44164                   app.backend_session - Received a thumbnail request. info 2023-01-06 02:15:00.493       back  47640  44164                   app.backend_session - Sending a new thumbnail. info 2023-01-06 02:15:10.337       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 16384 info 2023-01-06 02:15:11.043       back  47640  48716                   desk_rt.auto_adjust - Adjusting for a direct connection (61.13 kb/s). info 2023-01-06 02:15:11.043       back  47640  48716                   desk_rt.auto_adjust - Adjusting for < 90 kb/s info 2023-01-06 02:15:11.043       back  47640  48716                    audio.opus_encoder - Bitrate set to 65452 bits/s. error 2023-01-06 02:15:11.052       back  47640  48716                    base.impersonation - Couldn't query the user token (1314). error 2023-01-06 02:15:11.052       back  47640  48716            taskbar_animation_modifier - Couldn't impersonate. error 2023-01-06 02:15:11.052       back  47640  48716            taskbar_animation_modifier - Couldn't open key (6). info 2023-01-06 02:15:11.717       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 24576 info 2023-01-06 02:15:39.148      lctrl  44380  50232                        ad_app.control -    1 times: Session count: (1, 1) info 2023-01-06 02:15:39.148      lctrl  44380  50232                       clipbrd.capture - Relaying text offers. info 2023-01-06 02:18:47.449       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 32768 info 2023-01-06 02:19:17.141       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 40960 info 2023-01-06 02:20:11.560       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 49152 info 2023-01-06 02:20:12.995       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 57344 info 2023-01-06 02:20:15.287       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 65536 info 2023-01-06 02:21:46.079       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 73728 info 2023-01-06 02:21:47.542       lsvc  45640  49584   20         anynet.client_packetizer - Adjusted send buffer: 81920 info 2023-01-06 02:24:28.441       back  47640  39608            capture.dda_stream_capture - Access lost.

Question, Did some one try to log into my PC via Any desk ? were the successful in taking control over my mouse and keyboard while i was away ?

As pas these log lines did they failed ?

  error 2023-01-06 02:15:11.052       back  47640  48716                    base.impersonation - Couldn't query the user token (1314). error 2023-01-06 02:15:11.052       back  47640  48716            taskbar_animation_modifier - Couldn't impersonate. error 2023-01-06 02:15:11.052       back  47640  48716            taskbar_animation_modifier - Couldn't open key (6).

As pas these log lines did they failed ?

  error 2023-01-06 02:15:11.052       back  47640  48716                    base.impersonation - Couldn't query the user token (1314). error 2023-01-06 02:15:11.052       back  47640  48716            taskbar_animation_modifier - Couldn't impersonate. error 2023-01-06 02:15:11.052       back  47640  48716            taskbar_animation_modifier - Couldn't open key (6).

Title: AnyDesk Trace Logs issue


问:
There was no response when the admob reward advertisement view button was pressed
My game is currently published on the Google Play Store and registered on AdMob.
When I installed and ran it with APK on my device, both test and real worked well.
The advertisement doesn't come out only when I get it from the store.

I'm continuing to double-check, but are there any doubts?


问:
how to connect firebase to java for normal app
is it posible to make a app in java and use firebase database??

i cant import the following.. i get an error.

com.google.firebase.FirebaseApplication com.google.firebase.FirebaseOptions com.google.firebase.database

i am trying to code software with java and would like to conect it to a database please help i have the unitypackages for the firebase unity sdk.

I try to import the packages in netbeans for  com.google.firebase.FirebaseApplication
com.google.firebase.FirebaseOptions
com.google.firebase.database``


问:
How to build fromMap and toMap for predefined classes in flutter
How to build fromMap and toMap methods for predefined classes in flutter. Check the below code.</p>
```<code>import 'dart:convert';
import 'package:table_calendar/table_calendar.dart';
import 'package:time_machine/time_machine.dart';

class Session {
final TableCalendar startDate;
final LocalDate localDate;
final DateTime dateTime;
    Session({
        required this.startDate,
        required this.localDate,
        required this.dateTime,
    });
}
</code>```

Body:
How to build fromMap and toMap methods for predefined classes in flutter. Check the below code.

import 'dart:convert';
import 'package:table_calendar/table_calendar.dart';
import 'package:time_machine/time_machine.dart';

class Session {
final TableCalendar startDate;
final LocalDate localDate;
final DateTime dateTime;
    Session({
        required this.startDate,
        required this.localDate,
        required this.dateTime,
    });
}


问:
Twitter media upload returns message: 'Could not authenticate you', code: 32
I am creating a nodejs script to upload an image to twitter then tweet it. My tweeting code works, authentication is working and I can tweet (you can see a resemblance of my auth in this post, although it's been refactored a little). I'm using the same authentication approach for the media upload and I get { errors: [ { message: 'Could not authenticate you', code: 32 } ] }

From what I've seen, and what Twitter has shared, this could be from a malformed request. Below is my code...

const fetch = require('node-fetch');
const FormData = require('form-data');

console.log('getting image')
const imgResp = await fetch(newTweet.img)
const img = Buffer.from(await imgResp.arrayBuffer()).toString('base64') // img converts to a real image using online converters fine
const Authorization = getTwitterAuthHeader('https://upload.twitter.com/1.1/media/upload.json') // works when creating tweets
const twImg = await fetch('https://upload.twitter.com/1.1/media/upload.json', {
  method: 'POST',
  body: {media_data: img}, // other variations tried
  headers: {
    Authorization,
    'content-type': "application/x-www-form-urlencoded",
    'accept': "application/json"
  }
})
const twImgResp = await twImg.json();
console.log(twImgResp)
```
<p>my log looks like</p>
```getting image
{ errors: [ { message: 'Could not authenticate you', code: 32 } ] }
```
<p>As noted, I tried using the <code>formData</code> like</p>
```const formData = new FormData()
formData.append('media_data', img)
const twImg = await fetch('https://upload.twitter.com/1.1/media/upload.json', {
  method: 'POST',
  body: formData
```

I've tried media instead of media_data as well.

Body:
I am creating a nodejs script to upload an image to twitter then tweet it. My tweeting code works, authentication is working and I can tweet (you can see a resemblance of my auth in this post, although it's been refactored a little). I'm using the same authentication approach for the media upload and I get { errors: [ { message: 'Could not authenticate you', code: 32 } ] }

From what I've seen, and what Twitter has shared, this could be from a malformed request. Below is my code...

const fetch = require('node-fetch');
const FormData = require('form-data');

console.log('getting image')
const imgResp = await fetch(newTweet.img)
const img = Buffer.from(await imgResp.arrayBuffer()).toString('base64') // img converts to a real image using online converters fine
const Authorization = getTwitterAuthHeader('https://upload.twitter.com/1.1/media/upload.json') // works when creating tweets
const twImg = await fetch('https://upload.twitter.com/1.1/media/upload.json', {
  method: 'POST',
  body: {media_data: img}, // other variations tried
  headers: {
    Authorization,
    'content-type': "application/x-www-form-urlencoded",
    'accept': "application/json"
  }
})
const twImgResp = await twImg.json();
console.log(twImgResp)

my log looks like

getting image
{ errors: [ { message: 'Could not authenticate you', code: 32 } ] }

As noted, I tried using the formData like

const formData = new FormData()
formData.append('media_data', img)
const twImg = await fetch('https://upload.twitter.com/1.1/media/upload.json', {
  method: 'POST',
  body: formData

I've tried media instead of media_data as well.


问:
Inheritance entity and setup repository
I use spring boot 3, I have many entities who use inheritance.

```<code>@Entity
@DiscriminatorValue(Animal.DOG)
public class Dog extends Animal{
}

@Entity
@DiscriminatorValue(Animal.CAT)
public class Cat extends Animal{
}

@Entity
@Table(name = "Animal", schema = "")
@DiscriminatorColumn(name = "AnimalType", discriminatorType = DiscriminatorType.STRING)
public class Animal{

}
</code>```

For the repository I have

```<code>@Repository
@Transactional(readOnly = true)
public interface AnimalRepository extends JpaRepository<Animal, Long> {
}

@Repository
@Transactional(readOnly = true)
public interface DogRepository extends JpaRepository<Dog, Long> {
}

@Repository
@Transactional(readOnly = true)
public interface CatRepository extends JpaRepository<Cat, Long> {
}
</code>```

In DogRepository and CatRepository, do I need to setup something to be able to call findAll and it's return only dog or cat?

Title: Inheritance entity and setup repository

Body:
I use spring boot 3, I have many entities who use inheritance.

@Entity
@DiscriminatorValue(Animal.DOG)
public class Dog extends Animal{
}

@Entity
@DiscriminatorValue(Animal.CAT)
public class Cat extends Animal{
}

@Entity
@Table(name = "Animal", schema = "")
@DiscriminatorColumn(name = "AnimalType", discriminatorType = DiscriminatorType.STRING)
public class Animal{

}

For the repository I have

@Repository
@Transactional(readOnly = true)
public interface AnimalRepository extends JpaRepository<Animal, Long> {
}

@Repository
@Transactional(readOnly = true)
public interface DogRepository extends JpaRepository<Dog, Long> {
}

@Repository
@Transactional(readOnly = true)
public interface CatRepository extends JpaRepository<Cat, Long> {
}

In DogRepository and CatRepository, do I need to setup something to be able to call findAll and it's return only dog or cat?


问:
What is happening to the column I add?
I am trying to convert data from wide to long. It is pre/ post data for 15 subscales. In the wide version I have "intrinsic_pre" and "intrinsic_post" etc. I want to make faceted boxplots for all the subscales at the end. I thought that adding a new column with pre and post would work.

I convert from long to wide with

```<code>data_long<-gather(df, subscale, measurement, 23:52)
data_long<-na.omit(data_long)
data_long
</code>```

which seems to work fine. Then I try to add a column for status like so:

```<code>data_long %>%
  mutate(status = case_when(
    endsWith(subscale, "pre")~"pre",
    endsWith(subscale, "post")~"post"))
is.character(status)
</code>```

which tells me that the status column is there
A tibble: 1,140 x 3
condition     measurement status

1 Intrinsic_pre        7    pre
2 Intrinsic_pre        5.75 pre
3 Intrinsic_pre        5    pre
4 Intrinsic_pre        5.3  pre
5 Intrinsic_pre        4.25 pre
6 Intrinsic_pre        4.5  pre
7 Intrinsic_pre        6.3  pre
8 Intrinsic_pre        6.25 pre
9 Intrinsic_pre        6.3  pre
10 Intrinsic_pre        5    pre

but when I go to use it I get the following error

Error: object 'status' not found

Title: What is happening to the column I add?

Body:
I am trying to convert data from wide to long. It is pre/ post data for 15 subscales. In the wide version I have "intrinsic_pre" and "intrinsic_post" etc. I want to make faceted boxplots for all the subscales at the end. I thought that adding a new column with pre and post would work.

I convert from long to wide with

data_long<-gather(df, subscale, measurement, 23:52)
data_long<-na.omit(data_long)
data_long

which seems to work fine. Then I try to add a column for status like so:

data_long %>%
  mutate(status = case_when(
    endsWith(subscale, "pre")~"pre",
    endsWith(subscale, "post")~"post"))
is.character(status)

which tells me that the status column is there
A tibble: 1,140 x 3
condition     measurement status

1 Intrinsic_pre        7    pre
2 Intrinsic_pre        5.75 pre
3 Intrinsic_pre        5    pre
4 Intrinsic_pre        5.3  pre
5 Intrinsic_pre        4.25 pre
6 Intrinsic_pre        4.5  pre
7 Intrinsic_pre        6.3  pre
8 Intrinsic_pre        6.25 pre
9 Intrinsic_pre        6.3  pre
10 Intrinsic_pre        5    pre

but when I go to use it I get the following error

Error: object 'status' not found


问:
Is there an IDE platform that doesn't require code to be organized by file?
Moderately experienced but amateur programmer here. I've been transitioning to functional techniques after a lot of OO wrangling that always seemed to end up in a mess. But I've been considering that I really just don't find files to be a great way to organize code.

Is there any kind of IDE and plugin that handles the files for you and instead gives you a way to write functions and data structs independently with navigation done through references in code?

This is a rather generic question but for reference I use: Xcode, Android Studio, Sublime Text, and Arduino IDE. And I program in Swift/ObjC, Java, Python, HTML/CSS/JS/PHP, and C/C++


问:
Call a function on a pure HTML / JS Component
I am building a website using pure HTML/Javascript. I created an HTML component for the header and footer, and want the component to call a small script that changes the style of the navigation link when on that correlating page. Here is my full component, header.js (I've simplified the HTML):

```<code>const headerTemplate = document.createElement('template');
headerTemplate.innerHTML = `
<section id="header" class="fade-in">
        <div class="header-hero">
            <h1 class="cursor">Integrated Mind-Body</h1>
            <nav class="header-nav">
                <ul>
                    <li class="cursor"><a id='index' href="index.html">Home</a></li>
                    <li class="cursor"><a id='about' href="about.html">About</a></li>
                    <li class="cursor"><a id='services' href="services.html">Services</a></li>
                    <li class="cursor"><a id='contact' href="contact.html">Contact</a></li>
                </ul>
            </nav>
        </div>
    </section>
`

class Header extends HTMLElement {
    constructor() {super();}
    connectedCallback() {
        const shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.appendChild(headerTemplate.content);
    }
}
customElements.define('header-component', Header);
</code>```

The header-component is appearing fine in my code, but I can't get the component to interact with a very simple JS snippet:

```<code>var path = window.location.pathname;
var page = path.split("/").pop();

if (page === "index.html"){document.getElementById('index').classList.add('active')
</code>```

I've tried adding a const script tag to the connectedCallback() and get errors loading index.js (where I have the snippet)

I've also tried putting a script tag within the innerHTML that has the function. I'm unable to find many resources for non-React components. This site is static and using React would be overkill. Any help is greatly appreciated!

Body:
I am building a website using pure HTML/Javascript. I created an HTML component for the header and footer, and want the component to call a small script that changes the style of the navigation link when on that correlating page. Here is my full component, header.js (I've simplified the HTML):

const headerTemplate = document.createElement('template');
headerTemplate.innerHTML = `

Integrated Mind-Body

Home

About

Services

Contact

`

class Header extends HTMLElement {
    constructor() {super();}
    connectedCallback() {
        const shadowRoot = this.attachShadow({ mode: 'open' });
        shadowRoot.appendChild(headerTemplate.content);
    }
}
customElements.define('header-component', Header);

The header-component is appearing fine in my code, but I can't get the component to interact with a very simple JS snippet:

var path = window.location.pathname;
var page = path.split("/").pop();

if (page === "index.html"){document.getElementById('index').classList.add('active')

I've tried adding a const script tag to the connectedCallback() and get errors loading index.js (where I have the snippet)

I've also tried putting a script tag within the innerHTML that has the function. I'm unable to find many resources for non-React components. This site is static and using React would be overkill. Any help is greatly appreciated!


问:
How to use jest/ react testing library to test if component is visible?
I want to practice unit test so I created a book store with a variety of components. So I have a relatedBooks component for a react native app that is in a bookDetailsRelatedBooks component. In that component, I have this code below I want to write a unit test to cover.

```<code>{relatedBooks.map((relatedBook, index) => (
        <React.Fragment key={relatedBook.bookId}>
            <Grid item>
                <ViewabilityTrackingView
                    enabled
                    offsetBottom={150}
                    accessibilityState={{disabled: true}}
                    onViewabilityChange={({ isInView }: OnViewabilityCallbackParameters) => {
                        if (isInView) {
                            trackRelatedBookImpression(relatedBook.bookId, relatedBook.title, originBookId, index);
                        }
                    }}
                >
                    <RelatedBookRow
                        book={relatedBook}
                        onClick={() => {
                            trackRelatedBookClick(relatedBook.bookId, originBookId, index);
                        }}
                    />
                </ViewabilityTrackingView>
            </Grid>
            <Grid item cx={styles.divider}>
                <Divider />
            </Grid>
        </React.Fragment>
    ))}
</code>```

I tried this below but it does not work:

```<code>import { act, render, fireEvent } from 'react-testing-library';

test('trackRelatedBookImpression is called with correct arguments', () => {
  const relatedBooks = [{ bookId: 1, title: 'Test Book 1' }];
  const originBookId = 2;
  const trackRelatedBookImpression = jest.fn();

  const { getByTestId } = render(
    <bookDetailsRelatedBooks relatedBooks={relatedBooks} originBookId={originBookId} trackRelatedBookImpression={trackRelatedBookImpression} />
  );

  const viewabilityTrackingView = getByTestId('viewability-tracking-view');

  act(() => {
    fireEvent.scroll(viewabilityTrackingView);
  });

  expect(trackRelatedBookImpression).toHaveBeenCalledWith(1, 'Test Book 1', 2, 0);
});
</code>```

I expected it to work but I got an error stating:

```<code>Found multiple elements with testID: viewabilityTrackingView
</code>```

I tried assigning a testId to the viewabilityTrackingView but that does not work either, so I'm a bit stuck.

Body:
I want to practice unit test so I created a book store with a variety of components. So I have a relatedBooks component for a react native app that is in a bookDetailsRelatedBooks component. In that component, I have this code below I want to write a unit test to cover.

{relatedBooks.map((relatedBook, index) => (
        <React.Fragment key={relatedBook.bookId}>
            <Grid item>
                <ViewabilityTrackingView
                    enabled
                    offsetBottom={150}
                    accessibilityState={{disabled: true}}
                    onViewabilityChange={({ isInView }: OnViewabilityCallbackParameters) => {
                        if (isInView) {
                            trackRelatedBookImpression(relatedBook.bookId, relatedBook.title, originBookId, index);
                        }
                    }}
                >
                    <RelatedBookRow
                        book={relatedBook}
                        onClick={() => {
                            trackRelatedBookClick(relatedBook.bookId, originBookId, index);
                        }}
                    />
                </ViewabilityTrackingView>
            </Grid>
            <Grid item cx={styles.divider}>
                <Divider />
            </Grid>
        </React.Fragment>
    ))}

I tried this below but it does not work:

import { act, render, fireEvent } from 'react-testing-library';

test('trackRelatedBookImpression is called with correct arguments', () => {
  const relatedBooks = [{ bookId: 1, title: 'Test Book 1' }];
  const originBookId = 2;
  const trackRelatedBookImpression = jest.fn();

  const { getByTestId } = render(
    <bookDetailsRelatedBooks relatedBooks={relatedBooks} originBookId={originBookId} trackRelatedBookImpression={trackRelatedBookImpression} />
  );

  const viewabilityTrackingView = getByTestId('viewability-tracking-view');

  act(() => {
    fireEvent.scroll(viewabilityTrackingView);
  });

  expect(trackRelatedBookImpression).toHaveBeenCalledWith(1, 'Test Book 1', 2, 0);
});

I expected it to work but I got an error stating:

Found multiple elements with testID: viewabilityTrackingView

I tried assigning a testId to the viewabilityTrackingView but that does not work either, so I'm a bit stuck.


问:
Is there any better way to do like history.back() in django backend?
In Django, I have "form view(GET)" and "action view(POST)"

If there is a validation error or any other error in action view,

I want browser to go back to the previous form page with the input data whote by the user remains.

I tried:

At first, I used return redirect(request.META.get('HTTP_REFERER')).

This code goes back to the previous page well, but all the input fields became empty.

And now I am using return HttpResponse("") this code.

This works very well. but It looks weird sending javascript response.

What I expected was like return redirect.back()(with like HTTP 301 or 30X status code)

I was wondering if there is any better way or a proper way like officially provided by Django.


问:
How to create intricate custom shapes in python turtle
I'm trying to code a chess game, and I'm making each piece a turtle and because I need to them to move I need to create a custom shape that is made with many intricate parts. Is there an easier way than doing turtle.register_shape() with a bunch of coordinates in it

I would prefer a more simple code, I tried using file.gif and uploading a gif and registering that picture as a shape but I have no idea how to do that. And I don't think it works on the website I use for coding, replit.


问:
When applying the Having clause in Impala, a reference error occurs
Error occurs when referencing expr_1 after running the query like this on Impala.:

```<code>import pyodbc

import pandas as pd

sql = """
SELECT
    col,
    SUM(col2)
FROM table
WHERE conds
GROUP BY col
HAVING SUM(col2) > 0
"""

with pyodbc.connect(dsn=DSN, driver=CONN_DRIVER, schema=schema, autocommit=True) as conn:

    df = pd.read_sql(sql, conn)
</code>```

It seems that an error has occurred after the GROUP BY is applied.
How can it be solved?

Removing the aggregation function from the SELECT statement or eliminating the Having clause should solve the problem.
However, HUE displays the result without any issues, so it seems to be a pyodbc issue.

Body:
Error occurs when referencing expr_1 after running the query like this on Impala.:

import pyodbc

import pandas as pd

sql = """
SELECT
    col,
    SUM(col2)
FROM table
WHERE conds
GROUP BY col
HAVING SUM(col2) > 0
"""

with pyodbc.connect(dsn=DSN, driver=CONN_DRIVER, schema=schema, autocommit=True) as conn:

    df = pd.read_sql(sql, conn)

It seems that an error has occurred after the GROUP BY is applied.
How can it be solved?

Removing the aggregation function from the SELECT statement or eliminating the Having clause should solve the problem.
However, HUE displays the result without any issues, so it seems to be a pyodbc issue.