问:
UStaticMeshComponent is not moving with character
I have a Character C++ class, from which I created a Blueprint. If I add a static mesh to it from the Blueprint, the static mesh moves with the character.

But when I add a static mesh from C++, the static mesh appears but it does not move with the character. It stays in place instead.

I tried this in the constructor:

```<code>    this->Model = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Ship Model"));
    this->Model->SetupAttachment(this->RootComponent);
    this->Model->SetEnableGravity(false);
</code>```

As well as:

```<code>    this->Model = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Ship Model"));
    this->Model->AttachToComponent(
        this->RootComponent,
        FAttachmentTransformRules::SnapToTargetIncludingScale,
        TEXT("NAME_None")
    );
    this->Model->SetEnableGravity(false);
</code>```

But neither one of these seem to work.

What could be causing the issue?

Body:
I have a Character C++ class, from which I created a Blueprint. If I add a static mesh to it from the Blueprint, the static mesh moves with the character.

But when I add a static mesh from C++, the static mesh appears but it does not move with the character. It stays in place instead.

I tried this in the constructor:

    this->Model = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Ship Model"));
    this->Model->SetupAttachment(this->RootComponent);
    this->Model->SetEnableGravity(false);

As well as:

    this->Model = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Ship Model"));
    this->Model->AttachToComponent(
        this->RootComponent,
        FAttachmentTransformRules::SnapToTargetIncludingScale,
        TEXT("NAME_None")
    );
    this->Model->SetEnableGravity(false);

But neither one of these seem to work.

What could be causing the issue?


来源: stackexchange

问:
A github autograding problem i couldn't figure out
i was given a homework by my instructor which i was supposed to upload into autograding system and i did.
And even though the program flawlessly works in my ruby interpreter, it prints an error in autograding system:

This is my output of the program:
Range: 1453-2011
Sum: 129339
Binary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1

This is what resulted in autograding system:
❌ Example1
::error::The output for test Example1 did not match%0AExpected:%0ARange: 1453-2011%0ASum: 129339%0ABinary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1%0AActual:%0ARange: 1453-2011%0ASum: 129339%0ABinary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1

I didn't understand the reason why this error occurred at all. The output of my program is absolutely the same as the demanded output. Can you please explain?

It's basically a program that asks an input for which should be used to create an array with a range and the sum of the prime numbers within that range. It also asks for the binary representation of the sum of the prime numbers in that range:

```<code># frozen_string_literal: true

def set_number(index1, index2) # Create an array with a range by asking the minimum and maximum points of the range specified by the user.
   Array(index1..index2)

end

def prime?(number)  # Is the number prime?
  if number < 2
        return false
  elsif (2..Integer.sqrt(number)).each do
        |divisor| if number % divisor == 0
        return false
    end
     end
       return number
  end
end

def decimal_to_binary(number) # Convert the number from decimal to binary.
  number = number.to_i
  if number == 0
     return 0
  end

  binary = []
  while number != 0
    binary = binary << String(number % 2)
    number = number / 2
  end
  binary
end

index1, index2 = gets.chomp.split.map(&:to_i)
array = set_number(index1, index2)

puts "Range: #{index1}-#{index2}"

primes = []
array.each do |x|
  primes << x if prime?(x)
end

sum = 0
primes.each {|element| sum = sum + element}
puts "Sum: #{sum}"

binary = decimal_to_binary(sum)
puts "Binary: #{binary.reverse.join(" " " ")}"
</code>```

I expected the autograding system to verify the result which is correct and pass to the another example but it didn't.

ContentLicense: CC BY-SA 4.0

Body:
i was given a homework by my instructor which i was supposed to upload into autograding system and i did.
And even though the program flawlessly works in my ruby interpreter, it prints an error in autograding system:

This is my output of the program:
Range: 1453-2011
Sum: 129339
Binary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1

This is what resulted in autograding system:
❌ Example1
::error::The output for test Example1 did not match%0AExpected:%0ARange: 1453-2011%0ASum: 129339%0ABinary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1%0AActual:%0ARange: 1453-2011%0ASum: 129339%0ABinary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1

I didn't understand the reason why this error occurred at all. The output of my program is absolutely the same as the demanded output. Can you please explain?

It's basically a program that asks an input for which should be used to create an array with a range and the sum of the prime numbers within that range. It also asks for the binary representation of the sum of the prime numbers in that range:

# frozen_string_literal: true

def set_number(index1, index2) # Create an array with a range by asking the minimum and maximum points of the range specified by the user.
   Array(index1..index2)

end

def prime?(number)  # Is the number prime?
  if number < 2
        return false
  elsif (2..Integer.sqrt(number)).each do
        |divisor| if number % divisor == 0
        return false
    end
     end
       return number
  end
end

def decimal_to_binary(number) # Convert the number from decimal to binary.
  number = number.to_i
  if number == 0
     return 0
  end

  binary = []
  while number != 0
    binary = binary << String(number % 2)
    number = number / 2
  end
  binary
end

index1, index2 = gets.chomp.split.map(&:to_i)
array = set_number(index1, index2)

puts "Range: #{index1}-#{index2}"

primes = []
array.each do |x|
  primes << x if prime?(x)
end

sum = 0
primes.each {|element| sum = sum + element}
puts "Sum: #{sum}"

binary = decimal_to_binary(sum)
puts "Binary: #{binary.reverse.join(" " " ")}"

I expected the autograding system to verify the result which is correct and pass to the another example but it didn't.


问:
Prevent CSS from getting applied twice onto the ng-repeat element which was moved in the array
I am trying to create a swap animation for the elements in an array rendered via angularJS ng-repeat. Here, I just need 2 adjacent elements to simultaneously slide up/down to take each other's position. So for that I'm doing this:

function moveItemDown(item) {
    var lastIndex = itemsList.length - 1;
    var index = itemsList.indexOf(item);
    var $currentEl = $("#item-" + index);
    var $belowEl = $("#item-" + (index + 1));

    var translateYCurrent = $belowEl.innerHeight();
    var translateYBelow = 0 - $currentEl.innerHeight();
    $currentEl.css("transform", "translateY(" + translateYCurrent + "px)");
    $belowEl.css("transform", "translateY(" + translateYBelow + "px)");

    $timeout(function() {
        $belowEl.css("transform", "none");
        $currentEl.css("transform", "none");

        if (index !== lastIndex) {
            [itemsList[index], itemsList[index + 1]] =
                [itemsList[index + 1], itemsList[index]];
        }
    }, 500);
}
```

The above code would make the given element move down by the innerHeight of the element below and the below element to move up by the innerHeight of the element above.

The animations happens fine until the elements in the array are actually swapped. When that happens, the currentElement jumps down again by the innerHeight of the element below and then transitions up where its supposed to be. It seems that the negative translateY is applied again on the element which moved down. How can that be fixed?

Body:
I am trying to create a swap animation for the elements in an array rendered via angularJS ng-repeat. Here, I just need 2 adjacent elements to simultaneously slide up/down to take each other's position. So for that I'm doing this:

function moveItemDown(item) {
    var lastIndex = itemsList.length - 1;
    var index = itemsList.indexOf(item);
    var $currentEl = $("#item-" + index);
    var $belowEl = $("#item-" + (index + 1));

    var translateYCurrent = $belowEl.innerHeight();
    var translateYBelow = 0 - $currentEl.innerHeight();
    $currentEl.css("transform", "translateY(" + translateYCurrent + "px)");
    $belowEl.css("transform", "translateY(" + translateYBelow + "px)");

    $timeout(function() {
        $belowEl.css("transform", "none");
        $currentEl.css("transform", "none");

        if (index !== lastIndex) {
            [itemsList[index], itemsList[index + 1]] =
                [itemsList[index + 1], itemsList[index]];
        }
    }, 500);
}

The above code would make the given element move down by the innerHeight of the element below and the below element to move up by the innerHeight of the element above.

The animations happens fine until the elements in the array are actually swapped. When that happens, the currentElement jumps down again by the innerHeight of the element below and then transitions up where its supposed to be. It seems that the negative translateY is applied again on the element which moved down. How can that be fixed?


问:
How do I avoid the diagram appearing twice in the GUI after the button click?
I'm currently programming a GUI in which a diagram with data from a CSV file should be displayed. Since new data is always being added to the CSV, I want to display a current history after each button click.

My problem:
After every button click, a new diagram appears instead of a new course in the old diagram

Code:

```<code>def graph():

# List 1
liste_1_x = ["06:15", "15:30"]
liste_1_y = [0,16000]

# List 2
list_2_x = []
list_2_y = []

#------------------------------------------------------------------------

import csv

with open("testdata.csv", "r") as filedata:
    lines = csv.reader(filedata, delimiter=",")
    for row in lines:
        list_2_x.append(row[0])
        list_2_y.append(int(row[1]))

#------------------------------------------------------------------------

import matplotlib.pyplot as plt
import tkinter
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

fig = Figure(figsize=(6,4), dpi=100)

plot1 = fig.add_subplot(111)

plot1.plot(liste_1_x,liste_1_y, color="b", marker="o")

plot1.plot(list_2_x, list_2_y, color="r", marker="o")

plot1.grid()

plot1.set_ylabel("Amount")
plot1.set_xlabel("Time")

canvas = FigureCanvasTkAgg(fig, master=tkFenster)

canvas.draw()

canvas.get_tk_widget().pack(side=tkinter.BOTTOM)

toolbar = NavigationToolbar2Tk(canvas, tkFenster)
toolbar.update()

canvas.get_tk_widget().pack(side=tkinter.LEFT, expand = 1)
</code>```

Thanks for the help!

Body:
I'm currently programming a GUI in which a diagram with data from a CSV file should be displayed. Since new data is always being added to the CSV, I want to display a current history after each button click.

My problem:
After every button click, a new diagram appears instead of a new course in the old diagram

Code:

def graph():

# List 1
liste_1_x = ["06:15", "15:30"]
liste_1_y = [0,16000]

# List 2
list_2_x = []
list_2_y = []

#------------------------------------------------------------------------

import csv

with open("testdata.csv", "r") as filedata:
    lines = csv.reader(filedata, delimiter=",")
    for row in lines:
        list_2_x.append(row[0])
        list_2_y.append(int(row[1]))

#------------------------------------------------------------------------

import matplotlib.pyplot as plt
import tkinter
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

fig = Figure(figsize=(6,4), dpi=100)

plot1 = fig.add_subplot(111)

plot1.plot(liste_1_x,liste_1_y, color="b", marker="o")

plot1.plot(list_2_x, list_2_y, color="r", marker="o")

plot1.grid()

plot1.set_ylabel("Amount")
plot1.set_xlabel("Time")

canvas = FigureCanvasTkAgg(fig, master=tkFenster)

canvas.draw()

canvas.get_tk_widget().pack(side=tkinter.BOTTOM)

toolbar = NavigationToolbar2Tk(canvas, tkFenster)
toolbar.update()

canvas.get_tk_widget().pack(side=tkinter.LEFT, expand = 1)

Thanks for the help!


问:
How to plot overlaying shapes onto an Orthographic Plot in Plotly?
I am trying to identify a way to plot certain figures (semi-spheres or cones, for instance) onto an existing Figure with set orthographic projection created with Plotly.
I have utilized the code kindly provided here by Igor Comune: https://igorcomune.medium.com/data-science-how-to-plot-3d-interactive-globe-map-4dfba1b6e070

I now have a 3D Globe with geographic overlay, and some scattergeo points dotting the Globe. In some of those scattergeo points I would like to center shapes, ideally by utilizing Azimuth-Elevation Coordinates in order to showcase some umbrella coverages for some points of interest.

Any particular section of the documentation or any relevant guide that I can make use of?

I tried looking a bit into the documentation and I feel like doing a fig.add_mesh3d could perhaps be a solution here, but not sure how to pass Az-El coord pairs in order to obtain the desired shape centered on the scattergeo trace (centering which I believe I can do with xsrc, ysrc, zsrc?)


问:
Include entitlements file in a SPM's package
I currently have a .testTarget used to test a package that relies on HealthKit. In order to test I can write and read data from Apple HealthKit, I require an entitlement, otherwise I get:

```<code>"Missing com.apple.developer.healthkit entitlement." UserInfo={NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.}
</code>```

My question is: how can I add a dummy entitlement file to bypass this situation? Or maybe there's another way to test HealthKit via a .testTarget.

Body:
I currently have a .testTarget used to test a package that relies on HealthKit. In order to test I can write and read data from Apple HealthKit, I require an entitlement, otherwise I get:

"Missing com.apple.developer.healthkit entitlement." UserInfo={NSLocalizedDescription=Missing com.apple.developer.healthkit entitlement.}

My question is: how can I add a dummy entitlement file to bypass this situation? Or maybe there's another way to test HealthKit via a .testTarget.


问:
How do I scrape images using beautifulsoup in flutter?
So I successfully scraped the text from the card that im scraping from but for some reason i cant scrape the image within the card in the website.

```<code>class ScraperService{static List<PackageModel> run(String html){
try{
  final soup = BeautifulSoup(html);
  final items = soup.findAll('div', class_: 'card content-card');
  List<PackageModel> packages = [];
  for(var item in items){
    final dest = item.find('h3', class_: 'card-heading')?.text??'';
    final desc = item.find('p', class_: 'card-text')?.text??'';
    final img = item.find('img', class_: 'card-img-top lazy slick-slide slick-current slick-active');
    //final imgUrl = img!['src'];
    //print(imgUrl);
    PackageModel model = PackageModel(
      destination: dest.substring(4),
      description: desc,
      image: img!['src'],
    );
    packages.add(model);
  }
  return packages;
} catch (e){
  print('ScraperService $e');
  return [];
}}}
</code>```

When I write this code it does not show the cards  in my app. I tried printing the text i extracted from the img tag

```<code>final img = item.find('img', class_: 'card-img-top lazy slick-slide slick-current slick-active');
</code>```

The cards in my app did show,however the elements in the img tag did not show.

I also tried

```<code>final img = item.find('img', class_: 'card-img-top lazy slick-slide slick-current slick-active')!['src'];
</code>```

Same thing happened above, these means that I did not get the elements from the img tag right? Then what should I do

Body:
So I successfully scraped the text from the card that im scraping from but for some reason i cant scrape the image within the card in the website.

class ScraperService{static List<PackageModel> run(String html){
try{
  final soup = BeautifulSoup(html);
  final items = soup.findAll('div', class_: 'card content-card');
  List<PackageModel> packages = [];
  for(var item in items){
    final dest = item.find('h3', class_: 'card-heading')?.text??'';
    final desc = item.find('p', class_: 'card-text')?.text??'';
    final img = item.find('img', class_: 'card-img-top lazy slick-slide slick-current slick-active');
    //final imgUrl = img!['src'];
    //print(imgUrl);
    PackageModel model = PackageModel(
      destination: dest.substring(4),
      description: desc,
      image: img!['src'],
    );
    packages.add(model);
  }
  return packages;
} catch (e){
  print('ScraperService $e');
  return [];
}}}

When I write this code it does not show the cards  in my app. I tried printing the text i extracted from the img tag

final img = item.find('img', class_: 'card-img-top lazy slick-slide slick-current slick-active');

The cards in my app did show,however the elements in the img tag did not show.

I also tried

final img = item.find('img', class_: 'card-img-top lazy slick-slide slick-current slick-active')!['src'];

Same thing happened above, these means that I did not get the elements from the img tag right? Then what should I do


问:
Use Ctrl c , Ctrl v in v-list-item vuetify
I have a v-list with v-list-item

```<code><v-list>
  <v-list-item
    v-for="record in Records"
    :key="record.id"
    :to="somePath(record)"
     @dragstart="abc"
     @dragover="abc"
     @drop="abc"
     @contextmenu="abc"
  >
 </v-list-item
</v-list>

</code>```

Now i want to use keyboard shortcut Ctrl c to copy a list item and similarly ctrl v to paste using my custom logic. How do i achieve that ? Thanks

Body:
I have a v-list with v-list-item

<v-list>
  <v-list-item
    v-for="record in Records"
    :key="record.id"
    :to="somePath(record)"
     @dragstart="abc"
     @dragover="abc"
     @drop="abc"
     @contextmenu="abc"
  >
 </v-list-item
</v-list>

Now i want to use keyboard shortcut Ctrl c to copy a list item and similarly ctrl v to paste using my custom logic. How do i achieve that ? Thanks


问:
Bottom tabs and screen not touchable
I have a project that has stack and tab navigation in it. There is a strange problem it in which is: The tabs and screens are not touchable sometimes, although the screen is always scrollable is there is any ScrollView in that screen.

Note: The project was running fine for last 2 years but I recently(last month) migrated from mac intel to mac m1 chip using migration assistant.
This problem started appearing from the last week.

The Structure of the Project:

The Screen MainScreen is imported and called in app.js

MainScreen checks for the token and calls MainNavigation, which is
another screen

In MainNavigation I have 4 tabs like <Tab.Screen name="Dashboard"
component={DashboardStack}/>

Used import {createBottomTabNavigator} from
'@react-navigation/bottom-tabs'

Then there are 4 other screens each one for one tab like:
DashboardStack

Used import {createStackNavigator} from '@react-navigation/stack'

And inside DashboardStack file, I have all the files that will be for
Dashboard

Package.json

```<code>"react": "16.13.1",
"react-native": "0.63.4",
"@react-navigation/bottom-tabs": "^5.11.2",
"@react-navigation/native": "^5.8.10",
"@react-navigation/stack": "^5.12.8",
"react-native-safe-area-context": "^3.4.1",
"react-native-screens": "^2.16.1",
</code>```

MainNavigation screen

```<code>function DashboardStack({navigation, route}) {
    return <DashboardNavigation navigation={navigation} route={route} driverId={driverId} globalSettings={props.globalSettings} handleLogout={props.handleLogout}/>
  }
return(
<NavigationContainer>
      <Tab.Navigator tabBarOptions={{ showLabel: false, style:{bottom:5}}}
        screenOptions={({route}) => ({tabBarIcon: ({focused}) => handleNavIcon(route.name, focused)})}
        >
        <Tab.Screen name="Dashboard" component={DashboardStack}/>
        <Tab.Screen name="Billing" component={BillingStack} />
        <Tab.Screen name="Rental" component={RentalStack} />
        <Tab.Screen name="Support" component={SupportStack} />
        <Tab.Screen name="Account" component={AccountStack} />
      </Tab.Navigator>
    </NavigationContainer>
)
</code>```

DashboardNavigation.js

```<code><DashboardStack.Navigator options={{ headerShown: true, }} screenOptions={{ headerBackTitleVisible: false, headerTitleAlign: "center", headerRight: () => <NotificationIcon driverId={props && props.driverId && props.driverId} navigation={props.navigation}/> }}>
          <DashboardStack.Screen name="Dashboard" children={() => <Dashboard driverId={props.driverId} globalSettings={props.globalSettings} handleLogout={props.handleLogout} />} />
          <DashboardStack.Screen name="Current Documents" component={carDocs} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Notifications" component={NotificationListScreen} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Notification Detail" component={NotificationDetailScreen} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Under Construction" component={ComingSoon} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Make a Payment" component={makePayment} options={{ headerBackImage: () => <MaterialIcons size={30} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Verify Phone Number" component={VerifyPhoneNumber} options={{ headerBackImage: () => <MaterialIcons size={30} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
        </DashboardStack.Navigator>
</code>```

Title: Bottom tabs and screen not touchable

Body:
I have a project that has stack and tab navigation in it. There is a strange problem it in which is: The tabs and screens are not touchable sometimes, although the screen is always scrollable is there is any ScrollView in that screen.

Note: The project was running fine for last 2 years but I recently(last month) migrated from mac intel to mac m1 chip using migration assistant.
This problem started appearing from the last week.

The Structure of the Project:

The Screen MainScreen is imported and called in app.js

MainScreen checks for the token and calls MainNavigation, which is
another screen

In MainNavigation I have 4 tabs like <Tab.Screen name="Dashboard"
component={DashboardStack}/>

Used import {createBottomTabNavigator} from
'@react-navigation/bottom-tabs'

Then there are 4 other screens each one for one tab like:
DashboardStack

Used import {createStackNavigator} from '@react-navigation/stack'

And inside DashboardStack file, I have all the files that will be for
Dashboard

Package.json

"react": "16.13.1",
"react-native": "0.63.4",
"@react-navigation/bottom-tabs": "^5.11.2",
"@react-navigation/native": "^5.8.10",
"@react-navigation/stack": "^5.12.8",
"react-native-safe-area-context": "^3.4.1",
"react-native-screens": "^2.16.1",

MainNavigation screen

function DashboardStack({navigation, route}) {
    return <DashboardNavigation navigation={navigation} route={route} driverId={driverId} globalSettings={props.globalSettings} handleLogout={props.handleLogout}/>
  }
return(
<NavigationContainer>
      <Tab.Navigator tabBarOptions={{ showLabel: false, style:{bottom:5}}}
        screenOptions={({route}) => ({tabBarIcon: ({focused}) => handleNavIcon(route.name, focused)})}
        >
        <Tab.Screen name="Dashboard" component={DashboardStack}/>
        <Tab.Screen name="Billing" component={BillingStack} />
        <Tab.Screen name="Rental" component={RentalStack} />
        <Tab.Screen name="Support" component={SupportStack} />
        <Tab.Screen name="Account" component={AccountStack} />
      </Tab.Navigator>
    </NavigationContainer>
)

DashboardNavigation.js

<DashboardStack.Navigator options={{ headerShown: true, }} screenOptions={{ headerBackTitleVisible: false, headerTitleAlign: "center", headerRight: () => <NotificationIcon driverId={props && props.driverId && props.driverId} navigation={props.navigation}/> }}>
          <DashboardStack.Screen name="Dashboard" children={() => <Dashboard driverId={props.driverId} globalSettings={props.globalSettings} handleLogout={props.handleLogout} />} />
          <DashboardStack.Screen name="Current Documents" component={carDocs} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Notifications" component={NotificationListScreen} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Notification Detail" component={NotificationDetailScreen} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Under Construction" component={ComingSoon} options={{ headerBackImage: () => <MaterialIcons size={Platform.OS == "ios" ? 30 : 25} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Make a Payment" component={makePayment} options={{ headerBackImage: () => <MaterialIcons size={30} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
          <DashboardStack.Screen name="Verify Phone Number" component={VerifyPhoneNumber} options={{ headerBackImage: () => <MaterialIcons size={30} name="arrow-back" style={{ paddingLeft: 10 }} /> }}></DashboardStack.Screen>
        </DashboardStack.Navigator>


问:
Dash Active_cell and page_current conflict
I am trying to link a data table with multiple pages and a graph that displays all the pages of the data table. When I click on the data table, the relevant vertex in the graph is highlighted. When I hover over a vertex, the page_current value in the data table is updated and the active_cell is changed.

The issue I am having is when I update page_current and active_cell in a callback, active_cell updates, then page_current_updates, which clears the active cell. This results in the active_cell only highlighting if the vertex on the graph is in the same page as the data table. If it isn’t, the active_cell blinks and the page_current changes, with no cell highlighted. If you unhover then hover over the same point, the active cell will highlight.

I created a workaround by creating a chained callback (which is commented out below) named placeholder. With the chained callback, page_current is updated on the data table and the active cell is passed to the placeholder, which then updates the active cell in the data table. This works, but throws the errors below

:rescue_worker_helmet:
Circular Dependencies
10:31:41 AM
Error: Dependency Cycle Found: data_table.page_current → placeholder.active_cell → data_table.active_cell → placeholder.active_cell
:rescue_worker_helmet:
Invalid prop for this component
10:31:41 AM
Property “active_cell” was used with component ID:
“placeholder”
in one of the Input items of a callback.
This ID is assigned to a dash_html_components.Div component
in the layout, which does not support this property.
This ID was used in the callback(s) for Output(s):
data_table.active_cell
:rescue_worker_helmet:
Invalid prop for this component
10:31:41 AM
Property “active_cell” was used with component ID:
“placeholder”
in one of the Output items of a callback.
This ID is assigned to a dash_html_components.Div component
in the layout, which does not support this property.
This ID was used in the callback(s) for Output(s):
data_table.data, graph.figure, graph-tooltip.show, graph-tooltip.bbox, graph-tooltip.children, placeholder.active_cell, data_table.selected_cells, data_table.page_current, tbl_out.children

Is there a way to link a graph and data table with multiple pages without throwing errors by updating the page_current before the active_cell in a single call back or using a method like the chained callbacks I commented out?

```<code>from dash import Dash, dcc, html, Input, Output, no_update, dash_table, State, callback_context
from dash.exceptions import PreventUpdate
import plotly.express as px
import pandas as pd
import dash_bootstrap_components as dbc
import json
from datetime import datetime as dt, timedelta
import plotly.graph_objects as go
import os, sys
import datetime
import re
import time
import numpy as np
from collections import defaultdict

app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
dict_list = [{'fid': 'a1', 'tail': 'test1', 'x': 1, 'y': 1}, {'fid': 'b2', 'tail': 'test2', 'x': 2, 'y': 2},
             {'fid': 'c3', 'tail': 'test3', 'x': 3, 'y': 1}, {'fid': 'd4', 'tail': 'test1', 'x': 2, 'y': 2}, {'fid': 'e5', 'tail': 'test2', 'x': 4, 'y': 4},
             {'fid': 'f6', 'tail': 'test3', 'x': 6, 'y': 4}, {'fid': 'g7', 'tail': 'test1', 'x': 3, 'y': 3}, {'fid': 'h8', 'tail': 'test2', 'x': 6, 'y': 6},
             {'fid': 'i9', 'tail': 'test3', 'x':12, 'y': 10}]
df = pd.DataFrame(dict_list)

app.layout = html.Div(
    dbc.Container([dbc.Row(
                dash_table.DataTable(id='data_table',
                columns=[{"name": i, "id": i} for i in ['fid', 'tail', 'x', 'y']],
                page_current=0,
                page_size=5,
                page_action='custom',
                filter_action='custom',
                filter_query='',
                sort_action='custom',
                sort_mode='multi',
                sort_by=[],
                style_filter_conditional=[{
                'if': {'column_id': 'date_processed'},
                'pointer-events': 'None'}]),
            style={'height': 750, 'overflowY': 'scroll'},
            className='six columns'),
        dbc.Row([dcc.Graph(id="graph",clear_on_unhover=True),
                dcc.Tooltip(id="graph-tooltip",background_color="lightgrey",border_color="blue")]),
        dbc.Row([dbc.Alert(id='tbl_out'), html.Div(id='placeholder')])

]))

operators = [['ge ', '>='],
             ['le ', '<='],
             ['lt ', '<'],
             ['gt ', '>'],
             ['ne ', '!='],
             ['eq ', '='],
             ['contains '],
             ['datestartswith ']]

def split_filter_part(filter_part):
    for operator_type in operators:
        for operator in operator_type:
            if operator in filter_part:
                name_part, value_part = filter_part.split(operator, 1)
                name = name_part[name_part.find('{') + 1: name_part.rfind('}')]

                value_part = value_part.strip()
                v0 = value_part[0]
                if (v0 == value_part[-1] and v0 in ("'", '"', '`')):
                    value = value_part[1: -1].replace('\\' + v0, v0)
                else:
                    try:
                        value = float(value_part)
                    except ValueError:
                        value = value_part

                # word operators need spaces after them in the filter string,
                # but we don't want these later
                return name, operator_type[0].strip(), value

    return [None] * 3

@app.callback(
    Output('data_table', "data"),
    Output('graph', "figure"),
    Output("graph-tooltip", "show"),
    Output("graph-tooltip", "bbox"),
    Output("graph-tooltip", "children"),
    #Output("placeholder", "active_cell"),
    Output("data_table", "active_cell"),
    Output("data_table", "selected_cells"),
    Output('data_table', 'page_current'),
    Output('tbl_out', 'children'),
    Input('data_table', "page_current"),
    Input('data_table', "sort_by"),
    Input('data_table', "filter_query"),
    Input("graph", "hoverData"),
    Input("graph", "figure"),
    Input('data_table', 'active_cell'),
    State('data_table', 'data'),
    State('data_table', "page_size"))

def update_table(page_current, sort_by, filter,  hoverData, dict_fig, active_cell, data_table, page_size):
    dff = get_table(df, page_size, page_current, sort_by, filter)
    triggered_id = callback_context.triggered[0]['prop_id']
    if 'data_table.active_cell' == triggered_id:
        try:
            active_cell, selected_cells, fig = update_graphs(active_cell, data_table, dict_fig)
            return no_update, fig, False, no_update, no_update, active_cell, selected_cells, no_update, F"{callback_context.triggered}-----{callback_context.triggered_prop_ids}---{callback_context.triggered_id}"
        except Exception as e:
            return no_update, no_update,  no_update, no_update, no_update, no_update, no_update, no_update, str(e)

    elif 'graph.hoverData' == triggered_id:
        try:
            #show, bbox, children, active_cell, selected_cells, geojson3, idx, error = update_tooltip_content(hoverData, flights_geojson, flight_data, dff, page_size)
            try:
                show, bbox, children, active_cell, selected_cells, idx, error = update_tooltip_content(hoverData, data_table, dff, page_size)
                hover_rec = hoverData['points'][0]['customdata'][0]
            except:
                hover_rec = None
            if hover_rec is not None:
                fig = go.Figure(dict_fig)
                fig.for_each_trace(lambda trace: trace.update(visible=False) if trace.name == "highlight" else())
                page_current = int((idx)/page_size)
#
                return dff.iloc[
            page_current*page_size: (page_current + 1)*page_size
        ].to_dict('records'), fig, show, bbox, children,active_cell, selected_cells, page_current, page_current
            else:
                return no_update, no_update,  False, bbox, no_update,no_update, no_update, no_update,no_update#F"{idx}:{active_cell}"
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            return no_update, no_update,  no_update, no_update, no_update, no_update, no_update, no_update,F"{exc_type}, {fname}, {exc_tb.tb_lineno}"

    else:
        fig = px.line(dff.sort_values('x').reset_index(drop=True)[['tail', 'fid', 'x', 'y']], x="x", y="y",color="tail",hover_data=[dff.fid])

        fig.update_traces(
            hoverinfo="none",
            hovertemplate=None
        )
        fig.add_scatter(y=[0], x=[0], mode="markers", visible = False, name = 'highlight', hoverinfo='skip', showlegend=False, marker=dict(size=12))

        return dff.iloc[
            page_current*page_size: (page_current + 1)*page_size
        ].to_dict('records'), fig, no_update, no_update, no_update,no_update, no_update, page_current, no_update

#@app.callback(
#    Output("data_table", "active_cell"),
#    Input("placeholder", "active_cell"))
def update_highlight(active_cell):
    return active_cell
def get_table(dff, page_size, page_current, sort_by, filter):
    if filter is not None:
        filtering_expressions = filter.split(' && ')

        for filter_part in filtering_expressions:
            col_name, operator, filter_value = split_filter_part(filter_part)
            if operator in ('eq', 'ne', 'lt', 'le', 'gt', 'ge'):
                # these operators match pandas series operator method names
                dff = dff.loc[getattr(dff[col_name], operator)(filter_value)]
            elif operator == 'contains':
                dff = dff.loc[dff[col_name].str.contains(filter_value)]
            elif operator == 'datestartswith':
                # this is a simplification of the front-end filtering logic,
                # only works with complete fields in standard format
                dff = dff.loc[dff[col_name].str.startswith(filter_value)]

    if len(sort_by):
        dff = dff.sort_values(
            [col['column_id'] for col in sort_by],
            ascending=[
                col['direction'] == 'asc'
                for col in sort_by
            ],
            inplace=False
        )
    return dff.reset_index(drop=True)

def find_xy(fid, json_dict):
    for tail_obj in json_dict:
        i = 0
        for obj in tail_obj['customdata']:
            if obj[0] == fid:
                return tail_obj['x'][i], tail_obj['y'][i]
            i +=1
    return None, None
def find_table_idx(fid, flight_data):
    i = 0
    for row_obj in flight_data:
        if fid == row_obj['fid']:
            return i
        i += 1
    return None

def update_tooltip_content(hoverData, flight_data, dff, page_size):
    try:
        if hoverData is None:
            return no_update, no_update, no_update, no_update, no_update, None, None

        pt = hoverData["points"][0]
        bbox = pt["bbox"]
        fid = hoverData['points'][0]['customdata'][0]
        try:
            idx = dff.index[dff['fid'] == fid][0]
            activecell, selectedcells = [{'column':0, 'row':idx-int(idx/page_size)*page_size, 'column_id': 'noupdate'}, [{'column':0, 'row':idx-int(idx/page_size)*page_size}]]
        except:
            idx = 0
            activecell, selectedcells = [None, []]
        children = [
            html.P(f"Date: {pt['x']}, ASP: {pt['y']}, fid: {fid}")
        ]
        return True, bbox, children, activecell, selectedcells, idx, F"{idx}:{fid}:{dff.index[dff['fid'] == fid][0]}-----{dff.to_json(orient='records')}"
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        return no_update, no_update, no_update, no_update, no_update, 0, F"{dff.to_json(orient='records')}----{idx}:{fid}----{exc_type}, {fname}, {exc_tb.tb_lineno}"

def update_graphs(active_cell, flight_data, dict_fig):
    if active_cell:
        fig = go.Figure(dict_fig)
        fig.for_each_trace(
            lambda trace: trace.update(visible=False) if trace.name == "highlight" else (),
        )
        if active_cell['column_id'] =='fid':
            fid = flight_data[active_cell['row']]['fid']
            x, y = find_xy(fid, dict_fig['data'])

            if x is not None and y is not None:
                fig.for_each_trace(
                    lambda trace: trace.update(visible=True, x=[x], y=[y]) if trace.name == "highlight" else (),
                )
            return active_cell, [active_cell], fig
        elif active_cell['column_id'] =='noupdate':
            return active_cell, [active_cell], no_update
        else:
            return None, [], fig
    else:
        return None, [], no_update
if __name__ == '__main__':
    app.run_server(debug=True) # Running the application```
```

Body:
I am trying to link a data table with multiple pages and a graph that displays all the pages of the data table. When I click on the data table, the relevant vertex in the graph is highlighted. When I hover over a vertex, the page_current value in the data table is updated and the active_cell is changed.

The issue I am having is when I update page_current and active_cell in a callback, active_cell updates, then page_current_updates, which clears the active cell. This results in the active_cell only highlighting if the vertex on the graph is in the same page as the data table. If it isn’t, the active_cell blinks and the page_current changes, with no cell highlighted. If you unhover then hover over the same point, the active cell will highlight.

I created a workaround by creating a chained callback (which is commented out below) named placeholder. With the chained callback, page_current is updated on the data table and the active cell is passed to the placeholder, which then updates the active cell in the data table. This works, but throws the errors below

:rescue_worker_helmet:
Circular Dependencies
10:31:41 AM
Error: Dependency Cycle Found: data_table.page_current → placeholder.active_cell → data_table.active_cell → placeholder.active_cell
:rescue_worker_helmet:
Invalid prop for this component
10:31:41 AM
Property “active_cell” was used with component ID:
“placeholder”
in one of the Input items of a callback.
This ID is assigned to a dash_html_components.Div component
in the layout, which does not support this property.
This ID was used in the callback(s) for Output(s):
data_table.active_cell
:rescue_worker_helmet:
Invalid prop for this component
10:31:41 AM
Property “active_cell” was used with component ID:
“placeholder”
in one of the Output items of a callback.
This ID is assigned to a dash_html_components.Div component
in the layout, which does not support this property.
This ID was used in the callback(s) for Output(s):
data_table.data, graph.figure, graph-tooltip.show, graph-tooltip.bbox, graph-tooltip.children, placeholder.active_cell, data_table.selected_cells, data_table.page_current, tbl_out.children

Is there a way to link a graph and data table with multiple pages without throwing errors by updating the page_current before the active_cell in a single call back or using a method like the chained callbacks I commented out?

from dash import Dash, dcc, html, Input, Output, no_update, dash_table, State, callback_context
from dash.exceptions import PreventUpdate
import plotly.express as px
import pandas as pd
import dash_bootstrap_components as dbc
import json
from datetime import datetime as dt, timedelta
import plotly.graph_objects as go
import os, sys
import datetime
import re
import time
import numpy as np
from collections import defaultdict

app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
dict_list = [{'fid': 'a1', 'tail': 'test1', 'x': 1, 'y': 1}, {'fid': 'b2', 'tail': 'test2', 'x': 2, 'y': 2},
             {'fid': 'c3', 'tail': 'test3', 'x': 3, 'y': 1}, {'fid': 'd4', 'tail': 'test1', 'x': 2, 'y': 2}, {'fid': 'e5', 'tail': 'test2', 'x': 4, 'y': 4},
             {'fid': 'f6', 'tail': 'test3', 'x': 6, 'y': 4}, {'fid': 'g7', 'tail': 'test1', 'x': 3, 'y': 3}, {'fid': 'h8', 'tail': 'test2', 'x': 6, 'y': 6},
             {'fid': 'i9', 'tail': 'test3', 'x':12, 'y': 10}]
df = pd.DataFrame(dict_list)

app.layout = html.Div(
    dbc.Container([dbc.Row(
                dash_table.DataTable(id='data_table',
                columns=[{"name": i, "id": i} for i in ['fid', 'tail', 'x', 'y']],
                page_current=0,
                page_size=5,
                page_action='custom',
                filter_action='custom',
                filter_query='',
                sort_action='custom',
                sort_mode='multi',
                sort_by=[],
                style_filter_conditional=[{
                'if': {'column_id': 'date_processed'},
                'pointer-events': 'None'}]),
            style={'height': 750, 'overflowY': 'scroll'},
            className='six columns'),
        dbc.Row([dcc.Graph(id="graph",clear_on_unhover=True),
                dcc.Tooltip(id="graph-tooltip",background_color="lightgrey",border_color="blue")]),
        dbc.Row([dbc.Alert(id='tbl_out'), html.Div(id='placeholder')])

]))

operators = [['ge ', '>='],
             ['le ', '<='],
             ['lt ', '<'],
             ['gt ', '>'],
             ['ne ', '!='],
             ['eq ', '='],
             ['contains '],
             ['datestartswith ']]

def split_filter_part(filter_part):
    for operator_type in operators:
        for operator in operator_type:
            if operator in filter_part:
                name_part, value_part = filter_part.split(operator, 1)
                name = name_part[name_part.find('{') + 1: name_part.rfind('}')]

                value_part = value_part.strip()
                v0 = value_part[0]
                if (v0 == value_part[-1] and v0 in ("'", '"', '`')):
                    value = value_part[1: -1].replace('\\' + v0, v0)
                else:
                    try:
                        value = float(value_part)
                    except ValueError:
                        value = value_part

                # word operators need spaces after them in the filter string,
                # but we don't want these later
                return name, operator_type[0].strip(), value

    return [None] * 3

@app.callback(
    Output('data_table', "data"),
    Output('graph', "figure"),
    Output("graph-tooltip", "show"),
    Output("graph-tooltip", "bbox"),
    Output("graph-tooltip", "children"),
    #Output("placeholder", "active_cell"),
    Output("data_table", "active_cell"),
    Output("data_table", "selected_cells"),
    Output('data_table', 'page_current'),
    Output('tbl_out', 'children'),
    Input('data_table', "page_current"),
    Input('data_table', "sort_by"),
    Input('data_table', "filter_query"),
    Input("graph", "hoverData"),
    Input("graph", "figure"),
    Input('data_table', 'active_cell'),
    State('data_table', 'data'),
    State('data_table', "page_size"))

def update_table(page_current, sort_by, filter,  hoverData, dict_fig, active_cell, data_table, page_size):
    dff = get_table(df, page_size, page_current, sort_by, filter)
    triggered_id = callback_context.triggered[0]['prop_id']
    if 'data_table.active_cell' == triggered_id:
        try:
            active_cell, selected_cells, fig = update_graphs(active_cell, data_table, dict_fig)
            return no_update, fig, False, no_update, no_update, active_cell, selected_cells, no_update, F"{callback_context.triggered}-----{callback_context.triggered_prop_ids}---{callback_context.triggered_id}"
        except Exception as e:
            return no_update, no_update,  no_update, no_update, no_update, no_update, no_update, no_update, str(e)

    elif 'graph.hoverData' == triggered_id:
        try:
            #show, bbox, children, active_cell, selected_cells, geojson3, idx, error = update_tooltip_content(hoverData, flights_geojson, flight_data, dff, page_size)
            try:
                show, bbox, children, active_cell, selected_cells, idx, error = update_tooltip_content(hoverData, data_table, dff, page_size)
                hover_rec = hoverData['points'][0]['customdata'][0]
            except:
                hover_rec = None
            if hover_rec is not None:
                fig = go.Figure(dict_fig)
                fig.for_each_trace(lambda trace: trace.update(visible=False) if trace.name == "highlight" else())
                page_current = int((idx)/page_size)
#
                return dff.iloc[
            page_current*page_size: (page_current + 1)*page_size
        ].to_dict('records'), fig, show, bbox, children,active_cell, selected_cells, page_current, page_current
            else:
                return no_update, no_update,  False, bbox, no_update,no_update, no_update, no_update,no_update#F"{idx}:{active_cell}"
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            return no_update, no_update,  no_update, no_update, no_update, no_update, no_update, no_update,F"{exc_type}, {fname}, {exc_tb.tb_lineno}"

    else:
        fig = px.line(dff.sort_values('x').reset_index(drop=True)[['tail', 'fid', 'x', 'y']], x="x", y="y",color="tail",hover_data=[dff.fid])

        fig.update_traces(
            hoverinfo="none",
            hovertemplate=None
        )
        fig.add_scatter(y=[0], x=[0], mode="markers", visible = False, name = 'highlight', hoverinfo='skip', showlegend=False, marker=dict(size=12))

        return dff.iloc[
            page_current*page_size: (page_current + 1)*page_size
        ].to_dict('records'), fig, no_update, no_update, no_update,no_update, no_update, page_current, no_update

#@app.callback(
#    Output("data_table", "active_cell"),
#    Input("placeholder", "active_cell"))
def update_highlight(active_cell):
    return active_cell
def get_table(dff, page_size, page_current, sort_by, filter):
    if filter is not None:
        filtering_expressions = filter.split(' && ')

        for filter_part in filtering_expressions:
            col_name, operator, filter_value = split_filter_part(filter_part)
            if operator in ('eq', 'ne', 'lt', 'le', 'gt', 'ge'):
                # these operators match pandas series operator method names
                dff = dff.loc[getattr(dff[col_name], operator)(filter_value)]
            elif operator == 'contains':
                dff = dff.loc[dff[col_name].str.contains(filter_value)]
            elif operator == 'datestartswith':
                # this is a simplification of the front-end filtering logic,
                # only works with complete fields in standard format
                dff = dff.loc[dff[col_name].str.startswith(filter_value)]

    if len(sort_by):
        dff = dff.sort_values(
            [col['column_id'] for col in sort_by],
            ascending=[
                col['direction'] == 'asc'
                for col in sort_by
            ],
            inplace=False
        )
    return dff.reset_index(drop=True)

def find_xy(fid, json_dict):
    for tail_obj in json_dict:
        i = 0
        for obj in tail_obj['customdata']:
            if obj[0] == fid:
                return tail_obj['x'][i], tail_obj['y'][i]
            i +=1
    return None, None
def find_table_idx(fid, flight_data):
    i = 0
    for row_obj in flight_data:
        if fid == row_obj['fid']:
            return i
        i += 1
    return None

def update_tooltip_content(hoverData, flight_data, dff, page_size):
    try:
        if hoverData is None:
            return no_update, no_update, no_update, no_update, no_update, None, None

        pt = hoverData["points"][0]
        bbox = pt["bbox"]
        fid = hoverData['points'][0]['customdata'][0]
        try:
            idx = dff.index[dff['fid'] == fid][0]
            activecell, selectedcells = [{'column':0, 'row':idx-int(idx/page_size)*page_size, 'column_id': 'noupdate'}, [{'column':0, 'row':idx-int(idx/page_size)*page_size}]]
        except:
            idx = 0
            activecell, selectedcells = [None, []]
        children = [
            html.P(f"Date: {pt['x']}, ASP: {pt['y']}, fid: {fid}")
        ]
        return True, bbox, children, activecell, selectedcells, idx, F"{idx}:{fid}:{dff.index[dff['fid'] == fid][0]}-----{dff.to_json(orient='records')}"
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        return no_update, no_update, no_update, no_update, no_update, 0, F"{dff.to_json(orient='records')}----{idx}:{fid}----{exc_type}, {fname}, {exc_tb.tb_lineno}"

def update_graphs(active_cell, flight_data, dict_fig):
    if active_cell:
        fig = go.Figure(dict_fig)
        fig.for_each_trace(
            lambda trace: trace.update(visible=False) if trace.name == "highlight" else (),
        )
        if active_cell['column_id'] =='fid':
            fid = flight_data[active_cell['row']]['fid']
            x, y = find_xy(fid, dict_fig['data'])

            if x is not None and y is not None:
                fig.for_each_trace(
                    lambda trace: trace.update(visible=True, x=[x], y=[y]) if trace.name == "highlight" else (),
                )
            return active_cell, [active_cell], fig
        elif active_cell['column_id'] =='noupdate':
            return active_cell, [active_cell], no_update
        else:
            return None, [], fig
    else:
        return None, [], no_update
if __name__ == '__main__':
    app.run_server(debug=True) # Running the application```


问:
django python datetime not showing my linux server time
I deployed my Django project into my ubuntu server and at that time I set the timezone to UTC. Now I want to change the timezone. I changed my server time with

```<code>sudo timedatectl set-timezone Asia/Tehran
</code>```

and when I check the date with

```<code>date
</code>```

the command shows the right time with my timezone, but the problem is the time of my python Django project didn't change.
whenever I get the time of my project it doesn't show any updates from UTC to my timezone.
I use the DateTime module to get the time.
I restarted my Nginx, daphne, and gunicorn
with

```<code>sudo systemctl restart Nginx
sudo systemctl restart daphne
sudo systemctl restart gunicorn
</code>```

but it didn't help me.
how can I solve this problem?

Body:
I deployed my Django project into my ubuntu server and at that time I set the timezone to UTC. Now I want to change the timezone. I changed my server time with

sudo timedatectl set-timezone Asia/Tehran

and when I check the date with

date

the command shows the right time with my timezone, but the problem is the time of my python Django project didn't change.
whenever I get the time of my project it doesn't show any updates from UTC to my timezone.
I use the DateTime module to get the time.
I restarted my Nginx, daphne, and gunicorn
with

sudo systemctl restart Nginx
sudo systemctl restart daphne
sudo systemctl restart gunicorn

but it didn't help me.
how can I solve this problem?


问:
What does the influence_conversation parameter do?
From the rasa docs:

By default, entities influence action prediction. To prevent extracted
entities from influencing the conversation for specific intents you
can ignore entities for certain intents. To ignore an entity for all
intents, without having to list it under the ignore_entities flag of
each intent, you can set the flag influence_conversation to false
under the entity:

What does it actually mean to change the ignore_entities flag? The intent/entity combination is always processed by the NLU and can be queried in the next step in the story.. so what do they mean that it does not 'influence' the conversation?


问:
Can i make CKEditor 4 automatically wrap link tags?
When our customer inputs a link in a ckeditor field, and selects our custom style 'button', I want the generated 'a'-tag to be wrapped by a div (or some other element) automatically.

I couldn't find anything in the docs.

Thanks in advance!


问:
FFMPEG map 7.1 surround to 5.1 during transcode
I have a ProRes MOV whose audio contains 8 channels of audio in a 7.1 surround layout (L R C LFE Ls Rs Lt RT).

I am preparing an H.264 MP4 for a media player that only supports AAC, and does not support 7.1, so I would like to map to 5.1, dropping ther 7th and 8th channels (Lt and Rt). Under normal circumstances I would just use the below for my transcode:

ffmpeg -i input_file  -c:v libx264 -pix_fmt yuv420p -preset veryslow -crf 18 -c:a aac output_file

I've been looking at the documentation for audio layout manipulation, but am having trouble wrapping my head around it and they don't have a specific example of what I'm trying to do.

Do I need to export my audio to a WAV file first, or is there a way to manage the mapping in my transcode command? How can I map the existing first 6 channels to the new file?


问:
Android Realm asynchronous architecture in app with Activities & Fragments
I've been using Realm with UI thread writes until I found out the UI was unusable at some point with significant database volume.

I'm now trying to figure out how to properly orchestrate asynchronous writes in app with activities and fragments showing data list and screens to enter the data.

At this moment, my problem is:

I have an Activity A, with its own Realm instance, listing data and listening to realm changes to update itself.
If I want to add more data, I create an Activity B with its own Realm instance.

I've started listening to the onSuccess callback of the transaction to refresh() the Realm instance in order to trigger Realm listeners and have Activity A update itself. Unfortunately it doesn't work when I quickly go back to activity A because the Realm of Activity B is closed and onSuccess is not getting called.

At this point I'm not sure how should I organize all this. I see the option where I don't create Activity B and use fragments but having to do this everywhere in my app doesn't feel great and might be error prone.

What's the best practice for this use case?

Thanks a lot!


问:
How to redirect a python.exe within a pre-existing venv's .env file
Recently I uninstalled python and then reinstalled it to see what affects it would have on my code and ensure that I knew how to fix any path or directory issues. I mostly succeeded but am having trouble within my venvs. Testing out a basic django app I made any of my python manage.py ... code returns the error No Python at '"C:\Python311\python.exe'.

After doing some research it appears that the issue is that within .env\scripts there are two files called "python.exe" and "pythonw.exe" are causing the problem because they are trying to access a python.exe that no longer exists. (Note this is my understanding based off of pythons venv document and I could be incorrect)

My question is what is the best way to deal with this issue. I see two options but am not sure how to accomplish either.

Fully reset the .env folder so it points to the correct python.

Just change those two files so they point to the correct instance of python.

So far the only things I have tested are running code outside of venv's entirely and creating new ones to run the code from. Both work totally fine so it is definitely something from the historic venvs.

I have also looked at this question and I believe the two to be related but could be mistaken. Unfortunately it does not seem an answer was given there.


问:
How to pass javascript variable to PHP file
I have a link with javascript onclick function that gets html code from current page say a.php sends to javascript file script.js to edit it and now should go to destination php file print_invoice.php.

I have successfully sent data from php to javascript file and edited the data. Now i want to send to  print_invoice.php. See my code below:

a.php

```<code> <td><a id="getinfo"  href="print_invoice.php?invoice_id='.$invoiceDetails["order_id"].'"    onclick="invoice_ajax('.count(getInvoiceItems($invoiceDetails["order_id"])).')"  data-info="'.base64_encode($template).'" title="Print Invoice"><span class="glyphicon glyphicon-print"></span></a></td>
</code>```

script.js

```<code>var data = 'targetData';

    var variableToSend = 'foo';
$.post('print_invoice.php', {variable: variableToSend});
</code>```

print_invoice.php

```<code>$variable = $_POST['variable'];

 echo $variable;
</code>```

Body:
I have a link with javascript onclick function that gets html code from current page say a.php sends to javascript file script.js to edit it and now should go to destination php file print_invoice.php.

I have successfully sent data from php to javascript file and edited the data. Now i want to send to  print_invoice.php. See my code below:

a.php

script.js

var data = 'targetData';

    var variableToSend = 'foo';
$.post('print_invoice.php', {variable: variableToSend});

print_invoice.php

$variable = $_POST['variable'];

 echo $variable;


问:
How to make it compile?

type PageParamsKeys = keyof GenericPageParams;

type GenericPageParams = {
  pathParams?: Record<string, string>;
  searchParams?: Record<string, string>;
  state?: Record<string, any>;
};

type ExactParams<T extends GenericPageParams> = keyof T extends PageParamsKeys
    ? Pick<T, PageParamsKeys>
    : never;

function usePageParams<T extends GenericPageParams>(): ExactParams<T> {
    const pathParams = {} as T["pathParams"];
    const searchParams = {} as T["searchParams"];
    const state = {} as T["state"];

    return {
        pathParams: pathParams,
        searchParams: searchParams,
        state: state,
    };
}
```
<p>Whatever I try to feed to <code>return</code> it doesn't compile. I cannot understand why.
The error:</p>
```Type '{ pathParams: {}; searchParams: {}; state: {}; }' is not assignable to type 'ExactParamss<T>'.
```
<p>What I want to achieve: usePageParams could accept any type which is a subset of GenericPageParams' properties, but is fully typed.</p>
<p>Example:</p>
```usePageParams<{state: { id: string }}>();
```

Title: How to make it compile?

Body:
type PageParamsKeys = keyof GenericPageParams;

type GenericPageParams = {
  pathParams?: Record<string, string>;
  searchParams?: Record<string, string>;
  state?: Record<string, any>;
};

type ExactParams<T extends GenericPageParams> = keyof T extends PageParamsKeys
    ? Pick<T, PageParamsKeys>
    : never;

function usePageParams<T extends GenericPageParams>(): ExactParams<T> {
    const pathParams = {} as T["pathParams"];
    const searchParams = {} as T["searchParams"];
    const state = {} as T["state"];

    return {
        pathParams: pathParams,
        searchParams: searchParams,
        state: state,
    };
}

Whatever I try to feed to return it doesn't compile. I cannot understand why.
The error:

Type '{ pathParams: {}; searchParams: {}; state: {}; }' is not assignable to type 'ExactParamss<T>'.

What I want to achieve: usePageParams could accept any type which is a subset of GenericPageParams' properties, but is fully typed.

Example:

usePageParams<{state: { id: string }}>();


问:
Next JS Image component doesn't load svg beforehand / disable "Lazy Loading"
The problem is only with svg images. Works well with other formats

Hello! I am using an Image component in nextjs. I ran into a problem while trying to add an svg image to a modal window. When I open the modal the image is missing and it takes about a second to load. This happens every time the modal window is reopened.

I think this is due to "Lazy Loading". This option is very inappropriate in this case. I would like to load the image as soon as the user enters the site, and not during the opening of the modal window

I have tried several ways.

assign Image properties to the component

```<code>     `

    <Image
     src={Email}
     alt={"Picture"}
     width={20}
     height={20}
     loading={"eager"}
     priority
 />

    `
</code>```

Problem still exists. Loading an image takes a second of time after each modal window is opened

Load an image in the main component, and pass it through props to the modal window.
Problem still exists

My svg image is very small. I have also tried other images

Body:
The problem is only with svg images. Works well with other formats

Hello! I am using an Image component in nextjs. I ran into a problem while trying to add an svg image to a modal window. When I open the modal the image is missing and it takes about a second to load. This happens every time the modal window is reopened.

I think this is due to "Lazy Loading". This option is very inappropriate in this case. I would like to load the image as soon as the user enters the site, and not during the opening of the modal window

I have tried several ways.

assign Image properties to the component

     `

    <Image
     src={Email}
     alt={"Picture"}
     width={20}
     height={20}
     loading={"eager"}
     priority
 />

    `

Problem still exists. Loading an image takes a second of time after each modal window is opened

Load an image in the main component, and pass it through props to the modal window.
Problem still exists

My svg image is very small. I have also tried other images


问:
Error while knitting Rmarkdown with reticulate: OSError: libomp.dylib not found
I'm trying to knit an Rmarkdown with reticulate for a chunk of python code.
Knitting throws out an error saying libomp.dylib not found, but the code runs fine as a chunk (not knitted).

Machine: Macbook M1 Max
OS: Ventura 13.0.1

I used below packages for python with reticulate.

```<code>library(reticulate)
use_python("/Users/ramanujam/opt/anaconda3/bin/python")
</code>```
```<code>from lazypredict.Supervised import LazyClassifier
from sklearn.model_selection import train_test_split
</code>```

I'm Getting the error below.
However, code executes fine as a chunk.

```<code>Error in py_call_impl(callable, dots$args, dots$keywords) :
  OSError: dlopen(/Users/xxx/opt/anaconda3/lib/python3.9/site-packages/lightgbm/lib_lightgbm.so, 0x0006): Library not loaded: /usr/local/opt/libomp/lib/libomp.dylib
  Referenced from: <8DF2AF67-B85F-3F67-B687-E50A514307EC> /Users/xxx/opt/anaconda3/lib/python3.9/site-packages/lightgbm/lib_lightgbm.so
  Reason: tried: '/usr/local/opt/libomp/lib/libomp.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/usr/local/opt/libomp/lib/libomp.dylib' (no such file), '/usr/local/opt/libomp/lib/libomp.dylib' (no such file), '/Library/Frameworks/R.framework/Resources/lib/libomp.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/server/libomp.dylib' (no such file)
</code>```

I underestand this is a dependency on libomp.
I already tried installing libomp with

```<code>brew install libomp
</code>```

Tried creating a symlink to R.framework path from the brew install location but there is a conflict of architecture there.

Since the code executes in chunk but has trouble during knitting, I'm guessing the libomp source used is different there. But I'm not clear on how or why Rstudio would have a different source while running in chunks vs. knitting as I have specified the python path to be used.

Any help would be appreciated. Thanks in advance!

Body:
I'm trying to knit an Rmarkdown with reticulate for a chunk of python code.
Knitting throws out an error saying libomp.dylib not found, but the code runs fine as a chunk (not knitted).

Machine: Macbook M1 Max
OS: Ventura 13.0.1

I used below packages for python with reticulate.

library(reticulate)
use_python("/Users/ramanujam/opt/anaconda3/bin/python")

from lazypredict.Supervised import LazyClassifier
from sklearn.model_selection import train_test_split

I'm Getting the error below.
However, code executes fine as a chunk.

Error in py_call_impl(callable, dots$args, dots$keywords) :
  OSError: dlopen(/Users/xxx/opt/anaconda3/lib/python3.9/site-packages/lightgbm/lib_lightgbm.so, 0x0006): Library not loaded: /usr/local/opt/libomp/lib/libomp.dylib
  Referenced from: <8DF2AF67-B85F-3F67-B687-E50A514307EC> /Users/xxx/opt/anaconda3/lib/python3.9/site-packages/lightgbm/lib_lightgbm.so
  Reason: tried: '/usr/local/opt/libomp/lib/libomp.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/usr/local/opt/libomp/lib/libomp.dylib' (no such file), '/usr/local/opt/libomp/lib/libomp.dylib' (no such file), '/Library/Frameworks/R.framework/Resources/lib/libomp.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/jre/lib/server/libomp.dylib' (no such file)

I underestand this is a dependency on libomp.
I already tried installing libomp with

brew install libomp

Tried creating a symlink to R.framework path from the brew install location but there is a conflict of architecture there.

Since the code executes in chunk but has trouble during knitting, I'm guessing the libomp source used is different there. But I'm not clear on how or why Rstudio would have a different source while running in chunks vs. knitting as I have specified the python path to be used.

Any help would be appreciated. Thanks in advance!


问:
what are the cons and pros of SQL and NoSQL databases usage in the same project?
actually, I'm not sure if Stackoverflow is a suitable platform for asking such questions or not but I looked for this question many times and found many answers, and all answers agreed that NoSQL usage is perfect for real-time data transfer.

what I want to ask is that during a conversation between me and someone I used Django Celery to achieve the task using PostgreSQL where I used to Update data in real-time but he advised me that SQL is not the preferable database to execute such that task because it's slower so, he advised me to use NoSQL database instead or something like MongoDB. I take a while to search for what he advised me and I found that NoSQL structure is good for Graphs and Real-time data transactions and SQL for other purposes such as relationships between data and other.

but there are many questions that I want to ask for these:

1 - first of all, Is that right that SQL is slower than NoSQL when it deals with data in Real-time? if yes, so why?

2- if NoSQL is good for some purposes and bad for others unlike SQL then, Can I use two different databases like Postgresql and MongoDB together in one project (with Django for our example)?

3- if I can mix those two databases together so, I see that there are many things that will make it slower because once I use for example User as a column in the database and when I want to Update something for that user so, it will do two requests for both of database updates, Am I right in that?


问:
Error catching with a method inside a class
I have a lot of method with in my class :

   ethod def m(self):
        try:
            some code
        except KeyError:
            default value
        return value
```
<p>I want to make a method for error handling like this :</p>
<pre class="lang-py prettyprint-override"><code>    def get_field_value(method, default_value='N/A'):
        """Get the field value."""
        try:
            value = self.method
        except :
            value = default_value
        return value
</code>```

But when I run my test it doesn't work :

can you help me with how to write it and how to write my tests :

def test_field():

    h = class_instance()
    assert class_name.get_field_value(instance.method()) == 'N/A'
```

Im using Pytest to test my code

Body:
I have a lot of method with in my class :

   ethod def m(self):
        try:
            some code
        except KeyError:
            default value
        return value

I want to make a method for error handling like this :

    def get_field_value(method, default_value='N/A'):
        """Get the field value."""
        try:
            value = self.method
        except :
            value = default_value
        return value

But when I run my test it doesn't work :

can you help me with how to write it and how to write my tests :

def test_field():

    h = class_instance()
    assert class_name.get_field_value(instance.method()) == 'N/A'

Im using Pytest to test my code


问:
Restrict executer and driver, memory and core parameter in spark-submit on spark only cluster
We have a spark only cluster for multiple users, in spark-default.conf have below property set

spark.driver.memory 2g

spark.executor.cores 1

spark.executor.memory 2g

As we have a multiple users, i dont want users to pass below parameters in spark-submit command as this can utilise complete cluster resources.

--driver-memory 5g

--executor-cores 5

--executor-memory 5g

is that any possible way to restrict passing above runtime value in spark-submit command ?

try added this property as max value but still users are running with some random values less than 5

spark.cores.max 5


问:
BeanCreationException: Error creating bean with name 'articleRepository' defined in
I am making a simple Spring application. And I keep getting this error

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'articleController': Unsatisfied dependency expressed through field 'articleRepository': Error creating bean with name 'articleRepository' defined in com.example.work.repositories.ArticleRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.work.models.Article
</code>```

Here is my Article.java code

```<code>package com.example.work.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;
    private String description;
    private String text;

    public Article(String name, String description, String text) {
        this.name = name;
        this.description = description;
        this.text = text;
    }

    public Article(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
</code>```

Here is my @SpringBootApplication class

```<code>package com.example.work;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WorkApplication {

    public static void main(String[] args) {
        SpringApplication.run(WorkApplication.class, args);
    }

}
</code>```

Here is the ArticleRepository.java

```<code>package com.example.work.repositories;

import com.example.work.models.Article;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ArticleRepository extends CrudRepository<Article, Long> {
}
</code>```

And the ArticleController.java

```<code>package com.example.work.controllers;

import com.example.work.models.Article;
import com.example.work.repositories.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ArticleController {
    @Autowired
    private ArticleRepository articleRepository;

    @GetMapping("/article")
    public String article(Model model){
        Iterable<Article> articles = articleRepository.findAll();
        model.addAttribute("articles", articles);
        return "article";
    }
}
</code>```

And the whole project structure:
project structure

I have tried to find answerd for my issue, but I have only found the advice to check @Entity and @Id annotations in my models. But I do have them there, so I have no idea what to do :(

Body:
I am making a simple Spring application. And I keep getting this error

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'articleController': Unsatisfied dependency expressed through field 'articleRepository': Error creating bean with name 'articleRepository' defined in com.example.work.repositories.ArticleRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.work.models.Article

Here is my Article.java code

package com.example.work.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;
    private String description;
    private String text;

    public Article(String name, String description, String text) {
        this.name = name;
        this.description = description;
        this.text = text;
    }

    public Article(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

Here is my @SpringBootApplication class

package com.example.work;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WorkApplication {

    public static void main(String[] args) {
        SpringApplication.run(WorkApplication.class, args);
    }

}

Here is the ArticleRepository.java

package com.example.work.repositories;

import com.example.work.models.Article;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ArticleRepository extends CrudRepository
 {
}

And the ArticleController.java

package com.example.work.controllers;

import com.example.work.models.Article;
import com.example.work.repositories.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ArticleController {
    @Autowired
    private ArticleRepository articleRepository;

    @GetMapping("/article")
    public String article(Model model){
        Iterable
 articles = articleRepository.findAll();
        model.addAttribute("articles", articles);
        return "article";
    }
}

And the whole project structure:
project structure

I have tried to find answerd for my issue, but I have only found the advice to check @Entity and @Id annotations in my models. But I do have them there, so I have no idea what to do :(


问:
SwiftUI intrinsicContentSize is wrong when trying to render a view to image
Right off the bat, I am trying to render a custom SwiftUI View into an UIImage, but I am having issues. This is one of my first forays into SwiftUI so I might be missing something fundamental.

The test app is a photo collage app and I have this base view.

Each purple frame is a button which allows the user to pick an image, and will add it in a ZStack as an Image.

Tapping save results in this 10x10 pts image.

The full code:

```<code>//
//  ContentView.swift
//  photoframer
//
//  Created by Jonathan on 12/11/22.
//

import SwiftUI
import PhotosUI
import PhotoLibraryPicker

struct Screenn<Content: View>: View {
    var viewToScreenShot: Content
    var body: some View {
        VStack(alignment: .leading) {
            viewToScreenShot
            Button("save") {
                let img = viewToScreenShot.snapshot()
                UIImageWriteToSavedPhotosAlbum(img!, nil, nil, nil)
            }
            Spacer()
        }
        .navigationBarTitleDisplayMode(.inline)
        .navigationTitle("Choose Photos")
    }
}

struct Frame2v1h: View {
    var padding: CGFloat = 10

    var body: some View {
            VStack {
                VStack(spacing: padding) {
                    HStack(spacing: padding) {
                        ImagePickerButton()
                        ImagePickerButton()
                    }
                    ImagePickerButton()
                }
            }
            .padding(padding)
            .border(.blue, width: 2)
    }

}

struct ImagePickerButton: View {
    @State private var showImagePicker = false
    @State var pictures = [Picture]()

    var body: some View {
        ZStack {
            if !pictures.isEmpty {
                Rectangle()
                    .overlay (
                        pictures.first?.toImage(width: Int(pictures.first!.asset.pixelWidth), height: Int(pictures.first!.asset.pixelHeight), mode: .aspectFill)
                            .resizable()
                            .scaledToFill()
                        )
                    .clipped()
            }
            Button {
                self.showImagePicker = true
            } label: {
                Text(pictures.isEmpty ? "+" : "+++")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .foregroundColor(.red)
                    .border(Color.purple, width: 5)
            }
            .sheet(isPresented: $showImagePicker) {
                PhotoLibraryPicker(self.$pictures)
            }
        }
    }
}

extension View {

    func snapshot() -> UIImage? {

        // Note: since iOS 15 it seems these two modifiers are required.
        let controller = UIHostingController(
            rootView: self.ignoresSafeArea()
                .fixedSize(horizontal: true, vertical: true)
        )
        guard let view = controller.view else { return nil }

        let targetSize = view.intrinsicContentSize
        if targetSize.width <= 0 || targetSize.height <= 0 { return nil }

        view.bounds = CGRect(origin: .zero, size: targetSize)
        view.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }

    }

}

</code>```

It seems like the issue is that the let targetSize = view.intrinsicContentSize is always 10x10.

Any ideas of what I am doing wrong here? I've tried at least 10 snapshot solutions from SO and across the web.

Body:
Right off the bat, I am trying to render a custom SwiftUI View into an UIImage, but I am having issues. This is one of my first forays into SwiftUI so I might be missing something fundamental.

The test app is a photo collage app and I have this base view.

Each purple frame is a button which allows the user to pick an image, and will add it in a ZStack as an Image.

Tapping save results in this 10x10 pts image.

The full code:

//
//  ContentView.swift
//  photoframer
//
//  Created by Jonathan on 12/11/22.
//

import SwiftUI
import PhotosUI
import PhotoLibraryPicker

struct Screenn<Content: View>: View {
    var viewToScreenShot: Content
    var body: some View {
        VStack(alignment: .leading) {
            viewToScreenShot
            Button("save") {
                let img = viewToScreenShot.snapshot()
                UIImageWriteToSavedPhotosAlbum(img!, nil, nil, nil)
            }
            Spacer()
        }
        .navigationBarTitleDisplayMode(.inline)
        .navigationTitle("Choose Photos")
    }
}

struct Frame2v1h: View {
    var padding: CGFloat = 10

    var body: some View {
            VStack {
                VStack(spacing: padding) {
                    HStack(spacing: padding) {
                        ImagePickerButton()
                        ImagePickerButton()
                    }
                    ImagePickerButton()
                }
            }
            .padding(padding)
            .border(.blue, width: 2)
    }

}

struct ImagePickerButton: View {
    @State private var showImagePicker = false
    @State var pictures = [Picture]()

    var body: some View {
        ZStack {
            if !pictures.isEmpty {
                Rectangle()
                    .overlay (
                        pictures.first?.toImage(width: Int(pictures.first!.asset.pixelWidth), height: Int(pictures.first!.asset.pixelHeight), mode: .aspectFill)
                            .resizable()
                            .scaledToFill()
                        )
                    .clipped()
            }
            Button {
                self.showImagePicker = true
            } label: {
                Text(pictures.isEmpty ? "+" : "+++")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .foregroundColor(.red)
                    .border(Color.purple, width: 5)
            }
            .sheet(isPresented: $showImagePicker) {
                PhotoLibraryPicker(self.$pictures)
            }
        }
    }
}

extension View {

    func snapshot() -> UIImage? {

        // Note: since iOS 15 it seems these two modifiers are required.
        let controller = UIHostingController(
            rootView: self.ignoresSafeArea()
                .fixedSize(horizontal: true, vertical: true)
        )
        guard let view = controller.view else { return nil }

        let targetSize = view.intrinsicContentSize
        if targetSize.width <= 0 || targetSize.height <= 0 { return nil }

        view.bounds = CGRect(origin: .zero, size: targetSize)
        view.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }

    }

}

It seems like the issue is that the let targetSize = view.intrinsicContentSize is always 10x10.

Any ideas of what I am doing wrong here? I've tried at least 10 snapshot solutions from SO and across the web.


问:
Django ORM, displaying the nested for loops in the template
I'm building a school management system and right now I have implemented the backend for the 'Absences' of the student app, but I am not able to display it properly for the currently logged in student, bacause if the absence model exists on the same day more than once it is displaying everything once again.
Here is my code:

models.py

```<code>> import datetime
> from django.db import models
> from django.utils.translation import gettext_lazy as _
> from accounts.models import User
>
>
> class Hour(models.Model):
> value = models.IntegerField(_('value'), unique=True)
> time_period = models.CharField(_('time period'), max_length=55, unique=True)
>
> class Meta:
> ordering = ('value',)
> verbose_name = _('hour')
> verbose_name_plural = _('hours')
>
> def __str__(self):
> return str(self.value)
>
>
> class Type(models.Model):
> name = models.CharField(_('name'), max_length=55, unique=True)
>
> class Meta:
> ordering = ('name',)
> verbose_name = _('type')
> verbose_name_plural = _('types')
>
> def __str__(self):
> return self.name
>
>
> class Absence(models.Model):
> student = models.ForeignKey(User, on_delete=models.CASCADE, related_name='student1')
> teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacher1')
> hour = models.ForeignKey(Hour, on_delete=models.CASCADE)
> type = models.ForeignKey(Type, on_delete=models.CASCADE)
> day = models.DateField(_('day'), default=datetime.date.today)
> date_created = models.DateTimeField(auto_now_add=True)
> date_updated = models.DateTimeField(auto_now=True)
>
> class Meta:
> ordering = ('-day',)
> verbose_name = _('absence')
> verbose_name_plural = _('absences')
>
> def __str__(self):
> return str(self.hour)
</code>```

views.py

```<code>> def index_view(request):
> absences = Absence.objects.filter(student=request.user.id)
> hours = Hour.objects.all()
>
>
> year = datetime.now().year
> month = datetime.now().month
>
> number_of_days = calendar.monthrange(year, month)[1]
>
> first_day = date(year, month, 1)
> last_day = date(year, month, number_of_days)
>
> days = []
>
> delta = last_day - first_day
>
> for i in range(delta.days + 1):
> days.append((first_day + timedelta(days=i)).strftime('%d-%m-%Y'))
>
> days.reverse()
>
> for absence in absences:
> print(absence.hour)
> for i in days:
> print(i)
>
> context = {
>             'absences': absences,
>             'days': days,
>             'hours': hours,
>         }
>
> return render(request, 'absences/index.html', context)
</code>```

index.html

```<code>> <table class="table">
>     <thead>
>         <tr>
>             <th scope="col"></th>
>             <th scope="col"></th>
>         </tr>
>     </thead>
>     <tbody>
> for day in days %}
>             <tr>
>                 <td class="w-25 align-middle">{{ day }}</td>
>                 <td>
> for absence in absences %}
> for hour in hours %}
> if absence.day|date:'d-m-Y' == day  %}
> if absence.hour == hour %}
>                                     <mark>n</mark>
>
> endif %}
>                                 <mark>ob</mark>
> endif %}
> endfor %}
> endfor %}
>
>                 </td>
>             </tr>
> endfor %}
>     </tbody>
> </table>
</code>```

And here is a picture about what I am talking about:
enter image description here

Thanks for help in advance. Have a nice day.

I have been trying to fix the "absences display" for the whole two days and I'm stuck. I will appreciate every help.Thanks in advance

Body:
I'm building a school management system and right now I have implemented the backend for the 'Absences' of the student app, but I am not able to display it properly for the currently logged in student, bacause if the absence model exists on the same day more than once it is displaying everything once again.
Here is my code:

models.py

> import datetime
> from django.db import models
> from django.utils.translation import gettext_lazy as _
> from accounts.models import User
>
>
> class Hour(models.Model):
> value = models.IntegerField(_('value'), unique=True)
> time_period = models.CharField(_('time period'), max_length=55, unique=True)
>
> class Meta:
> ordering = ('value',)
> verbose_name = _('hour')
> verbose_name_plural = _('hours')
>
> def __str__(self):
> return str(self.value)
>
>
> class Type(models.Model):
> name = models.CharField(_('name'), max_length=55, unique=True)
>
> class Meta:
> ordering = ('name',)
> verbose_name = _('type')
> verbose_name_plural = _('types')
>
> def __str__(self):
> return self.name
>
>
> class Absence(models.Model):
> student = models.ForeignKey(User, on_delete=models.CASCADE, related_name='student1')
> teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='teacher1')
> hour = models.ForeignKey(Hour, on_delete=models.CASCADE)
> type = models.ForeignKey(Type, on_delete=models.CASCADE)
> day = models.DateField(_('day'), default=datetime.date.today)
> date_created = models.DateTimeField(auto_now_add=True)
> date_updated = models.DateTimeField(auto_now=True)
>
> class Meta:
> ordering = ('-day',)
> verbose_name = _('absence')
> verbose_name_plural = _('absences')
>
> def __str__(self):
> return str(self.hour)

views.py

> def index_view(request):
> absences = Absence.objects.filter(student=request.user.id)
> hours = Hour.objects.all()
>
>
> year = datetime.now().year
> month = datetime.now().month
>
> number_of_days = calendar.monthrange(year, month)[1]
>
> first_day = date(year, month, 1)
> last_day = date(year, month, number_of_days)
>
> days = []
>
> delta = last_day - first_day
>
> for i in range(delta.days + 1):
> days.append((first_day + timedelta(days=i)).strftime('%d-%m-%Y'))
>
> days.reverse()
>
> for absence in absences:
> print(absence.hour)
> for i in days:
> print(i)
>
> context = {
>             'absences': absences,
>             'days': days,
>             'hours': hours,
>         }
>
> return render(request, 'absences/index.html', context)

index.html

>

>

>

>
>
>

>

>

> for day in days %}
>

>                 {{ day }}
>
> for absence in absences %}
> for hour in hours %}
> if absence.day|date:'d-m-Y' == day  %}
> if absence.hour == hour %}
>                                     n
>
> endif %}
>                                 ob
> endif %}
> endfor %}
> endfor %}
>
>
>

> endfor %}
>

>

And here is a picture about what I am talking about:
enter image description here

Thanks for help in advance. Have a nice day.

I have been trying to fix the "absences display" for the whole two days and I'm stuck. I will appreciate every help.Thanks in advance


问:
Auth0 redirect when user is another organization member
I have two organizations in auth0, the users are the same but a group of them is from organization A and the rest from organization B. When a user from B login into A, the authguard of Auth0 when i use in canActivate only shows me the login form and I would like to display an unauthorized page for users. I make authguard because i see in url params has error=... but i cant get params in guard. any sugestion for this solution?

 {
    path: '',
    component: FullComponent,
    canActivate: [Auth0AutomationGuard],
    children: [
]}
```
<h1>customauthguard</h1>
<p>i am trying use route, this.route but dont work</p>
<pre class="lang-js prettyprint-override"><code>  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
        //obtenemos los parametros de la ruta
        let params = route.queryParams; // i try with this.route || route doesnt have params
</code>```

url when auth0 redirect

Body:
I have two organizations in auth0, the users are the same but a group of them is from organization A and the rest from organization B. When a user from B login into A, the authguard of Auth0 when i use in canActivate only shows me the login form and I would like to display an unauthorized page for users. I make authguard because i see in url params has error=... but i cant get params in guard. any sugestion for this solution?

 {
    path: '',
    component: FullComponent,
    canActivate: [Auth0AutomationGuard],
    children: [
]}

customauthguard

i am trying use route, this.route but dont work

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
        //obtenemos los parametros de la ruta
        let params = route.queryParams; // i try with this.route || route doesnt have params

url when auth0 redirect


问:
error MSB3073: The command "npm install" exited with code 1
```<code>    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />

</code>```

I am running "dotnet watch run" command in dotnet and react project. I'm getting this error for the above line of code found in the ".csproj" file.

Body:
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />

I am running "dotnet watch run" command in dotnet and react project. I'm getting this error for the above line of code found in the ".csproj" file.


问:
Trino - selecting date field - exceeds MAX_INT
I am using Hive connector. My Trino table is on a parquet file.  One of the fields is of type date.  When I do select * from the table, it fails with the error
[Code: 65536, SQL State: ]  Query failed (#20221210_041726_00031_4iqfp): Value 1610514540000000 exceeds MAX_INT

I have also tried to only select this date field by itself and still get the above error. How can my query return value?


问:
Laravel - Always filter model results based on user relation
I have 3 tables, a table of users, another of properties, and another that lists what properties each user can see.

Is there any way, whenever property data is collected, it is filtered by the relationship with the user? So that I don't have to create the filter in each query, or ad a scope, or "with" to take relation?

Something similar to what "SoftDeletes" does to always filter the "deleted" ones. But passing the user/properties relationship.


问:
Laravel php artisan schedule:run directly on bash
I have a laravel application hosted on a ubuntu server.While i was setting up the scheduler i ran this command on the terminal:

```<code>php artisan schedule:run >> /dev/null 2>&1
</code>```

Reading the documentation it says that i should have included the previous command in a cron file.I then created a cron configuration like so:

```<code>* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
</code>```

When using ps aux to check it shows:

```<code>User1@Laravel-Project:~$ ps aux | grep "artisan schedule:run"
User1  143147  0.0  0.0   7008  2100 pts/4    S+   16:55   0:00 grep artisan schedule:run
</code>```

Will this create a problem in the future and so how can i fix it

Body:
I have a laravel application hosted on a ubuntu server.While i was setting up the scheduler i ran this command on the terminal:

php artisan schedule:run >> /dev/null 2>&1

Reading the documentation it says that i should have included the previous command in a cron file.I then created a cron configuration like so:

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

When using ps aux to check it shows:

User1@Laravel-Project:~$ ps aux | grep "artisan schedule:run"
User1  143147  0.0  0.0   7008  2100 pts/4    S+   16:55   0:00 grep artisan schedule:run

Will this create a problem in the future and so how can i fix it


问:
Why is <output omitted> when running view_df() function?
I have ~11,000 customer surveys that I want to do some exploratory data analysis on.  Running the view_df() function is omitting some information in the table, so I trimmed down the dataframe to just 3 columns to troubleshoot.

str(test1)

'data.frame':   11845 obs. of  3 variables:
Survey.Type: chr  "FULL" "FULL" "FULL" "FULL" ...
GROUP      : chr  "Current_Production" "Current_Production" "Current_Production" "Current_Production" ...
STATE      : chr  "Oregon" "California" "California" "California" ...

But when I run the view_df() there are aspects that are showing as .

view_df(test1, show.na = TRUE, show.type = TRUE, show.frq = TRUE, show.prc = TRUE)

view_df table

What's weird is that I can run individual bar charts no problem.

plot_frq(test1, Survey.Type, show.na = TRUE)

Survey.Type bar chart

plot_frq(test1, GROUP, show.na = TRUE)

GROUP bar chart

plot_frq(test1, STATE, show.na = TRUE)

STATE bar chart

Any thoughts on what I can do to get the full view_df() table?

Thank You!

I tried adding and removing arguments in the view_df() function.  I confirmed the data.frame structure.  I confirmed the frequency results on individual variables is correct.


问:
How do I get the state of a redux slice ouside of a react component?
I want to create a helper.ts file which uses the updated state from a redux slice.

How do i get the updated state?

I tried using store.getState().<sliceName> however that only gives the initial state and not the updated state.