问:
Movie to another Screen in React Native Tab View
I only want to navigate to my other screen "MycoursesPage2 from my page MycoursesPage
This is the actual code. it is giving an error on onpress function that "undefined is an object (evaluating navigation.navigate)"

```<code>import React, {useState} from "react";
import { View, StyleSheet, TouchableOpacity, Image, Dimensions, ScrollView, StatusBar, Text } from 'react-native';
import { SafeAreaView } from "react-native-safe-area-context";
import CustomHeader from "../../components/CustomHeader";
import { IMAGE } from "../../constants/Images";
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import * as Progress from 'react-native-progress';

const FirstRoute = ({navigation}) => (
  <ScrollView>
  <View style={[styles.scene, { backgroundColor: '#f7f7f7' }]} />

  </ScrollView>
);

function SecondRoute({ navigation }) {
  return (
  <ScrollView>
  <View style={[styles.scene, { backgroundColor: '#f7f7f7' }]} />
  <TouchableOpacity onPress={() => navigation.navigate("Register")}>

              <View
                style={{
                  borderWidth: 1,
                  borderColor: "#fff",
                  backgroundColor:'#fff',
                  borderRadius: 10,
                  padding: 15,
                  marginHorizontal:20,
                  marginVertical: 15,
                  display:'flex',
                  flexDirection:'row'
                }}
              >
                <Image
                  source={IMAGE.MYCOURSES3}
                  style={{ width: 60, height: 60 }}
                />
                <View>

                <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>3D Design Illustration</Text>
                <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>2hrs 25mins</Text>

              <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={1} width={200} />
              </View>

              </View>

   </TouchableOpacity>
  <TouchableOpacity>

    <View
      style={{
        borderWidth: 1,
        borderColor: "#fff",
        backgroundColor:'#fff',
        borderRadius: 10,
        padding: 15,
        marginHorizontal:20,
        display:'flex',
        flexDirection:'row'
      }}
    >
      <Image
        source={IMAGE.MYCOURSES4}
        style={{ width: 60, height: 60 }}
      />
      <View>

      <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>CRM Management</Text>
      <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>3hrs 20mins</Text>

    <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={0.88} width={200} />
    </View>

    </View>

  </TouchableOpacity>
  <TouchableOpacity>

    <View
      style={{
        borderWidth: 1,
        borderColor: "#fff",
        backgroundColor:'#fff',
        borderRadius: 10,
        padding: 15,
        marginHorizontal:20,
        marginVertical:15,
        display:'flex',
        flexDirection:'row'
      }}
    >
      <Image
        source={IMAGE.MYCOURSES5}
        style={{ width: 60, height: 60 }}
      />
      <View>

      <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>Flutter Mobile Apps</Text>
      <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>4hrs 50mins</Text>

    <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={0.95} width={200} />
    </View>

    </View>

  </TouchableOpacity>
  <TouchableOpacity>

    <View
      style={{
        borderWidth: 1,
        borderColor: "#fff",
        backgroundColor:'#fff',
        borderRadius: 10,
        padding: 15,
        marginHorizontal:20,
        display:'flex',
        flexDirection:'row'
      }}
    >
      <Image
        source={IMAGE.MYCOURSES6}
        style={{ width: 60, height: 60 }}
      />
      <View>

      <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>3D Icons Set Blender</Text>
      <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>2hrs 45mins</Text>

    <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={0.85} width={200} />
    </View>

    </View>

  </TouchableOpacity>

  </ScrollView>
  )
}

const initialLayout = { width: Dimensions.get('window').width };

function MyCoursesPage({ navigation }) {
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: 'first', title: 'Ongoing' },
    { key: 'second', title: 'Completed' },
  ]);

  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
  });

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor:'#f7f7f7' }}>

      <CustomHeader title="My Courses" isHome={true} navigation={navigation} />

      <View style={{
        flexDirection: "row",
        justifyContent: "flex-end",
        marginTop:-35
      }}>
         <TouchableOpacity >
      <Image source={IMAGE.MYCOURSES1} style={{width: 22, height:22}}/>
      </TouchableOpacity>
      <TouchableOpacity >
      <Image source={IMAGE.MYCOURSES2} style={{width: 22, height:22, marginHorizontal:15}}/>
      </TouchableOpacity>
      </View>

      <TabView
      navigationState={{ index, routes }}
      renderTabBar={props => (
        <TabBar
          {...props}
          renderLabel={({ route, color }) => (
            <Text style={{ color: '#335ef7', fontWeight:'bold', margin: 8 }}>
              {route.title}
            </Text>
          )}
          style={{backgroundColor: 'white'}}
        />
      )}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={initialLayout}
      style={styles.container}
    />

    </SafeAreaView>
  );
}

export default MyCoursesPage;

const styles = StyleSheet.create({
  container: {
    marginTop: StatusBar.currentHeight,
  },
  scene: {
    flex: 1,
  },
});
</code>```

and my stack navigator code is below

```<code>import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import MyCoursesPage from "../pages/MyCourses/MyCoursesPage";
import MyCoursesPage2 from "../pages/MyCourses/MyCoursesPage2"
import MyCoursesDetailsPage from "../pages/MyCourses/MyCoursesDetailsPage";
import Coursedetailscreen from "../pages/MyCourses/Coursedetailscreen";

const StackSetting = createStackNavigator();

function MyCoursesStackNavigator() {
  return (
    <StackSetting.Navigator initialRouteName="MyCoursesPage" screenOptions={{ headerShown: false }}>
      <StackSetting.Screen name="MyCoursesPage" component={MyCoursesPage} />
      <StackSetting.Screen name="MyCoursesPage2" component={MyCoursesPage2} />
      <StackSetting.Screen name="MyCoursesDetailsPage" component={MyCoursesDetailsPage} />
      <StackSetting.Screen name="Coursedetailscreen" component={Coursedetailscreen} />
    </StackSetting.Navigator>
  );
}

export default MyCoursesStackNavigator;

</code>```
```<code>import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import MyCoursesPage from "../pages/MyCourses/MyCoursesPage";
import MyCoursesPage2 from "../pages/MyCourses/MyCoursesPage2"
import MyCoursesDetailsPage from "../pages/MyCourses/MyCoursesDetailsPage";
import Coursedetailscreen from "../pages/MyCourses/Coursedetailscreen";

const StackSetting = createStackNavigator();

function MyCoursesStackNavigator() {
  return (
    <StackSetting.Navigator initialRouteName="MyCoursesPage" screenOptions={{ headerShown: false }}>
      <StackSetting.Screen name="MyCoursesPage" component={MyCoursesPage} />
      <StackSetting.Screen name="MyCoursesPage2" component={MyCoursesPage2} />
      <StackSetting.Screen name="MyCoursesDetailsPage" component={MyCoursesDetailsPage} />
      <StackSetting.Screen name="Coursedetailscreen" component={Coursedetailscreen} />
    </StackSetting.Navigator>
  );
}

export default MyCoursesStackNavigator;

</code>```

The only problem is that when I am using onpress in scope of return it is working but I want to use it on top because of the react native tab view code is there please help me

I am only expecting there is no other issue in this code but only onpress is not working outside of the return scope

Body:
I only want to navigate to my other screen "MycoursesPage2 from my page MycoursesPage
This is the actual code. it is giving an error on onpress function that "undefined is an object (evaluating navigation.navigate)"

import React, {useState} from "react";
import { View, StyleSheet, TouchableOpacity, Image, Dimensions, ScrollView, StatusBar, Text } from 'react-native';
import { SafeAreaView } from "react-native-safe-area-context";
import CustomHeader from "../../components/CustomHeader";
import { IMAGE } from "../../constants/Images";
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import * as Progress from 'react-native-progress';

const FirstRoute = ({navigation}) => (
  <ScrollView>
  <View style={[styles.scene, { backgroundColor: '#f7f7f7' }]} />

  </ScrollView>
);

function SecondRoute({ navigation }) {
  return (
  <ScrollView>
  <View style={[styles.scene, { backgroundColor: '#f7f7f7' }]} />
  <TouchableOpacity onPress={() => navigation.navigate("Register")}>

              <View
                style={{
                  borderWidth: 1,
                  borderColor: "#fff",
                  backgroundColor:'#fff',
                  borderRadius: 10,
                  padding: 15,
                  marginHorizontal:20,
                  marginVertical: 15,
                  display:'flex',
                  flexDirection:'row'
                }}
              >
                <Image
                  source={IMAGE.MYCOURSES3}
                  style={{ width: 60, height: 60 }}
                />
                <View>

                <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>3D Design Illustration</Text>
                <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>2hrs 25mins</Text>

              <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={1} width={200} />
              </View>

              </View>

   </TouchableOpacity>
  <TouchableOpacity>

    <View
      style={{
        borderWidth: 1,
        borderColor: "#fff",
        backgroundColor:'#fff',
        borderRadius: 10,
        padding: 15,
        marginHorizontal:20,
        display:'flex',
        flexDirection:'row'
      }}
    >
      <Image
        source={IMAGE.MYCOURSES4}
        style={{ width: 60, height: 60 }}
      />
      <View>

      <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>CRM Management</Text>
      <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>3hrs 20mins</Text>

    <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={0.88} width={200} />
    </View>

    </View>

  </TouchableOpacity>
  <TouchableOpacity>

    <View
      style={{
        borderWidth: 1,
        borderColor: "#fff",
        backgroundColor:'#fff',
        borderRadius: 10,
        padding: 15,
        marginHorizontal:20,
        marginVertical:15,
        display:'flex',
        flexDirection:'row'
      }}
    >
      <Image
        source={IMAGE.MYCOURSES5}
        style={{ width: 60, height: 60 }}
      />
      <View>

      <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>Flutter Mobile Apps</Text>
      <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>4hrs 50mins</Text>

    <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={0.95} width={200} />
    </View>

    </View>

  </TouchableOpacity>
  <TouchableOpacity>

    <View
      style={{
        borderWidth: 1,
        borderColor: "#fff",
        backgroundColor:'#fff',
        borderRadius: 10,
        padding: 15,
        marginHorizontal:20,
        display:'flex',
        flexDirection:'row'
      }}
    >
      <Image
        source={IMAGE.MYCOURSES6}
        style={{ width: 60, height: 60 }}
      />
      <View>

      <Text style={{fontSize:17, fontWeight:'bold', marginHorizontal:15}}>3D Icons Set Blender</Text>
      <Text style={{fontSize:14, color:'grey', marginHorizontal:15}}>2hrs 45mins</Text>

    <Progress.Bar style={{marginHorizontal:15, marginVertical:5}} progress={0.85} width={200} />
    </View>

    </View>

  </TouchableOpacity>

  </ScrollView>
  )
}

const initialLayout = { width: Dimensions.get('window').width };

function MyCoursesPage({ navigation }) {
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: 'first', title: 'Ongoing' },
    { key: 'second', title: 'Completed' },
  ]);

  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
  });

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor:'#f7f7f7' }}>

      <CustomHeader title="My Courses" isHome={true} navigation={navigation} />

      <View style={{
        flexDirection: "row",
        justifyContent: "flex-end",
        marginTop:-35
      }}>
         <TouchableOpacity >
      <Image source={IMAGE.MYCOURSES1} style={{width: 22, height:22}}/>
      </TouchableOpacity>
      <TouchableOpacity >
      <Image source={IMAGE.MYCOURSES2} style={{width: 22, height:22, marginHorizontal:15}}/>
      </TouchableOpacity>
      </View>

      <TabView
      navigationState={{ index, routes }}
      renderTabBar={props => (
        <TabBar
          {...props}
          renderLabel={({ route, color }) => (
            <Text style={{ color: '#335ef7', fontWeight:'bold', margin: 8 }}>
              {route.title}
            </Text>
          )}
          style={{backgroundColor: 'white'}}
        />
      )}
      renderScene={renderScene}
      onIndexChange={setIndex}
      initialLayout={initialLayout}
      style={styles.container}
    />

    </SafeAreaView>
  );
}

export default MyCoursesPage;

const styles = StyleSheet.create({
  container: {
    marginTop: StatusBar.currentHeight,
  },
  scene: {
    flex: 1,
  },
});

and my stack navigator code is below

import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import MyCoursesPage from "../pages/MyCourses/MyCoursesPage";
import MyCoursesPage2 from "../pages/MyCourses/MyCoursesPage2"
import MyCoursesDetailsPage from "../pages/MyCourses/MyCoursesDetailsPage";
import Coursedetailscreen from "../pages/MyCourses/Coursedetailscreen";

const StackSetting = createStackNavigator();

function MyCoursesStackNavigator() {
  return (
    <StackSetting.Navigator initialRouteName="MyCoursesPage" screenOptions={{ headerShown: false }}>
      <StackSetting.Screen name="MyCoursesPage" component={MyCoursesPage} />
      <StackSetting.Screen name="MyCoursesPage2" component={MyCoursesPage2} />
      <StackSetting.Screen name="MyCoursesDetailsPage" component={MyCoursesDetailsPage} />
      <StackSetting.Screen name="Coursedetailscreen" component={Coursedetailscreen} />
    </StackSetting.Navigator>
  );
}

export default MyCoursesStackNavigator;

import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import MyCoursesPage from "../pages/MyCourses/MyCoursesPage";
import MyCoursesPage2 from "../pages/MyCourses/MyCoursesPage2"
import MyCoursesDetailsPage from "../pages/MyCourses/MyCoursesDetailsPage";
import Coursedetailscreen from "../pages/MyCourses/Coursedetailscreen";

const StackSetting = createStackNavigator();

function MyCoursesStackNavigator() {
  return (
    <StackSetting.Navigator initialRouteName="MyCoursesPage" screenOptions={{ headerShown: false }}>
      <StackSetting.Screen name="MyCoursesPage" component={MyCoursesPage} />
      <StackSetting.Screen name="MyCoursesPage2" component={MyCoursesPage2} />
      <StackSetting.Screen name="MyCoursesDetailsPage" component={MyCoursesDetailsPage} />
      <StackSetting.Screen name="Coursedetailscreen" component={Coursedetailscreen} />
    </StackSetting.Navigator>
  );
}

export default MyCoursesStackNavigator;

The only problem is that when I am using onpress in scope of return it is working but I want to use it on top because of the react native tab view code is there please help me

I am only expecting there is no other issue in this code but only onpress is not working outside of the return scope


来源: stackexchange

问:
aspose cell exception this file format is not supported
I am using aspose cells to convert json file to excel file but getting an excpection saying that file format is not supported, Below is the code which i am using.Getting excepetion at the line Workbook workbook = new Workbook(".//Json_files//elastic_search.json");

```<code>public void FinBlock() throws Exception {

    String USERNAME = CONFIG.getProperty("Username");
    String Password = CONFIG.getProperty("password");
    String URI = CONFIG.getProperty("API");
    SessionFilter session = new SessionFilter();
    RestAssured.baseURI = URI;
    String Response = given().auth().preemptive().basic(USERNAME, Password).filter(session).when()
            .get(RestAssured.baseURI).then().extract().response().getCookie("RAY_SESSION_ID");

    Response resp1 = given().cookie("RAY_SESSION_ID", Response).filter(session).when()
            .get("URI")
            .then().log().all().extract().response();

    PrintWriter out1 = new PrintWriter(
            new FileWriter(".//Json_files//elastic_search.json", true), true);
    out1.write(resp1.asString());
    out1.close();

    LocalDateTime date = LocalDateTime.now();
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    String formattedDate = date.format(dateFormat);

    DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm");
    String formatedate = date.format(dateformat);

    Path dir = Paths.get(".//Output_Files//ES_Excelfiles-" + formattedDate);
    Files.createDirectories(dir);

    Workbook workbook = new Workbook(".//Json_files//elastic_search.json");
    // workbook.save(".//output-"+formatedate+".xlsx");
    // workbook.save(".//Excel_files//es_files//ES-"+stockname+"-"+formatedate+".xlsx");
    workbook.save(dir + "//ES-" + stockname + "-" + formatedate + ".xlsx");

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using aspose cells to convert json file to excel file but getting an excpection saying that file format is not supported, Below is the code which i am using.Getting excepetion at the line Workbook workbook = new Workbook(".//Json_files//elastic_search.json");

public void FinBlock() throws Exception {

    String USERNAME = CONFIG.getProperty("Username");
    String Password = CONFIG.getProperty("password");
    String URI = CONFIG.getProperty("API");
    SessionFilter session = new SessionFilter();
    RestAssured.baseURI = URI;
    String Response = given().auth().preemptive().basic(USERNAME, Password).filter(session).when()
            .get(RestAssured.baseURI).then().extract().response().getCookie("RAY_SESSION_ID");

    Response resp1 = given().cookie("RAY_SESSION_ID", Response).filter(session).when()
            .get("URI")
            .then().log().all().extract().response();

    PrintWriter out1 = new PrintWriter(
            new FileWriter(".//Json_files//elastic_search.json", true), true);
    out1.write(resp1.asString());
    out1.close();

    LocalDateTime date = LocalDateTime.now();
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    String formattedDate = date.format(dateFormat);

    DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm");
    String formatedate = date.format(dateformat);

    Path dir = Paths.get(".//Output_Files//ES_Excelfiles-" + formattedDate);
    Files.createDirectories(dir);

    Workbook workbook = new Workbook(".//Json_files//elastic_search.json");
    // workbook.save(".//output-"+formatedate+".xlsx");
    // workbook.save(".//Excel_files//es_files//ES-"+stockname+"-"+formatedate+".xlsx");
    workbook.save(dir + "//ES-" + stockname + "-" + formatedate + ".xlsx");

}


问:
RuntimeError: dispatcher functions can only use None for default argument values

`runfile('E:/sow/New folder/local.py', wdir='E:/sow/New folder')
Traceback (most recent call last):

File "E:\sow\New folder\local.py", line 5, in
import numpy as np

File "C:\Users\new\AppData\Roaming\Python\Python38\site-packages\numpy_init_.py", line 140, in
from . import core

File "C:\Users\new\AppData\Roaming\Python\Python38\site-packages\numpy\core_init_.py", line 82, in
from . import function_base

File "C:\Users\new\AppData\Roaming\Python\Python38\site-packages\numpy\core\function_base.py", line 24, in
def linspace(start, stop, num=None, endpoint=True, retstep=False, dtype=None,

File "C:\Users\new\AppData\Roaming\Python\Python38\site-packages\numpy\core\overrides.py", line 172, in decorator
verify_matching_signatures(implementation, dispatcher)

File "C:\Users\new\AppData\Roaming\Python\Python38\site-packages\numpy\core\overrides.py", line 106, in verify_matching_signatures
raise RuntimeError('dispatcher functions can only use None for '

RuntimeError: dispatcher functions can only use None for default argument values`

Snipshot of error in Anaconda Spyder

Error description=>RuntimeError: dispatcher functions can only use None for default argument values
in spyder console.

Encountered same error for all programs which I had executed in a virtual environment in spyder console


问:
Flow is not refreshed when Room database table record is updated
I'm updating the is_in_cart column in the Room Database for the ShoppingListItem when the add-to-shopping-cart Checkbox is clicked. I have a separate LazyColumn items section to list the items in the cart, but when the checkbox is clicked, it is not showing the list of items in the shopping cart. The Room database is not triggering a fresh retrieval of the Flow from the database when the item is updated. How can I fix this?

ShoppingListItem

```<code>@Parcelize
data class ShoppingListItem(
    val id: Long = 0L,
    val shoppingListId: Long = 0L,

    ...

    val isInCart: Boolean = false
): Parcelable
</code>```

ShoppingListItemEntity

```<code>@Entity(
    tableName = "shopping_list_items",
    foreignKeys = [ForeignKey(
        entity = ShoppingListEntity::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("shopping_list_id"),
        onUpdate = ForeignKey.CASCADE,
        onDelete = ForeignKey.CASCADE
    )]
)
data class ShoppingListItemEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    @ColumnInfo(name = "shopping_list_id")
    var shoppingListId: Long = 0L,

    ...

    @ColumnInfo(name = "is_in_cart")
    val isInCart: Boolean
)
</code>```

Dao

```<code>@Query("SELECT * FROM shopping_list_items WHERE shopping_list_id = :listId")
fun getAllShoppingListItems(listId: Long): PagingSource<Int, ShoppingListItemEntity>
</code>```

Repository

```<code>override fun getAllShoppingListItems(listId: Long): Flow<PagingData<ShoppingListItem>> {

    val pagingSourceFactory = { shoppingListItemDao.getAllShoppingListItems(listId) }

    return Pager(
        config = PagingConfig(
            pageSize = 10,
            enablePlaceholders = false
        ),
        pagingSourceFactory = pagingSourceFactory
    ).flow.map {
        it.map { shoppingListItemEntity ->
            shoppingListItemMapper.mapFromEntity(shoppingListItemEntity)
        }
    }
}
</code>```

Use case

```<code>class GetAllShoppingListItemsUseCase @Inject constructor(
    private val shoppingListItemsRepository: ShoppingListItemsRepository
) {
      operator fun invoke(listId: Long): Flow<PagingData<ShoppingListItem>> {
        return shoppingListItemsRepository.getAllShoppingListItems(listId)
    }
}
</code>```

ViewModel

```<code>suspend fun addItemToCart(item: ShoppingListItem, checked: Boolean) {
    val updatedItem = item.copy(isInCart = checked)
    updateShoppingListItemInDb(updatedItem)
}

private suspend fun updateShoppingListItemInDb(item: ShoppingListItem) {
    viewModelScope.launch {
        updateShoppingListItemUseCase(item)

        _listItemsLoadingState.value = ListItemsState.Success(_shoppingListItemsState.value)
    }
}
</code>```

Composable

```<code>val scope = rememberCoroutineScope()
successItems = allItemsState.allItems?.collectAsLazyPagingItems()

val itemsNotInCart = successItems!!.itemSnapshotList.filter {
    !it!!.isInCart
}

val itemsInCart = successItems!!.itemSnapshotList.filter {
    it!!.isInCart
}

LazyColumn(
    state = alphaLazyListState,
    modifier = Modifier
        .fillMaxSize(),
    contentPadding = PaddingValues(
        start = 0.dp,
        end = 0.dp,
        bottom = 165.dp
    ),
    verticalArrangement = Arrangement.spacedBy(3.dp),
) {
    itemsIndexed(
        items = itemsNotInCart,
        key = { index, item ->
            item.id
        }
    ) { index, item ->
        ShoppingListScreenItem(
            item = item,
            mainViewModel = shoppingListScreenViewModel,
            sharedViewModel = sharedViewModel,
            onNavigateToAddEditItemScreenFromItemStrip = { shoppingListItem ->
                onNavigateToAddEditItemScreenFromItemStrip(
                    shoppingListItem
                )
            },
        ) { isChecked ->
            scope.launch {
                shoppingListScreenViewModel.addItemToCart(
                    item,
                    isChecked
                )
            }
        }
        Divider()
    }

    if (itemsInCart.isNotEmpty()) {
        stickyHeader {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .background("#bcd8c1".hexToColor())
                    .padding(7.dp)
            ) {
                Text(text = "Shopping Cart")
            }
        }

        items(
            items = itemsInCart,
            key = { item ->
                item.id
            }
        ) { item ->
            ShoppingListScreenItem(
                item = item,
                mainViewModel = shoppingListScreenViewModel,
                sharedViewModel = sharedViewModel,
                onNavigateToAddEditItemScreenFromItemStrip = { shoppingListItem ->
                    onNavigateToAddEditItemScreenFromItemStrip(
                        shoppingListItem
                    )
                },
            ) { isChecked ->
                scope.launch {
                    shoppingListScreenViewModel.addItemToCart(
                        item,
                        isChecked
                    )
                }
            }
            Divider()
        }
    }
}
</code>```

Body:
I'm updating the is_in_cart column in the Room Database for the ShoppingListItem when the add-to-shopping-cart Checkbox is clicked. I have a separate LazyColumn items section to list the items in the cart, but when the checkbox is clicked, it is not showing the list of items in the shopping cart. The Room database is not triggering a fresh retrieval of the Flow from the database when the item is updated. How can I fix this?

ShoppingListItem

@Parcelize
data class ShoppingListItem(
    val id: Long = 0L,
    val shoppingListId: Long = 0L,

    ...

    val isInCart: Boolean = false
): Parcelable

ShoppingListItemEntity

@Entity(
    tableName = "shopping_list_items",
    foreignKeys = [ForeignKey(
        entity = ShoppingListEntity::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("shopping_list_id"),
        onUpdate = ForeignKey.CASCADE,
        onDelete = ForeignKey.CASCADE
    )]
)
data class ShoppingListItemEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0L,
    @ColumnInfo(name = "shopping_list_id")
    var shoppingListId: Long = 0L,

    ...

    @ColumnInfo(name = "is_in_cart")
    val isInCart: Boolean
)

Dao

@Query("SELECT * FROM shopping_list_items WHERE shopping_list_id = :listId")
fun getAllShoppingListItems(listId: Long): PagingSource<Int, ShoppingListItemEntity>

Repository

override fun getAllShoppingListItems(listId: Long): Flow<PagingData<ShoppingListItem>> {

    val pagingSourceFactory = { shoppingListItemDao.getAllShoppingListItems(listId) }

    return Pager(
        config = PagingConfig(
            pageSize = 10,
            enablePlaceholders = false
        ),
        pagingSourceFactory = pagingSourceFactory
    ).flow.map {
        it.map { shoppingListItemEntity ->
            shoppingListItemMapper.mapFromEntity(shoppingListItemEntity)
        }
    }
}

Use case

class GetAllShoppingListItemsUseCase @Inject constructor(
    private val shoppingListItemsRepository: ShoppingListItemsRepository
) {
      operator fun invoke(listId: Long): Flow<PagingData<ShoppingListItem>> {
        return shoppingListItemsRepository.getAllShoppingListItems(listId)
    }
}

ViewModel

suspend fun addItemToCart(item: ShoppingListItem, checked: Boolean) {
    val updatedItem = item.copy(isInCart = checked)
    updateShoppingListItemInDb(updatedItem)
}

private suspend fun updateShoppingListItemInDb(item: ShoppingListItem) {
    viewModelScope.launch {
        updateShoppingListItemUseCase(item)

        _listItemsLoadingState.value = ListItemsState.Success(_shoppingListItemsState.value)
    }
}

Composable

val scope = rememberCoroutineScope()
successItems = allItemsState.allItems?.collectAsLazyPagingItems()

val itemsNotInCart = successItems!!.itemSnapshotList.filter {
    !it!!.isInCart
}

val itemsInCart = successItems!!.itemSnapshotList.filter {
    it!!.isInCart
}

LazyColumn(
    state = alphaLazyListState,
    modifier = Modifier
        .fillMaxSize(),
    contentPadding = PaddingValues(
        start = 0.dp,
        end = 0.dp,
        bottom = 165.dp
    ),
    verticalArrangement = Arrangement.spacedBy(3.dp),
) {
    itemsIndexed(
        items = itemsNotInCart,
        key = { index, item ->
            item.id
        }
    ) { index, item ->
        ShoppingListScreenItem(
            item = item,
            mainViewModel = shoppingListScreenViewModel,
            sharedViewModel = sharedViewModel,
            onNavigateToAddEditItemScreenFromItemStrip = { shoppingListItem ->
                onNavigateToAddEditItemScreenFromItemStrip(
                    shoppingListItem
                )
            },
        ) { isChecked ->
            scope.launch {
                shoppingListScreenViewModel.addItemToCart(
                    item,
                    isChecked
                )
            }
        }
        Divider()
    }

    if (itemsInCart.isNotEmpty()) {
        stickyHeader {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .background("#bcd8c1".hexToColor())
                    .padding(7.dp)
            ) {
                Text(text = "Shopping Cart")
            }
        }

        items(
            items = itemsInCart,
            key = { item ->
                item.id
            }
        ) { item ->
            ShoppingListScreenItem(
                item = item,
                mainViewModel = shoppingListScreenViewModel,
                sharedViewModel = sharedViewModel,
                onNavigateToAddEditItemScreenFromItemStrip = { shoppingListItem ->
                    onNavigateToAddEditItemScreenFromItemStrip(
                        shoppingListItem
                    )
                },
            ) { isChecked ->
                scope.launch {
                    shoppingListScreenViewModel.addItemToCart(
                        item,
                        isChecked
                    )
                }
            }
            Divider()
        }
    }
}


问:
Are avatars (like gravatars) findable from a phone number?
I know that I can use gravatar.org's simple API to find somebody's "Gravatar" if they have signed up using an email address.

Is there a similar service which attaches "avatars" (or profile pictures) to phone numbers?

I used gravatar.org API on an email address, and retrieved the person's "gravatar".
I would like to know if there is anything similar which would work on a phone number without an email address.


问:
How to embed using html or iframe the GMB updates/local posts/list into a wordpress website?
I know this data can also be accessed through api but no idea how to link the api to wordpress website to display it? Searched far and wide for a plugin but no one had developed one to fetch posts/updates made on GMB to be displayed as a feed on wordpress website.

Can do this through the Google My Business API;

```<code>https://developers.google.com/my-business/content/overview?
</code>```

The method to fetch Google My Business posts is accounts.locations.localPosts.list

But beyond this no idea how to actually get the end result anyone can help achieve this?

Tried all different plugins but none of them seem to have this feature but have the opposite which is to post updates from wordpress to GMB but what I need is simply to display posts/updates on GMB in wordpress website

Body:
I know this data can also be accessed through api but no idea how to link the api to wordpress website to display it? Searched far and wide for a plugin but no one had developed one to fetch posts/updates made on GMB to be displayed as a feed on wordpress website.

Can do this through the Google My Business API;

https://developers.google.com/my-business/content/overview?

The method to fetch Google My Business posts is accounts.locations.localPosts.list

But beyond this no idea how to actually get the end result anyone can help achieve this?

Tried all different plugins but none of them seem to have this feature but have the opposite which is to post updates from wordpress to GMB but what I need is simply to display posts/updates on GMB in wordpress website


问:
Trying to create a raid command for a discord bot in python
I've been trying to do a delayed timeout for 30 seconds, and it works but there's a huge flaw.

After the 30 seconds, it waits untill someone runs the .joinraid command AGAIN, even if its been an hour.

```<code>## Enter a raid
@client.command()
@commands.cooldown(1, 60, commands.BucketType.user)
async def startraid(ctx, name: str):
    joined_users = []
    players = []

    try:
        data = open_database()
        all_cards = open_cards()

        for card in all_cards["cards"]:
            if name == card["name"]:
                boss = {
                    "name" : card["name"],
                    "health" : card["stats"]["health"] * 10,
                    "attack" : card["stats"]["attack"] * 10,
                    "defense" : card["stats"]["defense"] * 2
                }

        def check(message):
            return message.content.startswith('.joinraid') and message.channel == ctx.channel
        await ctx.send("Type '.joinraid' to join the raid! The sign-up period will last 25 seconds.")
        start_time = time.time()
        while time.time() - start_time < 25:
            message = await client.wait_for('message', check=check)
            joined_users.append(message.author.id)
            await ctx.send(f"{message.author.name} has joined the raid!")
            await asyncio.sleep(0.1)

        await ctx.send("The sign-up period is over. Nobody can join the raid anymore.")

        for user_id in joined_users:
            user_team = data[user_id]["team"]
            if user_team:
                players.append(user_team[0])

    except:
        print(f"{ctx.author.name} has caused an error with the .fight command.")
        print(traceback.format_exc())
        await ctx.send(
            f"It seems like something went wrong, please contact <@824493336152113162>"
        )
</code>```

How can i fix this issue without using threading?

Body:
I've been trying to do a delayed timeout for 30 seconds, and it works but there's a huge flaw.

After the 30 seconds, it waits untill someone runs the .joinraid command AGAIN, even if its been an hour.

## Enter a raid
@client.command()
@commands.cooldown(1, 60, commands.BucketType.user)
async def startraid(ctx, name: str):
    joined_users = []
    players = []

    try:
        data = open_database()
        all_cards = open_cards()

        for card in all_cards["cards"]:
            if name == card["name"]:
                boss = {
                    "name" : card["name"],
                    "health" : card["stats"]["health"] * 10,
                    "attack" : card["stats"]["attack"] * 10,
                    "defense" : card["stats"]["defense"] * 2
                }

        def check(message):
            return message.content.startswith('.joinraid') and message.channel == ctx.channel
        await ctx.send("Type '.joinraid' to join the raid! The sign-up period will last 25 seconds.")
        start_time = time.time()
        while time.time() - start_time < 25:
            message = await client.wait_for('message', check=check)
            joined_users.append(message.author.id)
            await ctx.send(f"{message.author.name} has joined the raid!")
            await asyncio.sleep(0.1)

        await ctx.send("The sign-up period is over. Nobody can join the raid anymore.")

        for user_id in joined_users:
            user_team = data[user_id]["team"]
            if user_team:
                players.append(user_team[0])

    except:
        print(f"{ctx.author.name} has caused an error with the .fight command.")
        print(traceback.format_exc())
        await ctx.send(
            f"It seems like something went wrong, please contact <@824493336152113162>"
        )

How can i fix this issue without using threading?


问:
Apache Beam - Convert empty Dataframe back to PCollection
I'm experimenting with Apache Beam, and struggling with correclty handling dataframe to pcollection conversion. I've tested implementation of left anti-join with following logics:

```<code>def left_anti_join(
    left: DeferredDataFrame,
    right: DeferredDataFrame,
    left_index: str,
    right_index: str, ) -> DeferredDataFrame:

    inner_joined_df = left.merge(
        right.set_index(right_index),
        right_index=True,
        left_on=left_index,
        how="left",
        indicator=True,
    )
    return inner_joined_df[inner_joined_df._merge == "left_only"].drop("_merge", axis=1)
</code>```

After executing this function i'm turning its output into p_collection with:

```<code>data = left_anti_join(df1,df2,"id", "id")
to_pcollection(data)
</code>```

Everything works fine, until Deffered DataFrame returned by my "left_anti_join" function is empty.

If that happens i keep getting following error:

```<code>/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/opcounters.py:226: RuntimeWarning: invalid value encountered in long_scalars
  mean_element_size = self.producer_batch_converter.estimate_byte_size(
Traceback (most recent call last):
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1417, in process
    return self.do_fn_invoker.invoke_process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 623, in invoke_process
    self.output_handler.handle_process_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1600, in handle_process_outputs
    self._write_batch_to_tag(tag, windowed_batch, watermark_estimator)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1704, in _write_batch_to_tag
    self.main_receivers.receive_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 365, in receive_batch
    self.update_counters_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 206, in update_counters_batch
    self.opcounter.update_from_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/opcounters.py", line 228, in update_from_batch
    self.mean_byte_counter.update_n(mean_element_size, batch_length)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/utils/counters.py", line 222, in update_n
    self._fast_add_input_n(value, n)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/transforms/cy_combiners.py", line 213, in add_input_n
    element = int(element)
ValueError: cannot convert float NaN to integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/mydir/beam_jobs/test_job.py", line 163, in <module>
    with beam.Pipeline(options=beam_options) as p:
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/pipeline.py", line 597, in __exit__
    self.result = self.run()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/pipeline.py", line 574, in run
    return self.runner.run_pipeline(self, self._options)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/direct/direct_runner.py", line 131, in run_pipeline
    return runner.run_pipeline(pipeline, options)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 199, in run_pipeline
    self._latest_run_result = self.run_via_runner_api(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 212, in run_via_runner_api
    return self.run_stages(stage_context, stages)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 442, in run_stages
    bundle_results = self._execute_bundle(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 770, in _execute_bundle
    self._run_bundle(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 999, in _run_bundle
    result, splits = bundle_manager.process_bundle(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 1309, in process_bundle
    result_future = self._worker_handler.control_conn.push(process_bundle_req)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/worker_handlers.py", line 379, in push
    response = self.worker.do_instruction(request)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/sdk_worker.py", line 596, in do_instruction
    return getattr(self, request_type)(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/sdk_worker.py", line 634, in process_bundle
    bundle_processor.process_bundle(instruction_id))
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/bundle_processor.py", line 1009, in process_bundle
    op.finish()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 943, in finish
    self.dofn_runner.finish()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1479, in finish
    self._invoke_bundle_method(self.do_fn_invoker.invoke_finish_bundle)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1460, in _invoke_bundle_method
    self._reraise_augmented(exn)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented
    raise exn
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1458, in _invoke_bundle_method
    bundle_method()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 566, in invoke_finish_bundle
    self.output_handler.finish_bundle_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1745, in finish_bundle_outputs
    self.main_receivers.receive(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive
    self.consumer.process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 908, in process
    delayed_applications = self.dofn_runner.process(o)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1419, in process
    self._reraise_augmented(exn)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented
    raise exn
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1417, in process
    return self.do_fn_invoker.invoke_process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 837, in invoke_process
    self._invoke_process_per_window(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 981, in _invoke_process_per_window
    self.output_handler.handle_process_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1581, in handle_process_outputs
    self._write_value_to_tag(tag, windowed_value, watermark_estimator)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1696, in _write_value_to_tag
    self.tagged_receivers[tag].receive(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive
    self.consumer.process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 908, in process
    delayed_applications = self.dofn_runner.process(o)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1419, in process
    self._reraise_augmented(exn)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1507, in _reraise_augmented
    raise new_exn.with_traceback(tb)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1417, in process
    return self.do_fn_invoker.invoke_process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 623, in invoke_process
    self.output_handler.handle_process_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1600, in handle_process_outputs
    self._write_batch_to_tag(tag, windowed_batch, watermark_estimator)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1704, in _write_batch_to_tag
    self.main_receivers.receive_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 365, in receive_batch
    self.update_counters_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 206, in update_counters_batch
    self.opcounter.update_from_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/opcounters.py", line 228, in update_from_batch
    self.mean_byte_counter.update_n(mean_element_size, batch_length)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/utils/counters.py", line 222, in update_n
    self._fast_add_input_n(value, n)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/transforms/cy_combiners.py", line 213, in add_input_n
    element = int(element)
ValueError: cannot convert float NaN to integer [while running 'Unbatch 'drop_DataFrame_6039969152'']
</code>```

What's the correct way of handling such a cases of empty dataframes? I've been trying to count number of elements before transforming it to PCollection but it feels inefficient

Body:
I'm experimenting with Apache Beam, and struggling with correclty handling dataframe to pcollection conversion. I've tested implementation of left anti-join with following logics:

def left_anti_join(
    left: DeferredDataFrame,
    right: DeferredDataFrame,
    left_index: str,
    right_index: str, ) -> DeferredDataFrame:

    inner_joined_df = left.merge(
        right.set_index(right_index),
        right_index=True,
        left_on=left_index,
        how="left",
        indicator=True,
    )
    return inner_joined_df[inner_joined_df._merge == "left_only"].drop("_merge", axis=1)

After executing this function i'm turning its output into p_collection with:

data = left_anti_join(df1,df2,"id", "id")
to_pcollection(data)

Everything works fine, until Deffered DataFrame returned by my "left_anti_join" function is empty.

If that happens i keep getting following error:

/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/opcounters.py:226: RuntimeWarning: invalid value encountered in long_scalars
  mean_element_size = self.producer_batch_converter.estimate_byte_size(
Traceback (most recent call last):
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1417, in process
    return self.do_fn_invoker.invoke_process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 623, in invoke_process
    self.output_handler.handle_process_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1600, in handle_process_outputs
    self._write_batch_to_tag(tag, windowed_batch, watermark_estimator)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1704, in _write_batch_to_tag
    self.main_receivers.receive_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 365, in receive_batch
    self.update_counters_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 206, in update_counters_batch
    self.opcounter.update_from_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/opcounters.py", line 228, in update_from_batch
    self.mean_byte_counter.update_n(mean_element_size, batch_length)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/utils/counters.py", line 222, in update_n
    self._fast_add_input_n(value, n)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/transforms/cy_combiners.py", line 213, in add_input_n
    element = int(element)
ValueError: cannot convert float NaN to integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/mydir/beam_jobs/test_job.py", line 163, in <module>
    with beam.Pipeline(options=beam_options) as p:
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/pipeline.py", line 597, in __exit__
    self.result = self.run()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/pipeline.py", line 574, in run
    return self.runner.run_pipeline(self, self._options)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/direct/direct_runner.py", line 131, in run_pipeline
    return runner.run_pipeline(pipeline, options)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 199, in run_pipeline
    self._latest_run_result = self.run_via_runner_api(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 212, in run_via_runner_api
    return self.run_stages(stage_context, stages)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 442, in run_stages
    bundle_results = self._execute_bundle(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 770, in _execute_bundle
    self._run_bundle(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 999, in _run_bundle
    result, splits = bundle_manager.process_bundle(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/fn_runner.py", line 1309, in process_bundle
    result_future = self._worker_handler.control_conn.push(process_bundle_req)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/portability/fn_api_runner/worker_handlers.py", line 379, in push
    response = self.worker.do_instruction(request)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/sdk_worker.py", line 596, in do_instruction
    return getattr(self, request_type)(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/sdk_worker.py", line 634, in process_bundle
    bundle_processor.process_bundle(instruction_id))
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/bundle_processor.py", line 1009, in process_bundle
    op.finish()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 943, in finish
    self.dofn_runner.finish()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1479, in finish
    self._invoke_bundle_method(self.do_fn_invoker.invoke_finish_bundle)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1460, in _invoke_bundle_method
    self._reraise_augmented(exn)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented
    raise exn
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1458, in _invoke_bundle_method
    bundle_method()
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 566, in invoke_finish_bundle
    self.output_handler.finish_bundle_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1745, in finish_bundle_outputs
    self.main_receivers.receive(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive
    self.consumer.process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 908, in process
    delayed_applications = self.dofn_runner.process(o)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1419, in process
    self._reraise_augmented(exn)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1491, in _reraise_augmented
    raise exn
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1417, in process
    return self.do_fn_invoker.invoke_process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 837, in invoke_process
    self._invoke_process_per_window(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 981, in _invoke_process_per_window
    self.output_handler.handle_process_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1581, in handle_process_outputs
    self._write_value_to_tag(tag, windowed_value, watermark_estimator)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1696, in _write_value_to_tag
    self.tagged_receivers[tag].receive(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 240, in receive
    self.consumer.process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 908, in process
    delayed_applications = self.dofn_runner.process(o)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1419, in process
    self._reraise_augmented(exn)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1507, in _reraise_augmented
    raise new_exn.with_traceback(tb)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1417, in process
    return self.do_fn_invoker.invoke_process(windowed_value)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 623, in invoke_process
    self.output_handler.handle_process_outputs(
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1600, in handle_process_outputs
    self._write_batch_to_tag(tag, windowed_batch, watermark_estimator)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/common.py", line 1704, in _write_batch_to_tag
    self.main_receivers.receive_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 365, in receive_batch
    self.update_counters_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/operations.py", line 206, in update_counters_batch
    self.opcounter.update_from_batch(windowed_batch)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/runners/worker/opcounters.py", line 228, in update_from_batch
    self.mean_byte_counter.update_n(mean_element_size, batch_length)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/utils/counters.py", line 222, in update_n
    self._fast_add_input_n(value, n)
  File "/mydir/.venv/lib/python3.10/site-packages/apache_beam/transforms/cy_combiners.py", line 213, in add_input_n
    element = int(element)
ValueError: cannot convert float NaN to integer [while running 'Unbatch 'drop_DataFrame_6039969152'']

What's the correct way of handling such a cases of empty dataframes? I've been trying to count number of elements before transforming it to PCollection but it feels inefficient


问:
The flutter tool cannot access the file or directory
This problem occurred in only one project, knowing that there are 3 different projects in the same folder, all of them work without a problem
As for this project, I have a problem: Exception: The flutter tool cannot access the file or directory.
Please ensure that the SDK and/or project is installed in a location that has read/write permissions for the current user.
I run flutter doctor and everything is fine

how I can solve this problem?


问:
How can I solve WordPress Memory Exhausted Error
I see an error in my WordPress memory. Can you please help me, How can I fix this memory issue? The error displays a message like the one below:

```<code>Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2348617 bytes) in /home/username/public_html/site1/wp-includes/plugin.php on line xxx
</code>```

How can I fix this memory issue ?

Thank You

Body:
I see an error in my WordPress memory. Can you please help me, How can I fix this memory issue? The error displays a message like the one below:

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2348617 bytes) in /home/username/public_html/site1/wp-includes/plugin.php on line xxx

How can I fix this memory issue ?

Thank You


问:
update Workflow Status column for SharePoint list item ( on Prem )
We have a list on which a workflow  named “Approve Items” has already run. For some of the items in this list, the column “Approve items” is blank though the WF has run. I can even see the workflow history and the WF is there along with rest of details.  Its just that link which takes the user from List View to the Workflow history which is blank.
I want to somehow updated this column ( Approve items) on these selected items with the link . Already tried this PS script but it does not seem to make any change to the column.

Any idea on how to achieve this?

Also, it seem the column added by WF is of the type WorkFlowStatus and not really a hyperlink column.

```<code>---------------------------------PS-----------------------------
Add-PSSnapin Microsoft.SharePoint.Powershell
$webUrl = https://WEBURL
$nintexWFlist = "NintexWorkflowHistory"
$cntrListName = "Main List on Which WF is Running"
$web = get-spweb $webUrl
$cntrList = $web.Lists[$cntrListName]
$ListItem = $cntrList.Items | Where {$_["ID"] -eq 26473}
$ListItem > d:\scripts\26473.txt
$ofldurl= new-object Microsoft.SharePoint.SPFieldUrlValue($ListItem["Approve Items"])

#$ofldurl.URL = "WEB-URL/_layouts/15/NintexWorkflow/WorkflowLog.aspx?ListId=ef7f675a-cff2-495e-a260-b7e651b7b5ba&ItemId=20679&WorkflowId=308d9bad-108e-4acd-94a2-ea3e497a239f&InstanceId=31de7c30-ee4f-41fc-88f4-0a040fedb35f"

#$ofldurl.Description = "Completed"

$ListItem.update()
</code>```

Body:
We have a list on which a workflow  named “Approve Items” has already run. For some of the items in this list, the column “Approve items” is blank though the WF has run. I can even see the workflow history and the WF is there along with rest of details.  Its just that link which takes the user from List View to the Workflow history which is blank.
I want to somehow updated this column ( Approve items) on these selected items with the link . Already tried this PS script but it does not seem to make any change to the column.

Any idea on how to achieve this?

Also, it seem the column added by WF is of the type WorkFlowStatus and not really a hyperlink column.

---------------------------------PS-----------------------------
Add-PSSnapin Microsoft.SharePoint.Powershell
$webUrl = https://WEBURL
$nintexWFlist = "NintexWorkflowHistory"
$cntrListName = "Main List on Which WF is Running"
$web = get-spweb $webUrl
$cntrList = $web.Lists[$cntrListName]
$ListItem = $cntrList.Items | Where {$_["ID"] -eq 26473}
$ListItem > d:\scripts\26473.txt
$ofldurl= new-object Microsoft.SharePoint.SPFieldUrlValue($ListItem["Approve Items"])

#$ofldurl.URL = "WEB-URL/_layouts/15/NintexWorkflow/WorkflowLog.aspx?ListId=ef7f675a-cff2-495e-a260-b7e651b7b5ba&ItemId=20679&WorkflowId=308d9bad-108e-4acd-94a2-ea3e497a239f&InstanceId=31de7c30-ee4f-41fc-88f4-0a040fedb35f"

#$ofldurl.Description = "Completed"

$ListItem.update()


问:
share a source where there is detailed explanation on how to use vueJS web-component in angular App
I've searched on various sources for this, nothing is providing the detailed info in it. please share me one. I would appreciate if its a detailed video link.

I've no idea how to do it.


问:
How to prevent django test runner from flushing db after each test?
I'm using pytest-django plugin for running tests, I need prevent the database from being flushed after each test, which is the default behavior when the tests are defined as below. Note: I populate the User table before running the tests, that's why the below works.

```<code>class TestViews:
    @staticmethod
    def test1(django_user_model):
        assert django_user_model.objects.count() > 0

    @staticmethod
    def test2(django_user_model):
        assert django_user_model.objects.count() > 0
</code>```

result:

```<code>============================= test session starts ==============================
collecting ... collected 2 items

test_live_server.py::TestViews::test1
test_live_server.py::TestViews::test2

============================== 2 passed in 7.86s ===============================

Process finished with exit code 0
</code>```

However, when live_server fixture is included:

```<code>class TestViews:
    @staticmethod
    def test1(django_user_model, live_server):
        assert django_user_model.objects.count() > 0

    @staticmethod
    def test2(django_user_model, live_server):
        assert django_user_model.objects.count() > 0
</code>```

all model tables are flushed after each test.

```<code>============================= test session starts ==============================
collecting ... collected 2 items

test_live_server.py::TestViews::test1
test_live_server.py::TestViews::test2

PASSED                             [ 50%]  # records ok
FAILED                             [100%]  # records dropped
tests/test_live_server.py:5 (TestViews.test2)
0 != 0

Expected :0
Actual   :0
<Click to see difference>

django_user_model = <class 'django.contrib.auth.models.User'>
live_server = <LiveServer listening at http://localhost:61926>

    @staticmethod
    def test2(django_user_model, live_server):
>       assert django_user_model.objects.count() > 0
E       AssertionError: assert 0 > 0
E        +  where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>>()
E        +    where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>> = <django.contrib.auth.models.UserManager object at 0x10d83fc90>.count
E        +      where <django.contrib.auth.models.UserManager object at 0x10d83fc90> = <class 'django.contrib.auth.models.User'>.objects

test_live_server.py:8: AssertionError

========================= 1 failed, 1 passed in 7.63s ==========================
</code>```

By digging further, I found that call_command('flush', ...) is called after each test, which doesn't happen when live_server is not present in the function parameters.

So I tried setting -reuse-db or adding it to pytest.ini, when I check using django_db_keepdb, it evaluates to True when the flag is specified however, the database is flushed anyway. Also @pytest.mark.django_db(transaction=true) is not working.

Body:
I'm using pytest-django plugin for running tests, I need prevent the database from being flushed after each test, which is the default behavior when the tests are defined as below. Note: I populate the User table before running the tests, that's why the below works.

class TestViews:
    @staticmethod
    def test1(django_user_model):
        assert django_user_model.objects.count() > 0

    @staticmethod
    def test2(django_user_model):
        assert django_user_model.objects.count() > 0

result:

============================= test session starts ==============================
collecting ... collected 2 items

test_live_server.py::TestViews::test1
test_live_server.py::TestViews::test2

============================== 2 passed in 7.86s ===============================

Process finished with exit code 0

However, when live_server fixture is included:

class TestViews:
    @staticmethod
    def test1(django_user_model, live_server):
        assert django_user_model.objects.count() > 0

    @staticmethod
    def test2(django_user_model, live_server):
        assert django_user_model.objects.count() > 0

all model tables are flushed after each test.

============================= test session starts ==============================
collecting ... collected 2 items

test_live_server.py::TestViews::test1
test_live_server.py::TestViews::test2

PASSED                             [ 50%]  # records ok
FAILED                             [100%]  # records dropped
tests/test_live_server.py:5 (TestViews.test2)
0 != 0

Expected :0
Actual   :0
<Click to see difference>

django_user_model = <class 'django.contrib.auth.models.User'>
live_server = <LiveServer listening at http://localhost:61926>

    @staticmethod
    def test2(django_user_model, live_server):
>       assert django_user_model.objects.count() > 0
E       AssertionError: assert 0 > 0
E        +  where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>>()
E        +    where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>> = <django.contrib.auth.models.UserManager object at 0x10d83fc90>.count
E        +      where <django.contrib.auth.models.UserManager object at 0x10d83fc90> = <class 'django.contrib.auth.models.User'>.objects

test_live_server.py:8: AssertionError

========================= 1 failed, 1 passed in 7.63s ==========================

By digging further, I found that call_command('flush', ...) is called after each test, which doesn't happen when live_server is not present in the function parameters.

So I tried setting -reuse-db or adding it to pytest.ini, when I check using django_db_keepdb, it evaluates to True when the flag is specified however, the database is flushed anyway. Also @pytest.mark.django_db(transaction=true) is not working.


问:
How can I create a dynamic path for my cli?
I have a problem with my path! I need a way to make my path dynamic. I have programmed a cli that works on my system but not on others, because the paths keep changing. I want to make it crossplatform capable. What am I doing wrong ?

Thank you at all!

GitHub Repo: https://github.com/TimothieMT/sweetStack

```<code>function absPath() {

    let result = ''

    const winPath1 = `${path.parse(process.cwd()).root}/Users/${process.env.USERNAME}/AppData/Roaming/npm/node_modules/${name}/`
    const winPath2 = `${path.parse(process.cwd()).root}/Program Files/nodejs/node_modules/${name}/`

    const linuxPath1 = `${path.parse(process.cwd()).root}/lib/node_modules/${name}/`
    const linuxPath2 = `${path.parse(process.cwd()).root}/home/${process.env.USERNAME}/.nvm/versions/node/${process.version}/lib/node_modules/${name}/`

    const macPath1 = `${path.parse(process.cwd()).root}/usr/local/lib/node_modules/${name}/`

    switch (process.platform) {
        case 'win32':
            if (fs.existsSync(winPath1)) {
                result = winPath1
            } else {
                result = winPath2
            }
            break;
        case 'linux':
            if (fs.existsSync(linuxPath1)) {
                result = linuxPath1
            } else {
                result = linuxPath2
            }
            break
        case 'darwin':
            return macPath1
        default: {
            console.log(chalk.red('your platform is not supported'))
        }
    }

    return result
}
</code>```

I install my cli globally, and therefore I need to load my data. I want to load also from the global node_modules folder.

Body:
I have a problem with my path! I need a way to make my path dynamic. I have programmed a cli that works on my system but not on others, because the paths keep changing. I want to make it crossplatform capable. What am I doing wrong ?

Thank you at all!

GitHub Repo: https://github.com/TimothieMT/sweetStack

function absPath() {

    let result = ''

    const winPath1 = `${path.parse(process.cwd()).root}/Users/${process.env.USERNAME}/AppData/Roaming/npm/node_modules/${name}/`
    const winPath2 = `${path.parse(process.cwd()).root}/Program Files/nodejs/node_modules/${name}/`

    const linuxPath1 = `${path.parse(process.cwd()).root}/lib/node_modules/${name}/`
    const linuxPath2 = `${path.parse(process.cwd()).root}/home/${process.env.USERNAME}/.nvm/versions/node/${process.version}/lib/node_modules/${name}/`

    const macPath1 = `${path.parse(process.cwd()).root}/usr/local/lib/node_modules/${name}/`

    switch (process.platform) {
        case 'win32':
            if (fs.existsSync(winPath1)) {
                result = winPath1
            } else {
                result = winPath2
            }
            break;
        case 'linux':
            if (fs.existsSync(linuxPath1)) {
                result = linuxPath1
            } else {
                result = linuxPath2
            }
            break
        case 'darwin':
            return macPath1
        default: {
            console.log(chalk.red('your platform is not supported'))
        }
    }

    return result
}

I install my cli globally, and therefore I need to load my data. I want to load also from the global node_modules folder.


问:
Documentation error for Sort.Orientation?
I'm writing some code in VBScript to sort a table in an excel file. My process in this case is to first record a macro doing the sorting manually, and then translate that VBA into VBScript.

The specific part of the code I was working on was

```<code>With sheet.ListObjects("Table1").Sort
    .SortFields.Clear
    .SortFields.Add sheet.Range("Table1[Subset]")
    .SortFields.Add sheet.Range("Table1[Domain]")
    .SortFields.Add sheet.Range("Table1[Entity]")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom '<--- this value was generated by the macro recording
    .SortMethod = xlPinYin
    .Apply
End With
</code>```

Because VBScript doesn't know the excel VBA enumerations, I have to declare them myself.

So I went to the Microsoft documentation about the Sort.Orientation property where it says the type of this property is the enumeration XlSortOrientation

This enumeration contains two values:

Specifies the sort orientation.

Name
Value
Description

xlSortColumns
1
Sorts by column.

xlSortRows
2
Sorts by row. This is the default value.

To my surprise there is xlTopToBottom value present in that enumeration.
Furthermore not only the macro recorder uses xlTopToBottom, but so does the example code in the documentation for the Sort object

The value xlTopToBottom can be found in the Constants enum

So my question is:

Why is Microsoft using the value xlTopToBottom in both recorded macro's as the API documentation for the Sort.Orientation while the only valid values are xlSortColumns or xlSortRows?

Body:
I'm writing some code in VBScript to sort a table in an excel file. My process in this case is to first record a macro doing the sorting manually, and then translate that VBA into VBScript.

The specific part of the code I was working on was

With sheet.ListObjects("Table1").Sort
    .SortFields.Clear
    .SortFields.Add sheet.Range("Table1[Subset]")
    .SortFields.Add sheet.Range("Table1[Domain]")
    .SortFields.Add sheet.Range("Table1[Entity]")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom '<--- this value was generated by the macro recording
    .SortMethod = xlPinYin
    .Apply
End With

Because VBScript doesn't know the excel VBA enumerations, I have to declare them myself.

So I went to the Microsoft documentation about the Sort.Orientation property where it says the type of this property is the enumeration XlSortOrientation

This enumeration contains two values:

Specifies the sort orientation.

Name
Value
Description

xlSortColumns
1
Sorts by column.

xlSortRows
2
Sorts by row. This is the default value.

To my surprise there is xlTopToBottom value present in that enumeration.
Furthermore not only the macro recorder uses xlTopToBottom, but so does the example code in the documentation for the Sort object

The value xlTopToBottom can be found in the Constants enum

So my question is:

Why is Microsoft using the value xlTopToBottom in both recorded macro's as the API documentation for the Sort.Orientation while the only valid values are xlSortColumns or xlSortRows?


问:
Use zsh instead of bash in Sagemaker Studio
I have created an image that uses zsh as entrypoint and attached it to my Sagemaker Studio domain (I can use zsh just fine if I test the image locally using docker run), but when opening a terminal in the Studio with this custom image, I see it falls back to bash.

Is there a way to actually have the Studio terminal use the image I've provided?


问:
How to Automate MS teams using cypress
```<code>describe('Two Domain urls in different Test case', function () {
  it('navigates', () => {
    cy.visit('https://teams.microsoft.com')
  })
})
</code>```

tried using the above code, still not redirecting to login screen

It should redirect to login screen

Title: How to Automate MS teams using cypress

Body:
describe('Two Domain urls in different Test case', function () {
  it('navigates', () => {
    cy.visit('https://teams.microsoft.com')
  })
})

tried using the above code, still not redirecting to login screen

It should redirect to login screen


问:
converting base64 response getting from Api to excel file in java
I want to read base64 response coming by hitting a rest Api. next decoding the base64 response and converting into excel file. How can I do this using rest template.

I am hitting an Api through rest Template exchange method. now need to store that base64 response and converting it.


问:
jar-archive corrupted after download
I have set up a simple front- & backend project for browsing & downloading files.

My backend server is written in java and the frontend is an angular application.

The backend has a path to a directory which it exposes to the frontend. The use can then use the frontend to navigate through the directories which are exposed by my backend.

Now I have set up a simple file download, which works fine without any problems EXCEPT when I try to download a jar-archive from the backend.
When I try to download a .jar file, the downloaded file ends up being way larger than expected. For example: I want to download a 18mb .jar file and it ends up downloading a 30mb .jar file instead.

I'm pretty much at the end of my wits when it comes to this problem, as I'm still new to the Frontend & web environment, please keep that in mind. Thank you.

What makes this Problem even more confusing for me is that my response-header shows the correct Content length and the correct amount of transferred bytes, matching my expected file-size (see attached images).
I also tried to apply the "application/java-archive" MediaType to both my Request and Response headers but this didn't fix the problem.

I hope i provided most of the Information needed to fix this, but just in case, here is the relevant code:

Backend:
`

```<code>/** Snippet by @fateddy - https://stackoverflow.com/a/35683261
 *
 * @param path the path to the file as a String
 * @return a resource representing the file to download
 */
@GetMapping("/browsable/download")
public  ResponseEntity<Resource> getFile(@RequestParam (required = true) String path) {
   String pathToFile = ROOT_PATH + File.separator + path;
   Path pathTMP = Paths.get(pathToFile); // Temporary Path-Object
   File file = new File(pathToFile);
   HttpHeaders headers = new HttpHeaders();
   MediaType mediatype = MediaType.APPLICATION_OCTET_STREAM;

   if (resolveFileExtension(file).equals(".jar")){ // custom mediaType for .jar files
      mediatype = MediaType.parseMediaType("application/java-archive");
   }
   try {
      ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(pathTMP));
      return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(mediatype)
            .body(resource);
   } catch (IOException e) {
      System.err.println("Something went wrong");
      throw new RuntimeException(e);
   }
}
</code>```

`

which is called by my frontend code:
`

```<code>  /**
   * The wrapper function for Requesting a file Download
   * Called by the HTMLElements of the "Files"-Part of the filebrowser
   * @param fileClicked the file which is to be downloaded
   */
  requestFile(fileClicked: string) {
    if (this.currentURL === '') {
      var url = fileClicked;
    } else {
      var url = this.currentURL + this.pathSeperator + fileClicked; // The full URL of the Child directory
    }
    this.dl_filename = fileClicked;
    this.mediaType = 'application/octet-stream';
    if (this.resolveFileExtension(fileClicked) == '.jar') {
      this.mediaType = 'application/java-archive'; // apply custom mediaType for .jar files
    }
    this.http
      .downloadFile(url, this.mediaType)
      .subscribe(this.observerDOWNLOAD); // Call the Server and download the file -> calls download() inside the Observer
  }
</code>```

then in the httpService:

```<code>  /**
   * Calls the /download Endpoint to request a download of the given file
   * @param filePath The relative path to the file which was requested for Download
   * @returns An Observable containing the response of the Server (aka. the File as an Observable)
   */
  downloadFile(filePath: string, mediaType: string) {
    var httpOptions = {};
    httpOptions = {
      params: new HttpParams().set('path', filePath),
      responseType: mediaType
    };
    const url = `${environment.serverUrl}/browsable/download`;
    const result = this.http.get(url, httpOptions);
    return result;
  }
}
</code>```

`

and finally downloaded:
`

```<code>  /**
   * Downloads the given file inside a newly-created, hidden, a-tag-HTMLElement, which is destroyed afterwards
   * Called by the Observer responsible for downloads
   * @param response an Observable representing the File
   */
  download(response: any) {
    // Create a blob representing the File - https://stackblitz.com/edit/angular-blob-file-download?file=app%2Fapp.component.ts for more info
    // "Blobs represent data that isn't necessarily in a JavaScript-native format."
    const blob = new Blob([response], { type: this.mediaType });
    const url = window.URL.createObjectURL(blob);
    /** Workaround for FileDownload | Snippet customized from @Kol - https://stackoverflow.com/a/19328891
      1 - Create a hidden <a> tag.
      2 - Set its href attribute to the blob's URL.
      3 - Set its download attribute to the filename.
      4 - Click on the <a> tag.
       */
    var a = document.createElement('a');
    document.body.appendChild(a);
    a.className = 'hidden';
    a.href = url;
    a.download = this.dl_filename;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
  }
</code>```

`

And here is the picture of my request & response: (here the resulting jar file is ~30mb)
GET-request

Title: jar-archive corrupted after download

Body:
I have set up a simple front- & backend project for browsing & downloading files.

My backend server is written in java and the frontend is an angular application.

The backend has a path to a directory which it exposes to the frontend. The use can then use the frontend to navigate through the directories which are exposed by my backend.

Now I have set up a simple file download, which works fine without any problems EXCEPT when I try to download a jar-archive from the backend.
When I try to download a .jar file, the downloaded file ends up being way larger than expected. For example: I want to download a 18mb .jar file and it ends up downloading a 30mb .jar file instead.

I'm pretty much at the end of my wits when it comes to this problem, as I'm still new to the Frontend & web environment, please keep that in mind. Thank you.

What makes this Problem even more confusing for me is that my response-header shows the correct Content length and the correct amount of transferred bytes, matching my expected file-size (see attached images).
I also tried to apply the "application/java-archive" MediaType to both my Request and Response headers but this didn't fix the problem.

I hope i provided most of the Information needed to fix this, but just in case, here is the relevant code:

Backend:
`

/** Snippet by @fateddy - https://stackoverflow.com/a/35683261
 *
 * @param path the path to the file as a String
 * @return a resource representing the file to download
 */
@GetMapping("/browsable/download")
public  ResponseEntity<Resource> getFile(@RequestParam (required = true) String path) {
   String pathToFile = ROOT_PATH + File.separator + path;
   Path pathTMP = Paths.get(pathToFile); // Temporary Path-Object
   File file = new File(pathToFile);
   HttpHeaders headers = new HttpHeaders();
   MediaType mediatype = MediaType.APPLICATION_OCTET_STREAM;

   if (resolveFileExtension(file).equals(".jar")){ // custom mediaType for .jar files
      mediatype = MediaType.parseMediaType("application/java-archive");
   }
   try {
      ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(pathTMP));
      return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(mediatype)
            .body(resource);
   } catch (IOException e) {
      System.err.println("Something went wrong");
      throw new RuntimeException(e);
   }
}

`

which is called by my frontend code:
`

  /**
   * The wrapper function for Requesting a file Download
   * Called by the HTMLElements of the "Files"-Part of the filebrowser
   * @param fileClicked the file which is to be downloaded
   */
  requestFile(fileClicked: string) {
    if (this.currentURL === '') {
      var url = fileClicked;
    } else {
      var url = this.currentURL + this.pathSeperator + fileClicked; // The full URL of the Child directory
    }
    this.dl_filename = fileClicked;
    this.mediaType = 'application/octet-stream';
    if (this.resolveFileExtension(fileClicked) == '.jar') {
      this.mediaType = 'application/java-archive'; // apply custom mediaType for .jar files
    }
    this.http
      .downloadFile(url, this.mediaType)
      .subscribe(this.observerDOWNLOAD); // Call the Server and download the file -> calls download() inside the Observer
  }

then in the httpService:

  /**
   * Calls the /download Endpoint to request a download of the given file
   * @param filePath The relative path to the file which was requested for Download
   * @returns An Observable containing the response of the Server (aka. the File as an Observable)
   */
  downloadFile(filePath: string, mediaType: string) {
    var httpOptions = {};
    httpOptions = {
      params: new HttpParams().set('path', filePath),
      responseType: mediaType
    };
    const url = `${environment.serverUrl}/browsable/download`;
    const result = this.http.get(url, httpOptions);
    return result;
  }
}

`

and finally downloaded:
`

  /**
   * Downloads the given file inside a newly-created, hidden, a-tag-HTMLElement, which is destroyed afterwards
   * Called by the Observer responsible for downloads
   * @param response an Observable representing the File
   */
  download(response: any) {
    // Create a blob representing the File - https://stackblitz.com/edit/angular-blob-file-download?file=app%2Fapp.component.ts for more info
    // "Blobs represent data that isn't necessarily in a JavaScript-native format."
    const blob = new Blob([response], { type: this.mediaType });
    const url = window.URL.createObjectURL(blob);
    /** Workaround for FileDownload | Snippet customized from @Kol - https://stackoverflow.com/a/19328891
      1 - Create a hidden  tag.
      2 - Set its href attribute to the blob's URL.
      3 - Set its download attribute to the filename.
      4 - Click on the  tag.
       */
    var a = document.createElement('a');
    document.body.appendChild(a);
    a.className = 'hidden';
    a.href = url;
    a.download = this.dl_filename;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
  }

`

And here is the picture of my request & response: (here the resulting jar file is ~30mb)
GET-request


问:
Getting error in Inspect - Store does not have a valid reducer
I created a store.js file for my project and also created rootReducer as well as error reducer but I getting error while I inspect that "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.". My project is running smoothly but I need to see the errors in state as right now the initial state of error is o, so it should show in state - errore: (). But my state is empty and in console I,m getting this error. Here is my store.js file:

```<code>import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './Reducer/rootReducer';

const initialState = {}
const middleWare = [thunk]
let store;

if (window.navigator.userAgent.includes("Chrome")) {
    store = createStore(rootReducer,
        initialState,
        compose(applyMiddleware(...middleWare),
            window.__REDUX_DEVTOOLS_EXTENSION__ &&
            window.__REDUX_DEVTOOLS_EXTENSION__()
        ))
} else {
    store = createStore(rootReducer,
        initialState,
        compose(applyMiddleware(...middleWare)))
}

export default store;
</code>```

Here is my rootReducer.js file

```<code>import {combineReducers} from 'redux'
import errorReducer from './errorReducer';

export default combineReducers({
    errors:errorReducer
});
</code>```

Here is my errorReducer.js file

```<code>import {GET_ERRORS} from '../actions/types';

const initialState = {}

export default function(state=initialState,action){
    switch(action.type){
        case GET_ERRORS:
            return action.payload;
        default:
            return state;
    }
}
</code>```

I've exported the GET_ERROR separately in other file as type.js

```<code>export const GET_ERRORS = 'GET_ERRORS';
</code>```

And Here is my index.js file

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import { Provider } from 'react-redux';
import store from './Store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();
</code>```

I'm not getting any error while I run my project and my project is also running smoothly but I'm getting this error in my console and not getting any error displayed in my state.

Body:
I created a store.js file for my project and also created rootReducer as well as error reducer but I getting error while I inspect that "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.". My project is running smoothly but I need to see the errors in state as right now the initial state of error is o, so it should show in state - errore: (). But my state is empty and in console I,m getting this error. Here is my store.js file:

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './Reducer/rootReducer';

const initialState = {}
const middleWare = [thunk]
let store;

if (window.navigator.userAgent.includes("Chrome")) {
    store = createStore(rootReducer,
        initialState,
        compose(applyMiddleware(...middleWare),
            window.__REDUX_DEVTOOLS_EXTENSION__ &&
            window.__REDUX_DEVTOOLS_EXTENSION__()
        ))
} else {
    store = createStore(rootReducer,
        initialState,
        compose(applyMiddleware(...middleWare)))
}

export default store;

Here is my rootReducer.js file

import {combineReducers} from 'redux'
import errorReducer from './errorReducer';

export default combineReducers({
    errors:errorReducer
});

Here is my errorReducer.js file

import {GET_ERRORS} from '../actions/types';

const initialState = {}

export default function(state=initialState,action){
    switch(action.type){
        case GET_ERRORS:
            return action.payload;
        default:
            return state;
    }
}

I've exported the GET_ERROR separately in other file as type.js

export const GET_ERRORS = 'GET_ERRORS';

And Here is my index.js file

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import { Provider } from 'react-redux';
import store from './Store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

reportWebVitals();

I'm not getting any error while I run my project and my project is also running smoothly but I'm getting this error in my console and not getting any error displayed in my state.