问:
Django DRF - Only allow access to view if user is at a specific physical location
I'm working on a game (react front-end, DRF back-end) that requires users to visit physical locations to win digital prizes. I want to make sure the participants physically visit the locations and don't just make a request from their home to the prize endpoint using curl or postman.  What is the best strategy for this?

Haven't tried anything yet; not sure where to start.


来源: stackexchange

问:
Div scales on scroll but how can I set a max-width? [anime,js]
I'm currently trying out anime.js and wanted to make a background transition.

const divAnimation = anime({
    targets: '.background__circle',
    scale: [0, 50],
    easing: 'easeOutCirc',
    autoplay: false,
    opacity: 1,
});

const scrollPercent = () => {
    const bodyST = document.body.scrollTop;
    const docST = document.documentElement.scrollTop;
    const docSH = document.documentElement.scrollHeight;
    const docCH = document.documentElement.clientHeight;

    return (docST + bodyST) / (docSH - docCH) * 100
}
window.onscroll = () => {
    divAnimation.seek((scrollPercent() / 300) * divAnimation.duration);
  };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.background__1 {
   background-color: rgb( 56, 84, 58 );
   height: 1000px;
}
.background__circle {
        width: 50px;
        height: 50px;
        border-top-right-radius: 50%;
        background-color:  #3d6d41 ;
    }
    .background__2 {
        background-color:  #3d6d41 ;
        height: 1000px;
    }</code>```

```

It should work like that. But my problem is that I don't want that you can scroll in x-direction. Is there a way how I can enable a max-width within the animation progress? Or like 100%?

What I tried was like overflow-x: hidden but that didn't work like it had to.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying out anime.js and wanted to make a background transition.

const divAnimation = anime({
    targets: '.background__circle',
    scale: [0, 50],
    easing: 'easeOutCirc',
    autoplay: false,
    opacity: 1,
});

const scrollPercent = () => {
    const bodyST = document.body.scrollTop;
    const docST = document.documentElement.scrollTop;
    const docSH = document.documentElement.scrollHeight;
    const docCH = document.documentElement.clientHeight;

    return (docST + bodyST) / (docSH - docCH) * 100
}
window.onscroll = () => {
    divAnimation.seek((scrollPercent() / 300) * divAnimation.duration);
  };

.background__1 {
   background-color: rgb( 56, 84, 58 );
   height: 1000px;
}
.background__circle {
        width: 50px;
        height: 50px;
        border-top-right-radius: 50%;
        background-color:  #3d6d41 ;
    }
    .background__2 {
        background-color:  #3d6d41 ;
        height: 1000px;
    }

It should work like that. But my problem is that I don't want that you can scroll in x-direction. Is there a way how I can enable a max-width within the animation progress? Or like 100%?

What I tried was like overflow-x: hidden but that didn't work like it had to.


问:
A problem with the `cli` package the is affecting `ggfortify` and `tidyr` packages?
When loading my libraries, the 2 libraries of ggfortify and tidyr are not working.

What I did is as follows :

I updated R to the 4.2.2 version.

I used the update command for all the packages.

I installed again the library cli with dependencies = TRUE as an argument.

The error looks as follows

```<code>Error: package or namespace load failed for ‘ggfortify’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 namespace ‘cli’ 3.3.0 is already loaded, but >= 3.4.0 is required
</code>```

Body:
When loading my libraries, the 2 libraries of ggfortify and tidyr are not working.

What I did is as follows :

I updated R to the 4.2.2 version.

I used the update command for all the packages.

I installed again the library cli with dependencies = TRUE as an argument.

The error looks as follows

Error: package or namespace load failed for ‘ggfortify’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
 namespace ‘cli’ 3.3.0 is already loaded, but >= 3.4.0 is required


问:
How could scripts in a redirection endpoint HTTP response see the redirection endpoint URI (OAuth 2.0)?
In section 3.1.2.5 of RFC 6749 (OAuth 2.0) is stated:

The redirection request to the client’s endpoint typically results in
an HTML document response, processed by the user-agent.  If the HTML
response is served directly as the result of the redirection request,
any script included in the HTML document will execute with full
access to the redirection URI and the credentials it contains.

I'm assuming the "response" here is the HTTP response being sent from the client to the user agent in response to the request sent from the user agent to the client's redirection endpoint (as a result of the user agent receiving an HTTP redirect from the authorization server).

How could a script in the response have access to the redirection URI? Why would the redirection URI be in the response?


问:
Using reinforcement learning to optimize a function
Given the following cost-function:

```<code>def f(r:list)->float:
  '''
  Evaluates the Himmelblau Function
  Params:
  -r: list with two values x=r[0], y=r[1]
  Returns:
  -Value of the Himmelblau Function

  '''
       return (((r[0]**2+r[1]-11)**2) + (((r[0]+r[1]**2-7)**2)))
</code>```

If I want to optimize this function using any of the open-source reinforcement learning packages available today, what should I do? For the application I have in mind, I don't have access to a GPU. The dopamine package is installed, but I'm not sure how to use it for this kind of task.

As of now, I am having trouble with the following part:

```<code>import dopamine.discrete_domains.grid_world as grid_world

# Define the grid world configuration
config = grid_world.Config(
    width=5,
    height=5,
    start=[0, 0],
    goals=[(4, 4)],
    puddle_locations=[(1, 1), (1, 2), (2, 1), (2, 2)],
    puddle_rewards=[-1, -1, -1, -1],
    puddle_probabilities=[0.9, 0.9, 0.9, 0.9])

# Save the configuration to a file
grid_world.save_config(config, './grid_world_configs/himmelblau.gin')
</code>```

The code is producing the following error message:

ModuleNotFoundError: No module named
'dopamine.discrete_domains.grid_world'

Once the previous code works, it is assumed one shall do something like this:

```<code>import dopamine
import dopamine.discrete_domains.grid_world as grid_world
import tensorflow as tf

# Define the grid world environment
env = grid_world.GridWorld('./grid_world_configs/himmelblau.gin')

# Define the agent
agent = dopamine.agents.dqn.DQN(
    sess=tf.compat.v1.Session(),
    num_actions=env.action_space.n,
    observation_shape=env.observation_space.shape,
    stack_size=1)

# Set the discount factor
agent.gamma = 0.99

# Set the learning rate
agent.learning_rate = 1e-3

# Set the target update period
agent.target_update_period = 500

# Set the agent's exploration policy
agent.exploration = dopamine.exploration.LinearSchedule(1.0, 0.1, 1000000)

# Set the checkpoint interval
agent.checkpoint_interval = 1000

# Set the summary interval
agent.summary_interval = 100

# Set the logging directory
agent.logging_directory = './logs'

# Train the agent
agent.train(env, max_steps=10000)

# Test the agent
agent.test(env)
</code>```

Nonetheless, I don't understand how to let the agent know that f is the cost function and how to pass the information provided by f to the agent.

Any help in making this work would be greatly appreciated.

Body:
Given the following cost-function:

def f(r:list)->float:
  '''
  Evaluates the Himmelblau Function
  Params:
  -r: list with two values x=r[0], y=r[1]
  Returns:
  -Value of the Himmelblau Function

  '''
       return (((r[0]**2+r[1]-11)**2) + (((r[0]+r[1]**2-7)**2)))

If I want to optimize this function using any of the open-source reinforcement learning packages available today, what should I do? For the application I have in mind, I don't have access to a GPU. The dopamine package is installed, but I'm not sure how to use it for this kind of task.

As of now, I am having trouble with the following part:

import dopamine.discrete_domains.grid_world as grid_world

# Define the grid world configuration
config = grid_world.Config(
    width=5,
    height=5,
    start=[0, 0],
    goals=[(4, 4)],
    puddle_locations=[(1, 1), (1, 2), (2, 1), (2, 2)],
    puddle_rewards=[-1, -1, -1, -1],
    puddle_probabilities=[0.9, 0.9, 0.9, 0.9])

# Save the configuration to a file
grid_world.save_config(config, './grid_world_configs/himmelblau.gin')

The code is producing the following error message:

ModuleNotFoundError: No module named
'dopamine.discrete_domains.grid_world'

Once the previous code works, it is assumed one shall do something like this:

import dopamine
import dopamine.discrete_domains.grid_world as grid_world
import tensorflow as tf

# Define the grid world environment
env = grid_world.GridWorld('./grid_world_configs/himmelblau.gin')

# Define the agent
agent = dopamine.agents.dqn.DQN(
    sess=tf.compat.v1.Session(),
    num_actions=env.action_space.n,
    observation_shape=env.observation_space.shape,
    stack_size=1)

# Set the discount factor
agent.gamma = 0.99

# Set the learning rate
agent.learning_rate = 1e-3

# Set the target update period
agent.target_update_period = 500

# Set the agent's exploration policy
agent.exploration = dopamine.exploration.LinearSchedule(1.0, 0.1, 1000000)

# Set the checkpoint interval
agent.checkpoint_interval = 1000

# Set the summary interval
agent.summary_interval = 100

# Set the logging directory
agent.logging_directory = './logs'

# Train the agent
agent.train(env, max_steps=10000)

# Test the agent
agent.test(env)

Nonetheless, I don't understand how to let the agent know that f is the cost function and how to pass the information provided by f to the agent.

Any help in making this work would be greatly appreciated.


问:
Navigate to another page in React Native
I have difficulty navigate to another page. I want to click Card in Profile page and then it will navigate to page CardHome. I add <NavigationContainer> in apps.js but didnt work. I am newbie so I am not sure where is wrong. Hopefully someone can help me.

```<code>This is profile.js

`import React, { useState, useEffect } from 'react'import { Text, View, StyleSheet, SafeAreaView, TouchableOpacity } from 'react-native'
import { firebase } from '../config'import EntypoIcon from "react-native-vector-icons/Entypo";
import { createStackNavigator } from '@react-navigation/stack';import { NavigationContainer } from '@react-navigation/native';import CardHome from '../CardHome';

const Profile  = () => {const [name, setName] = useState('')

useEffect (() => {
  firebase.firestore().collection('users')
  .doc(firebase.auth().currentUser.uid).get()
  .then((snapshot) => {
    if(snapshot.exists){
      setName(snapshot.data())
    }
    else {
      console.log('User does not exist')
    }
  })
}, [])

return (
  <SafeAreaView style={styles.container}>
    <Text style={{fontSize:20, fontWeight:'bold', marginLeft:180, marginBottom:-11}}>
      {name.username}
    </Text>

  <TouchableOpacity
  onPress={() => navigation.navigate('CardHome')}
  style={styles.button3}>
    <View style={styles.icon3Row}>
      <EntypoIcon name="open-book" style={styles.icon3}></EntypoIcon>
      <Text style={styles.card}>CARD</Text>
    </View>
  </TouchableOpacity>

    <TouchableOpacity
      onPress={() => {firebase.auth().signOut()}}
      style={styles.button5}>
    <EntypoIcon name="user" style={styles.icon5}></EntypoIcon>
    </TouchableOpacity>

  </SafeAreaView>

)
</code>```

}`

This is my CardHome.js

```<code>`import React, { Component } from "react";
import { StyleSheet, View, TouchableOpacity, Text } from "react-native";
import EntypoIcon from "react-native-vector-icons/Entypo";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";

function CardHome(props) {
return (
    <View style={styles.container}>
      <View style={styles.buttonRow}>
        <TouchableOpacity style={styles.button}>
          <Text style={styles.scam}>SCAM</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.button5}>
          <EntypoIcon name="magnifying-glass" style={styles.icon5}></EntypoIcon>
          <Text style={styles.explore3}>EXPLORE</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.button4Row}>
        <TouchableOpacity style={styles.button4}>
          <Text style={styles.socialEngineering}>SOCIAL ENGINEERING</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.button3}>
          <EntypoIcon name="magnifying-glass" style={styles.icon4}></EntypoIcon>
          <Text style={styles.explore2}>EXPLORE</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
</code>```

this is my Apps.js

```<code>import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import React, { useState, useEffect } from 'react';
import { firebase } from './config';

import Login from "./src/Login";
import Registration from "./src/Registration";
import Profile from "./src/Profile";
import Header from "./components/Header";
import CardHome from "./CardHome";

const Stack = createStackNavigator();

function App() {
  const [initializing, setInitializing] = useState(true);
  const [user, setUser] = useState();

  function onAuthStateChanged(user) {
    setUser(user);
    if (initializing) setInitializing(false);
  }

  useEffect(() => {
    const subscriber = firebase.auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber;
  }, []);

  if (initializing) return null;

  if (!user) {
    return (
      <Stack.Navigator>
        <Stack.Screen
          name="Login"
          component={Login}
          options={{
            headerTitle: () => <Header name="MySecureAwareness" />,
            headerStyle: {
              height: 150,
              borderBottomLeftRadius: 50,
              borderBottomRightRadius: 50,
              backgroundColor: "#00e4d0",
              shadowColor: "#000",
              elevation: 25,
            }
          }}
        />
        <Stack.Screen
          name="Registration"
          component={Registration}
          options={{
            headerTitle: () => <Header name="MySecureAwareness" />,
            headerStyle: {
              height: 150,
              borderBottomLeftRadius: 50,
              borderBottomRightRadius: 50,
              backgroundColor: "#00e4d0",
              shadowColor: "#000",
              elevation: 25
            }
          }}
        />
      </Stack.Navigator>
    );
  }

  return (
    <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen
        name="Profile"
        component={Profile}
        options={{
          headerTitle: () => <Header name="MySecureAwareness" />,
          headerStyle: {
            height: 150,
            borderBottomLeftRadius: 50,
            borderBottomRightRadius: 50,
            backgroundColor: "#00e4d0",
            shadowColor: "#000",
            elevation: 25
          }
        }}
      />
      <Stack.Screen
        name="CardHome" component={CardHome} />
    </Stack.Navigator>
    </NavigationContainer>

  );
}

export default () => {
  return (
    <NavigationContainer>
      <App />
    </NavigationContainer>
  )
}

</code>```

I want to click Card then it will navigate to Cardhome.js.

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

Body:
I have difficulty navigate to another page. I want to click Card in Profile page and then it will navigate to page CardHome. I add <NavigationContainer> in apps.js but didnt work. I am newbie so I am not sure where is wrong. Hopefully someone can help me.

This is profile.js

`import React, { useState, useEffect } from 'react'import { Text, View, StyleSheet, SafeAreaView, TouchableOpacity } from 'react-native'
import { firebase } from '../config'import EntypoIcon from "react-native-vector-icons/Entypo";
import { createStackNavigator } from '@react-navigation/stack';import { NavigationContainer } from '@react-navigation/native';import CardHome from '../CardHome';

const Profile  = () => {const [name, setName] = useState('')

useEffect (() => {
  firebase.firestore().collection('users')
  .doc(firebase.auth().currentUser.uid).get()
  .then((snapshot) => {
    if(snapshot.exists){
      setName(snapshot.data())
    }
    else {
      console.log('User does not exist')
    }
  })
}, [])

return (
  <SafeAreaView style={styles.container}>
    <Text style={{fontSize:20, fontWeight:'bold', marginLeft:180, marginBottom:-11}}>
      {name.username}
    </Text>

  <TouchableOpacity
  onPress={() => navigation.navigate('CardHome')}
  style={styles.button3}>
    <View style={styles.icon3Row}>
      <EntypoIcon name="open-book" style={styles.icon3}></EntypoIcon>
      <Text style={styles.card}>CARD</Text>
    </View>
  </TouchableOpacity>

    <TouchableOpacity
      onPress={() => {firebase.auth().signOut()}}
      style={styles.button5}>
    <EntypoIcon name="user" style={styles.icon5}></EntypoIcon>
    </TouchableOpacity>

  </SafeAreaView>

)

}`

This is my CardHome.js

`import React, { Component } from "react";
import { StyleSheet, View, TouchableOpacity, Text } from "react-native";
import EntypoIcon from "react-native-vector-icons/Entypo";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";

function CardHome(props) {
return (
    <View style={styles.container}>
      <View style={styles.buttonRow}>
        <TouchableOpacity style={styles.button}>
          <Text style={styles.scam}>SCAM</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.button5}>
          <EntypoIcon name="magnifying-glass" style={styles.icon5}></EntypoIcon>
          <Text style={styles.explore3}>EXPLORE</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.button4Row}>
        <TouchableOpacity style={styles.button4}>
          <Text style={styles.socialEngineering}>SOCIAL ENGINEERING</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.button3}>
          <EntypoIcon name="magnifying-glass" style={styles.icon4}></EntypoIcon>
          <Text style={styles.explore2}>EXPLORE</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

this is my Apps.js

import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import React, { useState, useEffect } from 'react';
import { firebase } from './config';

import Login from "./src/Login";
import Registration from "./src/Registration";
import Profile from "./src/Profile";
import Header from "./components/Header";
import CardHome from "./CardHome";

const Stack = createStackNavigator();

function App() {
  const [initializing, setInitializing] = useState(true);
  const [user, setUser] = useState();

  function onAuthStateChanged(user) {
    setUser(user);
    if (initializing) setInitializing(false);
  }

  useEffect(() => {
    const subscriber = firebase.auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber;
  }, []);

  if (initializing) return null;

  if (!user) {
    return (
      <Stack.Navigator>
        <Stack.Screen
          name="Login"
          component={Login}
          options={{
            headerTitle: () => ,
            headerStyle: {
              height: 150,
              borderBottomLeftRadius: 50,
              borderBottomRightRadius: 50,
              backgroundColor: "#00e4d0",
              shadowColor: "#000",
              elevation: 25,
            }
          }}
        />
        <Stack.Screen
          name="Registration"
          component={Registration}
          options={{
            headerTitle: () => ,
            headerStyle: {
              height: 150,
              borderBottomLeftRadius: 50,
              borderBottomRightRadius: 50,
              backgroundColor: "#00e4d0",
              shadowColor: "#000",
              elevation: 25
            }
          }}
        />
      </Stack.Navigator>
    );
  }

  return (
    <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen
        name="Profile"
        component={Profile}
        options={{
          headerTitle: () => ,
          headerStyle: {
            height: 150,
            borderBottomLeftRadius: 50,
            borderBottomRightRadius: 50,
            backgroundColor: "#00e4d0",
            shadowColor: "#000",
            elevation: 25
          }
        }}
      />
      <Stack.Screen
        name="CardHome" component={CardHome} />
    </Stack.Navigator>
    </NavigationContainer>

  );
}

export default () => {
  return (
    <NavigationContainer>
      <App />
    </NavigationContainer>
  )
}

I want to click Card then it will navigate to Cardhome.js.


问:
SwiftUI computed var in custom init of a view error
I want to be able to calculate a variable (nbwin) depending of the attribute "nom_rang1" of the coredata entity "RamiSession".
Basically, for each entity "RamiSession" whose attribute "nom_rang1" is equal to "nom_joueur_selec" (which is a String), I want to increment a counter and return the final value of that counter in the variable "nbwin". And then display it in a text box.

I think I have to compute that property "nbwin" in my custom init() method. But it doesn't work.

I have the error message on the line where nbwin is calculated in init saying "Function produces expected type 'Int'; did you mean to call it with '()'?"

But if I put () at the end of the calculation of "nbwin", I have an error message saying "'self' used before all stored properties are initialized"

So I guess I am doing something wrong...

Can anyone help me? Thank you

Here is my code

```<code>struct GraphView: View {

    @FetchRequest
    private var sessions: FetchedResults<RamiSession>

    private var nbwin : Int

    init(nom_joueur_selec: String) {
        let predicate = NSPredicate(format: "nom_rang1= %@ OR nom_rang2= %@ ", nom_joueur_selec, nom_joueur_selec)
        let sortDescriptors = [SortDescriptor(\RamiSession.date)] // need something to sort by.
        _sessions = FetchRequest(sortDescriptors: sortDescriptors, predicate: predicate)

        nbwin = {
            var nbwinTotal = 0
            for session in sessions {
                if session.nom_rang1 == nom_joueur_selec {
                    nbwinTotal += 1
                }
            }
            return nbwinTotal
        }

    }

    //
    var body: some View {

        Text("\(nbwin)")

    } // body
}
</code>```

Body:
I want to be able to calculate a variable (nbwin) depending of the attribute "nom_rang1" of the coredata entity "RamiSession".
Basically, for each entity "RamiSession" whose attribute "nom_rang1" is equal to "nom_joueur_selec" (which is a String), I want to increment a counter and return the final value of that counter in the variable "nbwin". And then display it in a text box.

I think I have to compute that property "nbwin" in my custom init() method. But it doesn't work.

I have the error message on the line where nbwin is calculated in init saying "Function produces expected type 'Int'; did you mean to call it with '()'?"

But if I put () at the end of the calculation of "nbwin", I have an error message saying "'self' used before all stored properties are initialized"

So I guess I am doing something wrong...

Can anyone help me? Thank you

Here is my code

struct GraphView: View {

    @FetchRequest
    private var sessions: FetchedResults<RamiSession>

    private var nbwin : Int

    init(nom_joueur_selec: String) {
        let predicate = NSPredicate(format: "nom_rang1= %@ OR nom_rang2= %@ ", nom_joueur_selec, nom_joueur_selec)
        let sortDescriptors = [SortDescriptor(\RamiSession.date)] // need something to sort by.
        _sessions = FetchRequest(sortDescriptors: sortDescriptors, predicate: predicate)

        nbwin = {
            var nbwinTotal = 0
            for session in sessions {
                if session.nom_rang1 == nom_joueur_selec {
                    nbwinTotal += 1
                }
            }
            return nbwinTotal
        }

    }

    //
    var body: some View {

        Text("\(nbwin)")

    } // body
}


问:
numpy qr factorization problems
I'm trying to extract rotation matrix from affine transform matrix (via QR decomposition), but it gives me wrong rotations. After applying rotation vectors should have zero angle between them. I have no idea what is going wrong.

Here is the code that is currently giving the unexpected output:

import numpy as np
import math

np.set_printoptions(suppress=True)

def compute_affine(ins, out): # matrices 3x4
    # https://stackoverflow.com/questions/8873462/how-to-perform-coordinates-affine-transformation-using-python
    # finding transformation
    l = len(ins)
    entry = lambda r, d: np.linalg.det(np.delete(np.vstack([r, ins.T, np.ones(l)]), d, axis=0))
    M = np.array([[(-1) ** i * entry(R, i) for R in out.T] for i in range(l + 1)])
    print(M)
    A, t = np.hsplit(M[1:].T / (-M[0])[:, None], [l - 1])
    t = np.transpose(t)[0]
    # output transformation
    print("Affine transformation matrix:\n", A)
    print("Affine transformation translation vector:\n", t)
    # unittests
    print("TESTING:")
    for p, P in zip(np.array(ins), np.array(out)):
        image_p = np.dot(A, p) + t
        result = "[OK]" if np.allclose(image_p, P) else "[ERROR]"
        print(p, " mapped to: ", image_p, " ; expected: ", P, result)
    return A, t

def dot_product_angle(v1,v2):

    if np.linalg.norm(v1) == 0 or np.linalg.norm(v2) == 0:
        print("Zero magnitude vector!")
    else:
        vector_dot_product = np.dot(v1,v2)
        arccos = np.arccos(vector_dot_product / (np.linalg.norm(v1) * np.linalg.norm(v2)))
        angle = np.degrees(arccos)
        return angle
    return 0

if __name__=="__main__":
    import numpy as np

    src = np.array([
        [1, 0, 0],
        [0, 0, 1],
        [1, 0, 1],
        [1, 1, 1],
    ])

    uv = np.array([
        [0.1, 0],
        [0, -0.1],
        [0.1, -0.1],
        [1, 1]
    ])

    angle = 45
    rot_matrix = np.array([[math.cos(angle), -math.sin(angle), 0 ],
                                [math.sin(angle), math.cos(angle), 0],
                                [0, 0, 1]])

    dst = np.dot(src, rot_matrix)
    # compute affine matrices
    src_A, src_t = compute_affine(src, uv)
    dst_A, dst_t = compute_affine(dst, uv)

    src_Q, src_R = np.linalg.qr(np.vstack([src_A, np.cross(src_A[0], src_A[1])]))
    dst_Q, dst_R = np.linalg.qr(np.vstack([dst_A, np.cross(dst_A[0], dst_A[1])]))

    vec1 = np.dot(src_Q[:-1], src[0])
    vec2 = np.dot(dst_Q[:-1], dst[0])

    if not dot_product_angle(vec1, vec2) == 0:
        raise Exception("Angle is invalid should be zero")
```

Title: numpy qr factorization problems


问:
Wordpress woocommerce add to cart button not working
This is the code in the file loop/add-to-cart.php
I tried to edit the code, when I click on the add to cart button, nothing is added anyway

```<code><?php

if (!defined('ABSPATH')) {
  exit;
}

global $product;

if ( $product->is_in_stock() ) {
echo apply_filters(
  'woocommerce_loop_add_to_cart_link', // WPCS: XSS ok.
  sprintf(
    '<div class="add-to-cart-container product-buttons-wrapper mt-auto"><a href="%s" data-quantity="%s" class="%s product_type_%s single_add_to_cart_button button button-primary d-none %s" %s> %s</a>',
    esc_url($product->add_to_cart_url()),
    esc_attr(isset($args['quantity']) ? $args['quantity'] : 1),
    $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
    esc_attr($product->get_type()),
    $product->get_type() == 'simple' ? 'ajax_add_to_cart' : '',
    isset($args['attributes']) ? wc_implode_html_attributes($args['attributes']) : '',
    esc_html($product->add_to_cart_text())
  ),
  $product,
  $args
);?>
<button type="submit" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" data-quantity="1" data-product_id="<?php echo esc_attr($product->get_id()); ?>" class="single_add_to_cart_button alt button button-primary"><?php echo esc_html($product->single_add_to_cart_text()); ?></button>
<button class="button button-secondary" data-bs-toggle="modal" data-bs-target="#modal-request">Заказать</button></div>

<?php } else { ?>
    <div class="product-buttons-wrapper">
        <button class="button button-secondary" data-bs-toggle="modal" data-bs-target="#modal-request">Заказать</button>
    </div>
<?php }
</code>```

Tried online solutions, nothing worked.

Body:
This is the code in the file loop/add-to-cart.php
I tried to edit the code, when I click on the add to cart button, nothing is added anyway

<?php

if (!defined('ABSPATH')) {
  exit;
}

global $product;

if ( $product->is_in_stock() ) {
echo apply_filters(
  'woocommerce_loop_add_to_cart_link', // WPCS: XSS ok.
  sprintf(
    '
 %s',
    esc_url($product->add_to_cart_url()),
    esc_attr(isset($args['quantity']) ? $args['quantity'] : 1),
    $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
    esc_attr($product->get_type()),
    $product->get_type() == 'simple' ? 'ajax_add_to_cart' : '',
    isset($args['attributes']) ? wc_implode_html_attributes($args['attributes']) : '',
    esc_html($product->add_to_cart_text())
  ),
  $product,
  $args
);?>
<button type="submit" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" data-quantity="1" data-product_id="<?php echo esc_attr($product->get_id()); ?>" class="single_add_to_cart_button alt button button-primary"><?php echo esc_html($product->single_add_to_cart_text()); ?></button>
<button class="button button-secondary" data-bs-toggle="modal" data-bs-target="#modal-request">Заказать</button>

<?php } else { ?>

        <button class="button button-secondary" data-bs-toggle="modal" data-bs-target="#modal-request">Заказать</button>

<?php }

Tried online solutions, nothing worked.


问:
When calling JS function from Python: execjs._exceptions.ProgramError: Error: Cannot find module 'serialport'
I am attempting to call a function from a .js file in my python script using Pyexecjs.

with open("simulations/simulator.js", "r") as f:
js_code = f.read()

```<code>    ctx = execjs.compile(js_code)

    result = ctx.call("function")
    result
</code>```

But when calling the function, I get this error:

execjs._exceptions.ProgramError: Error: Cannot find module
'serialport'

The JS function that I am calling looks like this:

process.title = Simulator | ${process.argv[3]} | ${process.argv[4]}
var SerialPort = require('serialport')

```<code>const xps = new SerialPort(process.argv[3], {
        baudRate: 115200,
    }, (err) => {
        if (err) console.error(`ERROR ${err}`)
    })
    xps.asyncWrite = function (data) {
        return new Promise((resolve, reject) => {
            this.write(data, (err, results) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(results)
                }
            })
        })
    }
const UrinalFlush = async () => {
  //console.debug(' User with Flush', '\n','User Detected (wait 5 sec.)')
  await xps.asyncWrite(IR1)
  await delay(6000)
  await xps.asyncWrite(IR0)
  console.debug(' User departing... Flush starting')
  await delay(5000)
  console.debug(' Flush Completed')
  Start()
}
</code>```

I have run npm install serialport successfully but, I still am not sure what needs to be done next. Could someone point me in the right direction?

Body:
I am attempting to call a function from a .js file in my python script using Pyexecjs.

with open("simulations/simulator.js", "r") as f:
js_code = f.read()

    ctx = execjs.compile(js_code)

    result = ctx.call("function")
    result

But when calling the function, I get this error:

execjs._exceptions.ProgramError: Error: Cannot find module
'serialport'

The JS function that I am calling looks like this:

process.title = Simulator | ${process.argv[3]} | ${process.argv[4]}
var SerialPort = require('serialport')

const xps = new SerialPort(process.argv[3], {
        baudRate: 115200,
    }, (err) => {
        if (err) console.error(`ERROR ${err}`)
    })
    xps.asyncWrite = function (data) {
        return new Promise((resolve, reject) => {
            this.write(data, (err, results) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(results)
                }
            })
        })
    }
const UrinalFlush = async () => {
  //console.debug(' User with Flush', '\n','User Detected (wait 5 sec.)')
  await xps.asyncWrite(IR1)
  await delay(6000)
  await xps.asyncWrite(IR0)
  console.debug(' User departing... Flush starting')
  await delay(5000)
  console.debug(' Flush Completed')
  Start()
}

I have run npm install serialport successfully but, I still am not sure what needs to be done next. Could someone point me in the right direction?


问:
Android app show "java.lang.UnsupportedOperationExeption" while using JDBC to Connect mysql in localhost
I'm trying to execute a mysql query in my java application using JDBC but instead of a query result, I get an error

java.lang.UnsupportedOperationExeption.

I did these steps in my app:

Added mysql Connector.jar (version 8) in libs directory

Added <uses-permission android:name="android.permission.INTERNET" /> to manifest

Updated gradel, jdk to latest version

Changed api to 32 or 21 but it didn't work

The Mysql user privileges and tables are ok. I launched my app in Android Studio

Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    TextView query_result_TextView, Error_textview;
    Button show_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        query_result_TextView = (TextView) findViewById(R.id.textView);
        Error_textview = (TextView) findViewById(R.id.textView2);
        show_btn = (Button) findViewById(R.id.showbtn);

        show_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/adl","testuser","12345678");
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT * FROM test ;");

                    query_result_TextView.setText(rs.toString());
                }
                catch (Exception ex) {
                    Error_textview.setText(ex.toString());
//                    java.lang.UnsupportedOperationExeption
                }
            }
        });

    }
}
</code>```

I tried soooo much, but this error didn't get resolved.

Please help !

NOTE: i tried to coonect with eclipse IDE with same syntax and in Eclipse worked pefectly!!!! is there a option in Android Studio that's avoiding to connect?

Body:
I'm trying to execute a mysql query in my java application using JDBC but instead of a query result, I get an error

java.lang.UnsupportedOperationExeption.

I did these steps in my app:

Added mysql Connector.jar (version 8) in libs directory

Added <uses-permission android:name="android.permission.INTERNET" /> to manifest

Updated gradel, jdk to latest version

Changed api to 32 or 21 but it didn't work

The Mysql user privileges and tables are ok. I launched my app in Android Studio

Here is my code:

public class MainActivity extends AppCompatActivity {

    TextView query_result_TextView, Error_textview;
    Button show_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        query_result_TextView = (TextView) findViewById(R.id.textView);
        Error_textview = (TextView) findViewById(R.id.textView2);
        show_btn = (Button) findViewById(R.id.showbtn);

        show_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/adl","testuser","12345678");
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT * FROM test ;");

                    query_result_TextView.setText(rs.toString());
                }
                catch (Exception ex) {
                    Error_textview.setText(ex.toString());
//                    java.lang.UnsupportedOperationExeption
                }
            }
        });

    }
}

I tried soooo much, but this error didn't get resolved.

Please help !

NOTE: i tried to coonect with eclipse IDE with same syntax and in Eclipse worked pefectly!!!! is there a option in Android Studio that's avoiding to connect?


问:
How to upload images to facebook with selenium?
selenium is not locating the image upload box.

I tried using the xpath //input[@type='file'] and had no result

the page loads selenium looks for the input and the page simply closes, as if the code had run without errors

```<code>driver.get("https://www.facebook.com/groups/2754657368012666/")

input_email = driver.find_element(By.ID, "email").send_keys("xxxxxx")
input_password = driver.find_element(By.ID, "pass").send_keys("xxxxx", Keys.ENTER)

uploadimage = driver.find_element(By.XPATH, "//input[@type='file']")
uploadimage.send_keys(r"C:\Users\user01\Downloads\productionID_4434164.jpg")

publish = driver.find_element(By.XPATH, "//div[@aria-label='Publish']").click()
driver.implicitly_wait(30)
print(driver.current_url)
sleep(5)
</code>```

Body:
selenium is not locating the image upload box.

I tried using the xpath //input[@type='file'] and had no result

the page loads selenium looks for the input and the page simply closes, as if the code had run without errors

driver.get("https://www.facebook.com/groups/2754657368012666/")

input_email = driver.find_element(By.ID, "email").send_keys("xxxxxx")
input_password = driver.find_element(By.ID, "pass").send_keys("xxxxx", Keys.ENTER)

uploadimage = driver.find_element(By.XPATH, "//input[@type='file']")
uploadimage.send_keys(r"C:\Users\user01\Downloads\productionID_4434164.jpg")

publish = driver.find_element(By.XPATH, "//div[@aria-label='Publish']").click()
driver.implicitly_wait(30)
print(driver.current_url)
sleep(5)


问:
logoff/shutdown script for WSL
I've got a daemon running under WSL1 which writes to disk and specifically to the host partition ( D:\ ).

I was wondering if I can use Local Group Policy Editor to set a logoff/shutdown script to stop my daemon in those cases. Will it work? Is there any other method?

Thanks

Title: logoff/shutdown script for WSL


问:
How to create a random roulette selector/roulette horizontal scrollbar? - Tkinter Python
So as i have already posted a few questions here, about this assignment i have to do for uni, that is about building a food recipes desktop app with Tkinter and Python. And i thought it would be nice to add some kind of a random horizontal scroll/roulette selector of recipes in this bar that i am insert at the bottom of the startpage:

Like whenever the user clicked in one of the arrows (right or left) it would roll horizontally different recipe buttons and after some secons it would stop, something like a roulette I think:

Is that even possible to make with Tkinter and Python? I have already put the recipes buttons inside a main canvas, that would hide, on its sides, the others buttons that are not appearing at the moment. And i would probably need to do some function to when either one of the arrows was clicked it would do the "random selector thing". But what do i need to have inside the function? Thank you!!

Here's the code that i have already have for the bar:

```<code>        self.c_randombar = Canvas(self, width=1078, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_randombar.place(x=181, y=906,)
        self.img_random = PhotoImage(file="assets/frame0/randomrecipe.png")
        self.c_randombar.create_image(0, 0,anchor="nw", image= self.img_random)
        #Right Arrow
        self.c_rightarrow = Canvas(self, width=81, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_rightarrow.place(x=1290, y=907,)
        self.img_bg_rightarrow = PhotoImage(file="assets/frame0/bg_rightarrow.png")
        self.c_rightarrow.create_image(0, 0,anchor="nw", image= self.img_bg_rightarrow)
        #---------
        self.img_rightarrow = PhotoImage(file = r"assets/frame0/button_rightarrow.png")
        self.button_rightarrow = tk.Button(self, image = self.img_rightarrow, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,)
        self.button_rightarrow.place(x=1289, y=906, width=81, height=64)
        #Left Arrow
        self.c_leftarrow = Canvas(self, width=81, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_leftarrow.place(x=71, y=907,)
        self.img_bg_leftarrow = PhotoImage(file="assets/frame0/bg_rightarrow.png")
        self.c_leftarrow.create_image(0, 0,anchor="nw", image= self.img_bg_leftarrow)
        #---------
        self.img_leftarrow = PhotoImage(file = r"assets/frame0/button_leftarrow.png")
        self.button_leftarrow = tk.Button(self, image = self.img_leftarrow, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,)
        self.button_leftarrow.place(x=70, y=906, width=81, height=64)
        #____________________________

        #Main Canvas for the recipes buttons
        self.c_recipes = Canvas(self, width=1074, height=60, borderwidth=0, highlightthickness=0,relief="flat", background="#182DEF")
        self.c_recipes.place(x=183, y=908)
        #Recipe 1
        self.c_recipe1 = Canvas(self.c_recipes, width=157, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_recipe1.place(x=40, y=17,)
        self.img_bg_recipe1 = PhotoImage(file="assets/frame0/Nova pasta/bg_button1.png")
        self.c_recipe1.create_image(0, 0,anchor="nw", image= self.img_bg_recipe1)
        #---------
        self.img_recipe1 = PhotoImage(file = r"assets/frame0/Nova pasta/button1.png")
        self.button_recipe1 = tk.Button(self.c_recipes, image = self.img_recipe1, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
        self.button_recipe1.place(x=39, y=16, width=157, height=27)
        #____________________________
        #Recipe 2
        self.c_recipe2 = Canvas(self.c_recipes, width=256, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_recipe2.place(x=340, y=17,)
        self.img_bg_recipe2 = PhotoImage(file="assets/frame0/Nova pasta/bg_button2.png")
        self.c_recipe2.create_image(0, 0,anchor="nw", image= self.img_bg_recipe2)
        #---------
        self.img_recipe2 = PhotoImage(file = r"assets/frame0/Nova pasta/button2.png")
        self.button_recipe2 = tk.Button(self.c_recipes, image = self.img_recipe2, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
        self.button_recipe2.place(x=339, y=16, width=256, height=27)
        #____________________________
        #Recipe 3
        self.c_recipe3 = Canvas(self.c_recipes, width=296, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_recipe3.place(x=739, y=17,)
        self.img_bg_recipe3 = PhotoImage(file="assets/frame0/Nova pasta/bg_button3.png")
        self.c_recipe3.create_image(0, 0,anchor="nw", image= self.img_bg_recipe3)
        #---------
        self.img_recipe3 = PhotoImage(file = r"assets/frame0/Nova pasta/button3.png")
        self.button_recipe3 = tk.Button(self.c_recipes, image = self.img_recipe3, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
        self.button_recipe3.place(x=738, y=16, width=296, height=27)
        #____________________________```

Forever thankful!!
```

Body:
So as i have already posted a few questions here, about this assignment i have to do for uni, that is about building a food recipes desktop app with Tkinter and Python. And i thought it would be nice to add some kind of a random horizontal scroll/roulette selector of recipes in this bar that i am insert at the bottom of the startpage:

Like whenever the user clicked in one of the arrows (right or left) it would roll horizontally different recipe buttons and after some secons it would stop, something like a roulette I think:

Is that even possible to make with Tkinter and Python? I have already put the recipes buttons inside a main canvas, that would hide, on its sides, the others buttons that are not appearing at the moment. And i would probably need to do some function to when either one of the arrows was clicked it would do the "random selector thing". But what do i need to have inside the function? Thank you!!

Here's the code that i have already have for the bar:

        self.c_randombar = Canvas(self, width=1078, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_randombar.place(x=181, y=906,)
        self.img_random = PhotoImage(file="assets/frame0/randomrecipe.png")
        self.c_randombar.create_image(0, 0,anchor="nw", image= self.img_random)
        #Right Arrow
        self.c_rightarrow = Canvas(self, width=81, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_rightarrow.place(x=1290, y=907,)
        self.img_bg_rightarrow = PhotoImage(file="assets/frame0/bg_rightarrow.png")
        self.c_rightarrow.create_image(0, 0,anchor="nw", image= self.img_bg_rightarrow)
        #---------
        self.img_rightarrow = PhotoImage(file = r"assets/frame0/button_rightarrow.png")
        self.button_rightarrow = tk.Button(self, image = self.img_rightarrow, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,)
        self.button_rightarrow.place(x=1289, y=906, width=81, height=64)
        #Left Arrow
        self.c_leftarrow = Canvas(self, width=81, height=64, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_leftarrow.place(x=71, y=907,)
        self.img_bg_leftarrow = PhotoImage(file="assets/frame0/bg_rightarrow.png")
        self.c_leftarrow.create_image(0, 0,anchor="nw", image= self.img_bg_leftarrow)
        #---------
        self.img_leftarrow = PhotoImage(file = r"assets/frame0/button_leftarrow.png")
        self.button_leftarrow = tk.Button(self, image = self.img_leftarrow, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,)
        self.button_leftarrow.place(x=70, y=906, width=81, height=64)
        #____________________________

        #Main Canvas for the recipes buttons
        self.c_recipes = Canvas(self, width=1074, height=60, borderwidth=0, highlightthickness=0,relief="flat", background="#182DEF")
        self.c_recipes.place(x=183, y=908)
        #Recipe 1
        self.c_recipe1 = Canvas(self.c_recipes, width=157, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_recipe1.place(x=40, y=17,)
        self.img_bg_recipe1 = PhotoImage(file="assets/frame0/Nova pasta/bg_button1.png")
        self.c_recipe1.create_image(0, 0,anchor="nw", image= self.img_bg_recipe1)
        #---------
        self.img_recipe1 = PhotoImage(file = r"assets/frame0/Nova pasta/button1.png")
        self.button_recipe1 = tk.Button(self.c_recipes, image = self.img_recipe1, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
        self.button_recipe1.place(x=39, y=16, width=157, height=27)
        #____________________________
        #Recipe 2
        self.c_recipe2 = Canvas(self.c_recipes, width=256, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_recipe2.place(x=340, y=17,)
        self.img_bg_recipe2 = PhotoImage(file="assets/frame0/Nova pasta/bg_button2.png")
        self.c_recipe2.create_image(0, 0,anchor="nw", image= self.img_bg_recipe2)
        #---------
        self.img_recipe2 = PhotoImage(file = r"assets/frame0/Nova pasta/button2.png")
        self.button_recipe2 = tk.Button(self.c_recipes, image = self.img_recipe2, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
        self.button_recipe2.place(x=339, y=16, width=256, height=27)
        #____________________________
        #Recipe 3
        self.c_recipe3 = Canvas(self.c_recipes, width=296, height=27, borderwidth=0, highlightthickness=0,relief="flat", )
        self.c_recipe3.place(x=739, y=17,)
        self.img_bg_recipe3 = PhotoImage(file="assets/frame0/Nova pasta/bg_button3.png")
        self.c_recipe3.create_image(0, 0,anchor="nw", image= self.img_bg_recipe3)
        #---------
        self.img_recipe3 = PhotoImage(file = r"assets/frame0/Nova pasta/button3.png")
        self.button_recipe3 = tk.Button(self.c_recipes, image = self.img_recipe3, command= lambda: controller.show_frame(StartPage), relief="flat", borderwidth=0, highlightthickness=0,activebackground="#182DEF")
        self.button_recipe3.place(x=738, y=16, width=296, height=27)
        #____________________________```

Forever thankful!!


问:
Creating a pipeline with the REST API causes error 400: INVALID_ARGUMENT
I am using a direct call to the Dataflow REST API (https://cloud.google.com/dataflow/docs/reference/data-pipelines/rest/v1/projects.locations.pipelines/create) using the Python requests module to create a pipeline. I have retrieved the definition of an existing, working pipeline as a base, which I modified to create a new, different pipeline. I've double checked all the parameters but I still end up with {'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT'}}
The API doesn't say what argument is invalid. What's going wrong? I'd like to use the proper client library for Python, but for Dataflow it's still in preview and does not support pipeline creation.

This is my code:

body = {'name': 'projects/<project_id>/locations/europe-west1/pipelines/test_name',
 'displayName': 'test_name',
 'type': 'PIPELINE_TYPE_BATCH',
 'state': 'STATE_ACTIVE',
 'workload': {'dataflowFlexTemplateRequest': {'projectId': '<project_id>',
   'launchParameter': {'jobName': 'job_test2',
    'parameters': {'password': '<base64 encoded string>',
     'isTruncate': 'true',
     'useColumnAlias': 'true',
     'serviceAccount': 'censored@censored.iam.gserviceaccount.com',
     'experiments': 'use_runner_v2',
     'driverClassName': 'com.amazon.redshift.jdbc.Driver',
     'connectionProperties': 'autosave=never',
     'workerMachineType': 'n2-highmem-4',
     'bigQueryLoadingTemporaryDirectory': 'gs://censored-temp',
     'connectionURL': '<base64 encoded string>',
     'defaultWorkerLogLevel': 'DEBUG',
     'maxNumWorkers': '2',
     'query': 'select column1 from schema_name.table_name',
     'driverJars': 'gs://censored-assets/redshift-jdbc42-2.1.0.10.jar',
     'username': '<base64 encoded string>',
     'outputTable': '<project_id>:<dataset_name.<table_name>'},
    'containerSpecGcsPath': 'gs://dataflow-templates-europe-west1/latest/flex/Jdbc_to_BigQuery_Flex',
    'environment': {'workerZone': 'europe-west4-a',
     'kmsKeyName': 'projects/<project_id>/locations/global/keyrings/<keyring_id>/<key_id>'}},
   'location': 'europe-west1'}}}

headers = { 'Authorization': f'Bearer {creds.token}',
            'Content-Type': 'application/json; charset=UTF-8'}
response = requests.post(url_create, json=body, headers=headers)
```

Result: {'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT'}}

I've double checked that all the parameter values are correct, and I've also tried removing and changing some, to see if I can pinpoint which one is problematic, to no avail.

Body:
I am using a direct call to the Dataflow REST API (https://cloud.google.com/dataflow/docs/reference/data-pipelines/rest/v1/projects.locations.pipelines/create) using the Python requests module to create a pipeline. I have retrieved the definition of an existing, working pipeline as a base, which I modified to create a new, different pipeline. I've double checked all the parameters but I still end up with {'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT'}}
The API doesn't say what argument is invalid. What's going wrong? I'd like to use the proper client library for Python, but for Dataflow it's still in preview and does not support pipeline creation.

This is my code:

body = {'name': 'projects/<project_id>/locations/europe-west1/pipelines/test_name',
 'displayName': 'test_name',
 'type': 'PIPELINE_TYPE_BATCH',
 'state': 'STATE_ACTIVE',
 'workload': {'dataflowFlexTemplateRequest': {'projectId': '<project_id>',
   'launchParameter': {'jobName': 'job_test2',
    'parameters': {'password': '<base64 encoded string>',
     'isTruncate': 'true',
     'useColumnAlias': 'true',
     'serviceAccount': 'censored@censored.iam.gserviceaccount.com',
     'experiments': 'use_runner_v2',
     'driverClassName': 'com.amazon.redshift.jdbc.Driver',
     'connectionProperties': 'autosave=never',
     'workerMachineType': 'n2-highmem-4',
     'bigQueryLoadingTemporaryDirectory': 'gs://censored-temp',
     'connectionURL': '<base64 encoded string>',
     'defaultWorkerLogLevel': 'DEBUG',
     'maxNumWorkers': '2',
     'query': 'select column1 from schema_name.table_name',
     'driverJars': 'gs://censored-assets/redshift-jdbc42-2.1.0.10.jar',
     'username': '<base64 encoded string>',
     'outputTable': '<project_id>:<dataset_name.<table_name>'},
    'containerSpecGcsPath': 'gs://dataflow-templates-europe-west1/latest/flex/Jdbc_to_BigQuery_Flex',
    'environment': {'workerZone': 'europe-west4-a',
     'kmsKeyName': 'projects/<project_id>/locations/global/keyrings/<keyring_id>/<key_id>'}},
   'location': 'europe-west1'}}}

headers = { 'Authorization': f'Bearer {creds.token}',
            'Content-Type': 'application/json; charset=UTF-8'}
response = requests.post(url_create, json=body, headers=headers)

Result: {'error': {'code': 400, 'message': 'Request contains an invalid argument.', 'status': 'INVALID_ARGUMENT'}}

I've double checked that all the parameter values are correct, and I've also tried removing and changing some, to see if I can pinpoint which one is problematic, to no avail.


问:
CircleCI: job for test using karma
I try to run unit-tests on CI in my project, but for some reason, I get the error Please set env variable CHROME_BIN.

So, I add environment: - CHROME_BIN=/usr/bin/google-chrome, but it still doesn't work. I also try setting the browser to ChromeHeadless in the karma.config file by using config.set({browsers: ['ChromeHeadless']}). Does anyone have an idea what might be the issue?

Here is code of my test job:

```<code>  test:
    docker:
      - image: cimg/node:16.19.0-browsers
        environment:
          - CHROME_BIN=/usr/bin/google-chrome
    steps:
      - checkout
      - run: npm install
      - run:
          command: npm test
</code>```

Here is error from CI:

```<code>#!/bin/bash -eo pipefail
npm test

> api-data@0.0.0 test
> ng test

- Generating browser application bundles (phase: setup)...
✔ Browser application bundle generation complete.
07 01 2023 23:22:42.949:WARN [karma]: No captured browser, open http://localhost:9876/
07 01 2023 23:22:42.959:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/
07 01 2023 23:22:42.959:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
07 01 2023 23:22:42.961:INFO [launcher]: Starting browser Chrome
07 01 2023 23:22:43.020:ERROR [launcher]: Cannot start Chrome
    Can not find the binary /usr/bin/google-chrome
    Please set env variable CHROME_BIN
07 01 2023 23:22:43.020:ERROR [launcher]: Chrome stdout:
07 01 2023 23:22:43.020:ERROR [launcher]: Chrome stderr:
</code>```

Title: CircleCI: job for test using karma

Body:
I try to run unit-tests on CI in my project, but for some reason, I get the error Please set env variable CHROME_BIN.

So, I add environment: - CHROME_BIN=/usr/bin/google-chrome, but it still doesn't work. I also try setting the browser to ChromeHeadless in the karma.config file by using config.set({browsers: ['ChromeHeadless']}). Does anyone have an idea what might be the issue?

Here is code of my test job:

  test:
    docker:
      - image: cimg/node:16.19.0-browsers
        environment:
          - CHROME_BIN=/usr/bin/google-chrome
    steps:
      - checkout
      - run: npm install
      - run:
          command: npm test

Here is error from CI:

#!/bin/bash -eo pipefail
npm test

> api-data@0.0.0 test
> ng test

- Generating browser application bundles (phase: setup)...
✔ Browser application bundle generation complete.
07 01 2023 23:22:42.949:WARN [karma]: No captured browser, open http://localhost:9876/
07 01 2023 23:22:42.959:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/
07 01 2023 23:22:42.959:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
07 01 2023 23:22:42.961:INFO [launcher]: Starting browser Chrome
07 01 2023 23:22:43.020:ERROR [launcher]: Cannot start Chrome
    Can not find the binary /usr/bin/google-chrome
    Please set env variable CHROME_BIN
07 01 2023 23:22:43.020:ERROR [launcher]: Chrome stdout:
07 01 2023 23:22:43.020:ERROR [launcher]: Chrome stderr:


问:
Parallelism with object dependency methods c#
Hi i am trying my best to understand that how task run parallel with object dependency methods.
Example: i have list of case data and I want to loop that parallely. Now in the loop i am calling a rest api to get the data by passing Id. And that api data is begin used in some inner methods to perform some curd. So how should I know that paraell.foreach will is calling restapi parallely and the result of api is correctly passed to inner methods to perform curd.?

I have created a object List()
And in foreach loop added the rest api call method to the task list and i have some more method which are async but it used the result of api data. So should I add those methods also in the list?


问:
Pipx can not build packages when trying to install eth-brownie
I got a following error code while trying to install brownie through pipx (by typing "pipx install eth-brownie)

```<code>PS C:\Users\J.M\demos\brownie_simple_storage> pipx install eth-brownie
Fatal error from pip prevented installation. Full pip output in file:
    C:\Users\J.M\.local\pipx\logs\cmd_2023-01-08_01.26.02_pip_errors.log

pip failed to build packages:
    bitarray
    cytoolz
    lru-dict
    multidict
    psutil
    regex
    yarl

Some possibly relevant errors from pip install:
    error: subprocess-exited-with-error
    error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

Error installing eth-brownie.
PS C:\Users\J.M\demos\brownie_simple_storage>
</code>```

I have all the prerequirements (node.js, recent python version, ganache cli, npm all successfully installed), I really have no idea why it can't build those packages.

Body:
I got a following error code while trying to install brownie through pipx (by typing "pipx install eth-brownie)

PS C:\Users\J.M\demos\brownie_simple_storage> pipx install eth-brownie
Fatal error from pip prevented installation. Full pip output in file:
    C:\Users\J.M\.local\pipx\logs\cmd_2023-01-08_01.26.02_pip_errors.log

pip failed to build packages:
    bitarray
    cytoolz
    lru-dict
    multidict
    psutil
    regex
    yarl

Some possibly relevant errors from pip install:
    error: subprocess-exited-with-error
    error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

Error installing eth-brownie.
PS C:\Users\J.M\demos\brownie_simple_storage>

I have all the prerequirements (node.js, recent python version, ganache cli, npm all successfully installed), I really have no idea why it can't build those packages.


问:
Difference in lifetimes between &i32 and &str in Rust
I'm reading the Rust Handbook chapter about lifetimes https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html

I copied this code

fn main() {
    let r;                // ---------+-- 'a
                          //          |
    {                     //          |
        let x = 5;        // -+-- 'b  |
        r = &x;           //  |       |
    }                     // -+       |
                          //          |
    println!("r: {}", r); //          |
}                         // ---------+
```
<p>which doesn't work because of the difference in the lifetimes between r and x and changed x's type to this</p>
<pre class="lang-rust prettyprint-override"><code>fn main() {
    let r;
    {
        let s = "abc";
        r = s;
    }
    println!("{r}");
}
</code>```

and now it works.

Shouldn't x still be dropped at the end of its scope? Why did that behavior change when x's type is &str?

Body:
I'm reading the Rust Handbook chapter about lifetimes https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html

I copied this code

fn main() {
    let r;                // ---------+-- 'a
                          //          |
    {                     //          |
        let x = 5;        // -+-- 'b  |
        r = &x;           //  |       |
    }                     // -+       |
                          //          |
    println!("r: {}", r); //          |
}                         // ---------+

which doesn't work because of the difference in the lifetimes between r and x and changed x's type to this

fn main() {
    let r;
    {
        let s = "abc";
        r = s;
    }
    println!("{r}");
}

and now it works.

Shouldn't x still be dropped at the end of its scope? Why did that behavior change when x's type is &str?


问:
Github Action - Can't build gtest using ccache, mingw, cmake and ninja
I am using this workflow: cmake_build.yaml

Here is my toplevel CMakeLists.txt:

cmake_minimum_required(VERSION 3.15)

project(
  container
  VERSION 0.1.0
  DESCRIPTION "An extension to the standard container library in c++"
  HOMEPAGE_URL ""
  LANGUAGES CXX
)

add_executable(${PROJECT_NAME} src/main.cpp)

set_target_properties(
  ${PROJECT_NAME}
  PROPERTIES
  LINKER_LANGUAGE CXX
  ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}"
  LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}"
  RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}"
)

target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17)

target_include_directories(
    ${PROJECT_NAME}
    PUBLIC
    $<INSTALL_INTERFACE:include>
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
  )

  install(
  DIRECTORY
  include/${PROJECT_NAME_LOWERCASE}
  DESTINATION
  include
)

enable_testing()

add_subdirectory(test)
```
<p>and test/CMakeLists.txt</p>
<pre class="lang-cmake prettyprint-override"><code>cmake_minimum_required(VERSION 3.14)
project(my_project)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 17)

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)

# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

add_executable(
  hello_test
  hello_test.cc
)
target_link_libraries(
  hello_test
  GTest::gtest_main
)

include(GoogleTest)
gtest_discover_tests(hello_test)

</code>```

I am using the example from gtest docs:

test/hello_test.cc:

#include <gtest/gtest.h>

TEST(HelloTest, BasicAssertions) {
  // Expect two strings not to be equal.
  EXPECT_STRNE("hello", "world");
  // Expect equality.
  EXPECT_EQ(7 * 6, 42);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
```
<p>It builds fine on Windows MSVC, Macos Clang, Linux GCC, but fails using Mingw GCC, here is error shown:</p>
```FAILED: test/hello_test.exe test/hello_test[1]_tests.cmake D:/a/tsst/tsst/build/test/hello_test[1]_tests.cmake
cmd.exe /C "cd . && C:\ProgramData\chocolatey\bin\g++.exe -O3 -DNDEBUG  test/CMakeFiles/hello_test.dir/hello_test.cc.obj -o test\hello_test.exe -Wl,--out-implib,test\libhello_test.dll.a -Wl,--major-image-version,0,--minor-image-version,0  lib/libgtest_main.a  lib/libgtest.a  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cmd.exe /C "cd /D D:\a\tsst\tsst\build\test && D:\a\tsst\tsst\cmake-3.24.3-windows-x86_64\bin\cmake.exe -D TEST_TARGET=hello_test -D TEST_EXECUTABLE=D:/a/tsst/tsst/build/test/hello_test.exe -D TEST_EXECUTOR= -D TEST_WORKING_DIR=D:/a/tsst/tsst/build/test -D TEST_EXTRA_ARGS= -D TEST_PROPERTIES= -D TEST_PREFIX= -D TEST_SUFFIX= -D TEST_FILTER= -D NO_PRETTY_TYPES=FALSE -D NO_PRETTY_VALUES=FALSE -D TEST_LIST=hello_test_TESTS -D CTEST_FILE=D:/a/tsst/tsst/build/test/hello_test[1]_tests.cmake -D TEST_DISCOVERY_TIMEOUT=5 -D TEST_XML_OUTPUT_DIR= -P D:/a/tsst/tsst/cmake-3.24.3-windows-x86_64/share/cmake-3.24/Modules/GoogleTestAddTests.cmake""
CMake Error at D:/a/tsst/tsst/cmake-3.24.3-windows-x86_64/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:112 (message):
  Error running test executable.

    Path: 'D:/a/tsst/tsst/build/test/hello_test.exe'
    Result: Exit code 0xc0000139

    Output:

Call Stack (most recent call first):
  D:/a/tsst/tsst/cmake-3.24.3-windows-x86_64/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:225 (gtest_discover_tests_impl)

ninja: build stopped: subcommand failed.
```

Build works fine without building gtest, and it fails when building test executable with gtest

Body:
I am using this workflow: cmake_build.yaml

Here is my toplevel CMakeLists.txt:

cmake_minimum_required(VERSION 3.15)

project(
  container
  VERSION 0.1.0
  DESCRIPTION "An extension to the standard container library in c++"
  HOMEPAGE_URL ""
  LANGUAGES CXX
)

add_executable(${PROJECT_NAME} src/main.cpp)

set_target_properties(
  ${PROJECT_NAME}
  PROPERTIES
  LINKER_LANGUAGE CXX
  ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}"
  LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}"
  RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/${CMAKE_BUILD_TYPE}"
)

target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17)

target_include_directories(
    ${PROJECT_NAME}
    PUBLIC
    $<INSTALL_INTERFACE:include>
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
  )

  install(
  DIRECTORY
  include/${PROJECT_NAME_LOWERCASE}
  DESTINATION
  include
)

enable_testing()

add_subdirectory(test)

and test/CMakeLists.txt

cmake_minimum_required(VERSION 3.14)
project(my_project)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 17)

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)

# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

add_executable(
  hello_test
  hello_test.cc
)
target_link_libraries(
  hello_test
  GTest::gtest_main
)

include(GoogleTest)
gtest_discover_tests(hello_test)

I am using the example from gtest docs:

test/hello_test.cc:

#include <gtest/gtest.h>

TEST(HelloTest, BasicAssertions) {
  // Expect two strings not to be equal.
  EXPECT_STRNE("hello", "world");
  // Expect equality.
  EXPECT_EQ(7 * 6, 42);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

It builds fine on Windows MSVC, Macos Clang, Linux GCC, but fails using Mingw GCC, here is error shown:

FAILED: test/hello_test.exe test/hello_test[1]_tests.cmake D:/a/tsst/tsst/build/test/hello_test[1]_tests.cmake
cmd.exe /C "cd . && C:\ProgramData\chocolatey\bin\g++.exe -O3 -DNDEBUG  test/CMakeFiles/hello_test.dir/hello_test.cc.obj -o test\hello_test.exe -Wl,--out-implib,test\libhello_test.dll.a -Wl,--major-image-version,0,--minor-image-version,0  lib/libgtest_main.a  lib/libgtest.a  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cmd.exe /C "cd /D D:\a\tsst\tsst\build\test && D:\a\tsst\tsst\cmake-3.24.3-windows-x86_64\bin\cmake.exe -D TEST_TARGET=hello_test -D TEST_EXECUTABLE=D:/a/tsst/tsst/build/test/hello_test.exe -D TEST_EXECUTOR= -D TEST_WORKING_DIR=D:/a/tsst/tsst/build/test -D TEST_EXTRA_ARGS= -D TEST_PROPERTIES= -D TEST_PREFIX= -D TEST_SUFFIX= -D TEST_FILTER= -D NO_PRETTY_TYPES=FALSE -D NO_PRETTY_VALUES=FALSE -D TEST_LIST=hello_test_TESTS -D CTEST_FILE=D:/a/tsst/tsst/build/test/hello_test[1]_tests.cmake -D TEST_DISCOVERY_TIMEOUT=5 -D TEST_XML_OUTPUT_DIR= -P D:/a/tsst/tsst/cmake-3.24.3-windows-x86_64/share/cmake-3.24/Modules/GoogleTestAddTests.cmake""
CMake Error at D:/a/tsst/tsst/cmake-3.24.3-windows-x86_64/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:112 (message):
  Error running test executable.

    Path: 'D:/a/tsst/tsst/build/test/hello_test.exe'
    Result: Exit code 0xc0000139

    Output:

Call Stack (most recent call first):
  D:/a/tsst/tsst/cmake-3.24.3-windows-x86_64/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:225 (gtest_discover_tests_impl)

ninja: build stopped: subcommand failed.

Build works fine without building gtest, and it fails when building test executable with gtest


问:
iOS: 4.2 or lower must include ARM6 object code?

Possible Duplicate:

  How to build for armv6 and armv7 architectures with iOS 5

I need to build a library and executable that will be installable on both iPhone 3 and iPhone 3gs & later. I guess the iPhone 3 has an arm6 processor and later devices have arm7. However when I try to build for later devices with Build for Active Architectures Only to set No, which would produce an arm6+arm7 binary, the build doesn't complete, because it rejects the library.

Is there a way to get Xcode to build for both arm6 and arm7 without complaints?

Thanks.

ContentLicense: CC BY-SA 3.0


问:
docplex maximize problem with multiple knapsack problem
```<code>import numpy as np
from docplex.mp.model import Model
rnd = np.random
rnd.seed(1995)

#Number of Objects

N = 12
M = 3

#Gnerate the list of objects indices

Obj = [j for j in range(0, N)]
Knap = [i for i in range(0, M)]

print(Obj)
print(Knap)

#Generate objects weights and save them in W list

W = rnd.randint(5, 50, size=N)
print(W)

#Generate objects profits and save them in P list

P = rnd.randint(10, 100, size=N)
print(P)

#Knapsack Capacity

C = rnd.randint(1, 5, size=M)   ### different of m capisties

print(C)

#Create the model

mdl = Model('MKP')

#Define decision variables

x = mdl.binary_var_matrix(Obj,M, name='x')

print(x)

#Add objective function

mdl.maximize(mdl.sum(P[j]*x[j] for j in Obj))

## mdl.maximize(mdl.sum(P[i]*x[j][i] for i in Knap))

#Add capacity constraint

mdl.add_constraints(mdl.sum(W[j]*x[j] for j in Obj) <= C[i] for i in Knap)
mdl.add_constraints(mdl.sum(x[j][i] for i in Knap) <= 1 for j in Obj)

#Write the model on lp file

mdl.export_as_lp("./mkp.lp")

#Define the cpu time limit

mdl.parameters.timelimit = 300

#Solve the model

solution = mdl.solve(log_output=True)

#Print the solution status

print(solution.solve_status)

#Print the solution

print(solution)
</code>```

Well, how about adding more details. Like, what are you trying to accomplish, how are you doing it, what difficulties you have found with the approach, another approaches you have tried, etc. In summary, without code isn't a good question neither is with just code. Search for the balance!

this is output how can i solve this maximize problem

```<code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[0, 1, 2]
[41 23 43 10 34 25 33  6 16 14 40 11]
[59 73 50 89 74 66 22 62 42 40 27 10]
[3 2 3]
{(0, 0): docplex.mp.Var(type=B,name='x_0_0'), (0, 1): docplex.mp.Var(type=B,name='x_0_1'), (0, 2): docplex.mp.Var(type=B,name='x_0_2'), (1, 0): docplex.mp.Var(type=B,name='x_1_0'), (1, 1): docplex.mp.Var(type=B,name='x_1_1'), (1, 2): docplex.mp.Var(type=B,name='x_1_2'), (2, 0): docplex.mp.Var(type=B,name='x_2_0'), (2, 1): docplex.mp.Var(type=B,name='x_2_1'), (2, 2): docplex.mp.Var(type=B,name='x_2_2'), (3, 0): docplex.mp.Var(type=B,name='x_3_0'), (3, 1): docplex.mp.Var(type=B,name='x_3_1'), (3, 2): docplex.mp.Var(type=B,name='x_3_2'), (4, 0): docplex.mp.Var(type=B,name='x_4_0'), (4, 1): docplex.mp.Var(type=B,name='x_4_1'), (4, 2): docplex.mp.Var(type=B,name='x_4_2'), (5,
0): docplex.mp.Var(type=B,name='x_5_0'), (5, 1): docplex.mp.Var(type=B,name='x_5_1'), (5, 2): docplex.mp.Var(type=B,name='x_5_2'), (6, 0): docplex.mp.Var(type=B,name='x_6_0'), (6, 1): docplex.mp.Var(type=B,name='x_6_1'), (6, 2): docplex.mp.Var(type=B,name='x_6_2'), (7, 0): docplex.mp.Var(type=B,name='x_7_0'), (7, 1): docplex.mp.Var(type=B,name='x_7_1'), (7, 2): docplex.mp.Var(type=B,name='x_7_2'), (8, 0): docplex.mp.Var(type=B,name='x_8_0'), (8, 1): docplex.mp.Var(type=B,name='x_8_1'), (8, 2): docplex.mp.Var(type=B,name='x_8_2'), (9, 0): docplex.mp.Var(type=B,name='x_9_0'), (9, 1): docplex.mp.Var(type=B,name='x_9_1'), (9, 2): docplex.mp.Var(type=B,name='x_9_2'), (10, 0):
docplex.mp.Var(type=B,name='x_10_0'), (10, 1): docplex.mp.Var(type=B,name='x_10_1'),
(10, 2): docplex.mp.Var(type=B,name='x_10_2'), (11, 0): docplex.mp.Var(type=B,name='x_11_0'), (11, 1): docplex.mp.Var(type=B,name='x_11_1'), (11, 2): docplex.mp.Var(type=B,name='x_11_2')}
Traceback (most recent call last):
  File "c:/Users/User/Downloads/Mmmmkp.py", line 49, in <module>
    mdl.maximize(mdl.sum(P[j]*x[j] for j in Obj))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\docplex\mp\model.py", line 2845, in sum
    return self._aggregator.sum(args)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\docplex\mp\aggregator.py", line 176, in sum
    sum_res = self._sum_with_iter(sum_args)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\docplex\mp\aggregator.py", line 199, in _sum_with_iter
    for item in args:
  File "c:/Users/User/Downloads/Mmmmkp.py", line 49, in <genexpr>
    mdl.maximize(mdl.sum(P[j]*x[j] for j in Obj))
KeyError: 0
</code>```

Body:
import numpy as np
from docplex.mp.model import Model
rnd = np.random
rnd.seed(1995)

#Number of Objects

N = 12
M = 3

#Gnerate the list of objects indices

Obj = [j for j in range(0, N)]
Knap = [i for i in range(0, M)]

print(Obj)
print(Knap)

#Generate objects weights and save them in W list

W = rnd.randint(5, 50, size=N)
print(W)

#Generate objects profits and save them in P list

P = rnd.randint(10, 100, size=N)
print(P)

#Knapsack Capacity

C = rnd.randint(1, 5, size=M)   ### different of m capisties

print(C)

#Create the model

mdl = Model('MKP')

#Define decision variables

x = mdl.binary_var_matrix(Obj,M, name='x')

print(x)

#Add objective function

mdl.maximize(mdl.sum(P[j]*x[j] for j in Obj))

## mdl.maximize(mdl.sum(P[i]*x[j][i] for i in Knap))

#Add capacity constraint

mdl.add_constraints(mdl.sum(W[j]*x[j] for j in Obj) <= C[i] for i in Knap)
mdl.add_constraints(mdl.sum(x[j][i] for i in Knap) <= 1 for j in Obj)

#Write the model on lp file

mdl.export_as_lp("./mkp.lp")

#Define the cpu time limit

mdl.parameters.timelimit = 300

#Solve the model

solution = mdl.solve(log_output=True)

#Print the solution status

print(solution.solve_status)

#Print the solution

print(solution)

Well, how about adding more details. Like, what are you trying to accomplish, how are you doing it, what difficulties you have found with the approach, another approaches you have tried, etc. In summary, without code isn't a good question neither is with just code. Search for the balance!

this is output how can i solve this maximize problem

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[0, 1, 2]
[41 23 43 10 34 25 33  6 16 14 40 11]
[59 73 50 89 74 66 22 62 42 40 27 10]
[3 2 3]
{(0, 0): docplex.mp.Var(type=B,name='x_0_0'), (0, 1): docplex.mp.Var(type=B,name='x_0_1'), (0, 2): docplex.mp.Var(type=B,name='x_0_2'), (1, 0): docplex.mp.Var(type=B,name='x_1_0'), (1, 1): docplex.mp.Var(type=B,name='x_1_1'), (1, 2): docplex.mp.Var(type=B,name='x_1_2'), (2, 0): docplex.mp.Var(type=B,name='x_2_0'), (2, 1): docplex.mp.Var(type=B,name='x_2_1'), (2, 2): docplex.mp.Var(type=B,name='x_2_2'), (3, 0): docplex.mp.Var(type=B,name='x_3_0'), (3, 1): docplex.mp.Var(type=B,name='x_3_1'), (3, 2): docplex.mp.Var(type=B,name='x_3_2'), (4, 0): docplex.mp.Var(type=B,name='x_4_0'), (4, 1): docplex.mp.Var(type=B,name='x_4_1'), (4, 2): docplex.mp.Var(type=B,name='x_4_2'), (5,
0): docplex.mp.Var(type=B,name='x_5_0'), (5, 1): docplex.mp.Var(type=B,name='x_5_1'), (5, 2): docplex.mp.Var(type=B,name='x_5_2'), (6, 0): docplex.mp.Var(type=B,name='x_6_0'), (6, 1): docplex.mp.Var(type=B,name='x_6_1'), (6, 2): docplex.mp.Var(type=B,name='x_6_2'), (7, 0): docplex.mp.Var(type=B,name='x_7_0'), (7, 1): docplex.mp.Var(type=B,name='x_7_1'), (7, 2): docplex.mp.Var(type=B,name='x_7_2'), (8, 0): docplex.mp.Var(type=B,name='x_8_0'), (8, 1): docplex.mp.Var(type=B,name='x_8_1'), (8, 2): docplex.mp.Var(type=B,name='x_8_2'), (9, 0): docplex.mp.Var(type=B,name='x_9_0'), (9, 1): docplex.mp.Var(type=B,name='x_9_1'), (9, 2): docplex.mp.Var(type=B,name='x_9_2'), (10, 0):
docplex.mp.Var(type=B,name='x_10_0'), (10, 1): docplex.mp.Var(type=B,name='x_10_1'),
(10, 2): docplex.mp.Var(type=B,name='x_10_2'), (11, 0): docplex.mp.Var(type=B,name='x_11_0'), (11, 1): docplex.mp.Var(type=B,name='x_11_1'), (11, 2): docplex.mp.Var(type=B,name='x_11_2')}
Traceback (most recent call last):
  File "c:/Users/User/Downloads/Mmmmkp.py", line 49, in <module>
    mdl.maximize(mdl.sum(P[j]*x[j] for j in Obj))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\docplex\mp\model.py", line 2845, in sum
    return self._aggregator.sum(args)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\docplex\mp\aggregator.py", line 176, in sum
    sum_res = self._sum_with_iter(sum_args)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\docplex\mp\aggregator.py", line 199, in _sum_with_iter
    for item in args:
  File "c:/Users/User/Downloads/Mmmmkp.py", line 49, in <genexpr>
    mdl.maximize(mdl.sum(P[j]*x[j] for j in Obj))
KeyError: 0


问:
GULP.js: three single tasks works fine in stand alone but leads to unexpected results in gulp.series()
I would like to implement a build and watch job with automated testing via gulp.js.
New for me is the integration of a typescript compiler and the testing of frontend javascript in node.js.
For this I have coded three tasks:

compiling the typescript files into frontend javascript files

compiling the backend javascript test files using jsdom and amd-loader

running the unit tests

If I execute the tasks one by one, everything works as intended.
But if I run all three in gulp.series() after a code change, the next task does not grap the result of the previous task but to the state before the gulp.series call.
A TS change overwrites JS version 1 with JS version 2 in the build task.
The following buildUnitTests task, however, still uses JS version 1.

This is not the case with the watcher, where all changes are recognised by all tasks. But here I have the problem that every change triggers the execution of the unitTestings task and with the termination of the task the Watcher is also terminated:

```<code>[hh:mm:ss] The following tasks did not complete: watch, watch
[hh:mm:ss] Did you forget to signal async completion?
</code>```

Well, the unit tests in the watcher are also a drag on performance and probably belong more in the release task - only there it doesn't work as desired yet.
What to do so that the tasks are processed one after the other, but the view to the changed files is updated between the tasks?

This is the file structure:

```<code>dev
|_ js
|_|_ customElements
|_|_|_ callbackBrookerExtesion.js
|_|
|_|_ looselyConnected
|_|_|_ stringifiedReferenceHandler
|_|_|_|_ require.js
|_|_|_|_ set.js
|_|_|
|_|_|_ callbackBrooker.js
|_|_|_ fileManager.js
|_|_|_ stringifiedReferenceHandler.js

gulp
|_ tasks
|_|_ script.js
|
|_ config.js
|_ index.js

test
|_ config
|_|_ unitTests.json
|
|_ templates
|_|_ exports.js
|_|_ looselyConnected.js
|_|_ prepare.js
|
|_ unittests
|_|_ spec
|_|_|_ looselyConnected
|_|_|_|_ callbackBrooker
|_|_|_|_|_ pull.spec.js
|_|_|_|_|_ push.spec.js
|_|
|_|_ src
|_|_|_ // the unit tests for custom elements are in progress
|_|_|_ looselyConnected.js

TS
|_ client
|_|_ customElements
|_|_|_ callbackBrookerExtesion.ts
|_|_|_ tsCallbackBrookerExtesionConfig.json
|_|
|_|_ looselyConnected
|_|_|_ stringifiedReferenceHandler
|_|_|_|_ require.ts
|_|_|_|_ set.jts
|_|_|
|_|_|_ callbackBrooker.ts
|_|_|_ fileManager.ts
|_|_|_ looselyConnected.d.ts
|_|_|_ stringifiedReferenceHandler.ts
|_|
|_|_ tsBaseConfig.json
|
|_ tsconfig
|_|_ customElements.json
|_|_ looselyConnected.json

gulpfile.js
</code>```

gulp/index.js:

const gulp = require("gulp");
const scripts = require("./tasks/scripts");

gulp.task("default",
    gulp.series(
        scripts.build,
        scripts.buildUnitTests,
        scripts.unitTesting
    )
);

gulp.task("build",
    gulp.series(
        scripts.build
    )
);

gulp.task("buildUnitTests",
    gulp.series(
        scripts.buildUnitTests
    )
);

gulp.task("unitTesting",
    gulp.series(
        scripts.unitTesting
    )
);

gulp.task("watch",
    gulp.series(
        scripts.watch
    )
);```
</div>
</div>
</p>
<p>gulp/config.js
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>exports.unitTests = {
    looselyConnected: {
        files: [
            "./test/templates/prepare.js",
            "./test/templates/looselyConnected.js",
            "./dev/js/looselyConnected/callbackBroker.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler.js",
            "./dev/js/looselyConnected/fileManager.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler/require.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler/set.js",
            "./test/templates/exports.js"
        ],
        name: 'looselyConnected.js',
        dest: './test/unittests/src',
        watch: [
            "./TS/client/looselyConnected/**/*",
            "./TS/client/looselyConnected/looselyConnected.d.ts",
            "./TS/client/customElements/**/*"
        ],
        specs: [
            "test/unittests/src/looselyConnected.js",
            "test/unittests/spec/looselyConnected/callbackBroker/push.spec.js",
            "test/unittests/spec/looselyConnected/callbackBroker/pull.spec.js"
        ]
    }
}</code>```

gulp/tasks/script.js

const gulp = require("gulp");
const ts = require("gulp-typescript");
const concat = require('gulp-concat');
const Jasmine = require('jasmine');
const jasmine = new Jasmine();
const reporters = require('jasmine-reporters');
const config = require('../config');

const buildScript = cb => {
    let tsProject = ts.createProject("tsconfig/looselyConnected.json");
    tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("./dev/js/looselyConnected"));
    tsProject = ts.createProject("tsconfig/customElements.json");
    tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("./dev/js/customElements"));
    return cb();
};

const unitTesting = cb => {
    jasmine.loadConfigFile('./test/config/unitTests.json');
    jasmine.addReporter(new reporters.JUnitXmlReporter());
    jasmine.execute(config.unitTests.looselyConnected.specs);
    return cb();
}

const buildUnitTests = cb => {
    let tests = config.unitTests;
    for (i in tests) {
        let test = tests[i];
        gulp.src(test.files)
            .pipe(concat(test.name))
            .pipe(gulp.dest(test.dest));
    }
    return cb();
}

const watch = () => {
    let confLC = config.unitTests.looselyConnected;
    gulp.watch(confLC.watch, buildScript);
    gulp.watch(confLC.files, buildUnitTests);
    //gulp.watch(confLC.specs, unitTesting); -> this will quit the watcher after every change
}

module.exports = {
    build: buildScript,
    buildUnitTests: buildUnitTests,
    unitTesting: unitTesting,
    watch: watch,
};```

Body:
I would like to implement a build and watch job with automated testing via gulp.js.
New for me is the integration of a typescript compiler and the testing of frontend javascript in node.js.
For this I have coded three tasks:

compiling the typescript files into frontend javascript files

compiling the backend javascript test files using jsdom and amd-loader

running the unit tests

If I execute the tasks one by one, everything works as intended.
But if I run all three in gulp.series() after a code change, the next task does not grap the result of the previous task but to the state before the gulp.series call.
A TS change overwrites JS version 1 with JS version 2 in the build task.
The following buildUnitTests task, however, still uses JS version 1.

This is not the case with the watcher, where all changes are recognised by all tasks. But here I have the problem that every change triggers the execution of the unitTestings task and with the termination of the task the Watcher is also terminated:

[hh:mm:ss] The following tasks did not complete: watch, watch
[hh:mm:ss] Did you forget to signal async completion?

Well, the unit tests in the watcher are also a drag on performance and probably belong more in the release task - only there it doesn't work as desired yet.
What to do so that the tasks are processed one after the other, but the view to the changed files is updated between the tasks?

This is the file structure:

dev
|_ js
|_|_ customElements
|_|_|_ callbackBrookerExtesion.js
|_|
|_|_ looselyConnected
|_|_|_ stringifiedReferenceHandler
|_|_|_|_ require.js
|_|_|_|_ set.js
|_|_|
|_|_|_ callbackBrooker.js
|_|_|_ fileManager.js
|_|_|_ stringifiedReferenceHandler.js

gulp
|_ tasks
|_|_ script.js
|
|_ config.js
|_ index.js

test
|_ config
|_|_ unitTests.json
|
|_ templates
|_|_ exports.js
|_|_ looselyConnected.js
|_|_ prepare.js
|
|_ unittests
|_|_ spec
|_|_|_ looselyConnected
|_|_|_|_ callbackBrooker
|_|_|_|_|_ pull.spec.js
|_|_|_|_|_ push.spec.js
|_|
|_|_ src
|_|_|_ // the unit tests for custom elements are in progress
|_|_|_ looselyConnected.js

TS
|_ client
|_|_ customElements
|_|_|_ callbackBrookerExtesion.ts
|_|_|_ tsCallbackBrookerExtesionConfig.json
|_|
|_|_ looselyConnected
|_|_|_ stringifiedReferenceHandler
|_|_|_|_ require.ts
|_|_|_|_ set.jts
|_|_|
|_|_|_ callbackBrooker.ts
|_|_|_ fileManager.ts
|_|_|_ looselyConnected.d.ts
|_|_|_ stringifiedReferenceHandler.ts
|_|
|_|_ tsBaseConfig.json
|
|_ tsconfig
|_|_ customElements.json
|_|_ looselyConnected.json

gulpfile.js

gulp/index.js:

const gulp = require("gulp");
const scripts = require("./tasks/scripts");

gulp.task("default",
    gulp.series(
        scripts.build,
        scripts.buildUnitTests,
        scripts.unitTesting
    )
);

gulp.task("build",
    gulp.series(
        scripts.build
    )
);

gulp.task("buildUnitTests",
    gulp.series(
        scripts.buildUnitTests
    )
);

gulp.task("unitTesting",
    gulp.series(
        scripts.unitTesting
    )
);

gulp.task("watch",
    gulp.series(
        scripts.watch
    )
);

gulp/config.js

exports.unitTests = {
    looselyConnected: {
        files: [
            "./test/templates/prepare.js",
            "./test/templates/looselyConnected.js",
            "./dev/js/looselyConnected/callbackBroker.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler.js",
            "./dev/js/looselyConnected/fileManager.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler/require.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler/set.js",
            "./test/templates/exports.js"
        ],
        name: 'looselyConnected.js',
        dest: './test/unittests/src',
        watch: [
            "./TS/client/looselyConnected/**/*",
            "./TS/client/looselyConnected/looselyConnected.d.ts",
            "./TS/client/customElements/**/*"
        ],
        specs: [
            "test/unittests/src/looselyConnected.js",
            "test/unittests/spec/looselyConnected/callbackBroker/push.spec.js",
            "test/unittests/spec/looselyConnected/callbackBroker/pull.spec.js"
        ]
    }
}

gulp/tasks/script.js

const gulp = require("gulp");
const ts = require("gulp-typescript");
const concat = require('gulp-concat');
const Jasmine = require('jasmine');
const jasmine = new Jasmine();
const reporters = require('jasmine-reporters');
const config = require('../config');

const buildScript = cb => {
    let tsProject = ts.createProject("tsconfig/looselyConnected.json");
    tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("./dev/js/looselyConnected"));
    tsProject = ts.createProject("tsconfig/customElements.json");
    tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("./dev/js/customElements"));
    return cb();
};

const unitTesting = cb => {
    jasmine.loadConfigFile('./test/config/unitTests.json');
    jasmine.addReporter(new reporters.JUnitXmlReporter());
    jasmine.execute(config.unitTests.looselyConnected.specs);
    return cb();
}

const buildUnitTests = cb => {
    let tests = config.unitTests;
    for (i in tests) {
        let test = tests[i];
        gulp.src(test.files)
            .pipe(concat(test.name))
            .pipe(gulp.dest(test.dest));
    }
    return cb();
}

const watch = () => {
    let confLC = config.unitTests.looselyConnected;
    gulp.watch(confLC.watch, buildScript);
    gulp.watch(confLC.files, buildUnitTests);
    //gulp.watch(confLC.specs, unitTesting); -> this will quit the watcher after every change
}

module.exports = {
    build: buildScript,
    buildUnitTests: buildUnitTests,
    unitTesting: unitTesting,
    watch: watch,
};


问:
Quering `IntegrationEventLogs` on `eshopOnContainters` throws Execution Timeout Expired on SQL Server
When I have > 6000 IntergrationEnventLogs records in the database and I hit this line:

```<code>var result = await _integrationEventLogContext.IntegrationEventLogs
            .Where(e => e.TransactionId == tid && e.State == EventStateEnum.NotPublished).ToListAsync();
</code>```

as part of the normal execution.

I get the following error and stack trace:

```<code>Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
 ---> System.ComponentModel.Win32Exception (258): The wait operation timed out.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__208_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at IFMS.GMT.BuildingBlocks.IntegrationEventLogEF.Services.IntegrationEventLogService.RetrieveEventLogsPendingToPublishAsync(Guid transactionId) in D:\repos\IntegratedFleetManagementSystem.GMT\src\BuildingBlocks\BuildingBlocks.IntegrationEventLogEF\Services\IntegrationEventLogService.cs:line 38
   at IFMS.GMT.Services.VehicleManagement.WebAPI.Application.IntegrationEvents.VehicleManagementIntegrationEventService.PublishEventsThroughEventBusAsync(Guid transactionId) in D:\repos\IntegratedFleetManagementSystem.GMT\src\Services\VehicleManagement\VehicleManagement.WebAPI\Application\IntegrationEvents\VehicleManagementIntegrationEventService.cs:line 38
   at IFMS.GMT.Services.VehicleManagement.WebAPI.Application.Behaviors.TransactionBehaviour`2.<>c__DisplayClass4_0.<<Handle>b__0>d.MoveNext() in D:\repos\IntegratedFleetManagementSystem.GMT\src\Services\VehicleManagement\VehicleManagement.WebAPI\Application\Behaviors\TransactionBehaviour.cs:line 61
--- End of stack trace from previous location ---
</code>```

Is this query slow? (if so are there any recommendations on how to improve it) because I tried to create an Index for TransactionId but still no changes.

Or my machine together with SQL Server instance its running

Body:
When I have > 6000 IntergrationEnventLogs records in the database and I hit this line:

var result = await _integrationEventLogContext.IntegrationEventLogs
            .Where(e => e.TransactionId == tid && e.State == EventStateEnum.NotPublished).ToListAsync();

as part of the normal execution.

I get the following error and stack trace:

Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
 ---> System.ComponentModel.Win32Exception (258): The wait operation timed out.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__208_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at IFMS.GMT.BuildingBlocks.IntegrationEventLogEF.Services.IntegrationEventLogService.RetrieveEventLogsPendingToPublishAsync(Guid transactionId) in D:\repos\IntegratedFleetManagementSystem.GMT\src\BuildingBlocks\BuildingBlocks.IntegrationEventLogEF\Services\IntegrationEventLogService.cs:line 38
   at IFMS.GMT.Services.VehicleManagement.WebAPI.Application.IntegrationEvents.VehicleManagementIntegrationEventService.PublishEventsThroughEventBusAsync(Guid transactionId) in D:\repos\IntegratedFleetManagementSystem.GMT\src\Services\VehicleManagement\VehicleManagement.WebAPI\Application\IntegrationEvents\VehicleManagementIntegrationEventService.cs:line 38
   at IFMS.GMT.Services.VehicleManagement.WebAPI.Application.Behaviors.TransactionBehaviour`2.<>c__DisplayClass4_0.<<Handle>b__0>d.MoveNext() in D:\repos\IntegratedFleetManagementSystem.GMT\src\Services\VehicleManagement\VehicleManagement.WebAPI\Application\Behaviors\TransactionBehaviour.cs:line 61
--- End of stack trace from previous location ---

Is this query slow? (if so are there any recommendations on how to improve it) because I tried to create an Index for TransactionId but still no changes.

Or my machine together with SQL Server instance its running


问:
How to enable/disable cookies programmatically for IE
I'd like to turn on cookies programmatically using a script or C# code. This needs to work at least for IE8 and IE9. Is there a way to do that. Is it a registry setting? Is there an API to do it?

I believe it is a per user setting, so ideally it would change the setting for the user the script/process is executing under.


问:
Detect wether a component is a ChildView or a ContentView
Is there a way to detect wether a component is a ChildView or a ContentView of a parent ?

I don't think there is a public API for that but maybe it's accessible somewhere in the ViewRef/ChangeDetectorRef