问:
Compare Contract Settings Goerli on Etherscan
I recently took over a project from another developer who has been uncooperative in providing assistance. The project includes a contract deployed on the Rinkeby network and a decentralized exchange (DEX) developed for it. Users were able to test the DEX using our own platform, with liquidity added via the Uniswap interface. The contract includes the Uniswap V2Router contract to fetch liquidity and use it on our DEX. I have completed all necessary web3 setup, including changing the RPC port to 5 and adding the correct URL.

No error so far on my console.

SITE FOR REFERENCE: https://doxastaking.netlify.app/, It is deployed on GOERLI ETHER.

Recently, I migrated the project to the Goerli network. However, since the migration, I have not been able to purchase tokens using our DEX. Transactions go through, but the equivalent tokens are not assigned to my wallet. It is unclear to me whether the issue is with the contract or the web3 setup.

The web3 swap code:

import React, { Component } from "react";
import eth from "../../assets/eth.png";
import transfer from "../../assets/transfer.png";
import buyLoader from "../../assets/doxa-ico-loader.gif";
import { connect } from "react-redux";
import { connectWallet } from '../../redux/WalletAction';
import miniLogo from "../../assets/logo.png";
import "./scss/bs.css";

class Buydoxa extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '0',
      doxaValue: 0
    }
  }

  componentDidMount() {
    const { web3Modal } = this.props.wallet
    if (web3Modal.cachedProvider) {
      this.props.connectWallet();
    }
  }

  connectToWallet = async () => {
    await this.props.connectWallet();
  }

  buyToken = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const id = queryParams.get('email');

    let inputValue = parseFloat(this.state.inputValue);

    if (inputValue >= 0.00001 && inputValue <= 10) {
      const { web3, doxa, wallet, address } = this.props.wallet;
      const value = this.state.inputValue.toString();
      const buyValue = web3.utils.toWei(value, 'ether');
      const tokenPrice = web3.utils.toWei('0.00001', 'ether');
      const totalTokens = (web3.utils.toBN(buyValue).div(web3.utils.toBN(tokenPrice))).toString();
      try {
        this.setState({ loading: true })

        const res = await wallet.methods.swapEthToDoxa(id).send({ from: address, value: buyValue });

        this.setState({ loading: false })

      } catch (err) {
        this.setState({ loading: false })

        if (err.message) {
          alert(err.message)
        } else {
          alert("Something went wrong!")
        }
      }
    } else {
      alert("ETH should be between 0.00001 and 10");
      return
    }
  }

  updateInputValue = async (e) => {
    let totalTokens;
    if (e.target.value != '') {
      totalTokens = parseFloat(e.target.value) / 0.00001;
    }
    this.setState({
      inputValue: e.target.value,
      doxaValue: totalTokens
    });
  }

  render() {
    return (

swap your crypto

              Enter ETH
              <input type="number" value={this.state.inputValue} onChange={e => this.updateInputValue(e)} />

ETH

          {/* image */}

{this.state.doxaValue}

DOXAZO

          {/* btn */}
          <button className="bs-btn" disabled={this.state.loading} onClick={() => this.props.wallet.connected ? this.buyToken() : this.connectToWallet()}>{this.props.wallet.connected ? this.state.loading ?
            Processing
          : 'Buy' : 'PROCEED TO SWAP'}</button>

    );
  }
}

const mapStateToProps = state => ({
  wallet: state.walletConnect
});

export default connect(mapStateToProps, { connectWallet })(Buydoxa);
```
<p>My Wallet Action.js Codes:</p>
<pre class="lang-js prettyprint-override"><code>// constants
import Web3 from "web3";
import Web3Modal from "web3modal";
import WalletConnectProvider from "@walletconnect/web3-provider";
import contract from "../contracts/staking.json";
import tokenContract from "../contracts/token.json";
import walletContract from "../contracts/wallet.json";
import store from './store';

const connectRequest = () => {
  return {
    type: "CONNECTION_REQUEST",
  };
};

export const disconnectRequest = () => {
  return {
    type: "DISCONNECT"
  };
}

export const connectSuccess = (payload) => {
  return {
    type: "CONNECTION_SUCCESS",
    payload: payload,
  };
};

const connectFailed = (payload) => {
  return {
    type: "CONNECTION_FAILED",
    payload: payload,
  };
};

export const updateAccountRequest = (payload) => {
  return {
    type: "UPDATE_ADDRESS",
    payload: payload,
  };
};

const getProviderOptions = () => {
    const providerOptions = {
      walletconnect: {
        package: WalletConnectProvider,
        options: {
          rpc: {
            5: "https://goerli.infura.io/v3/ea95b0776037479abf7a62fc14b55188",
            1: "https://mainnet.infura.io/v3/ea95b0776037479abf7a62fc14b55188"
          }
        }
      },
    }
    return providerOptions;
}

export const connectWallet = () => {
    return async(dispatch) => {
        dispatch(connectRequest());
        try {
            const web3Modal = new Web3Modal({
              cacheProvider: true,
                providerOptions: getProviderOptions() // required
            });

            const provider = await web3Modal.connect();
            const stakingContractAddress = process.env.REACT_APP_DOXACONTRACT_ADDRESS;
            const internalWalletAddress = process.env.REACT_APP_WALLET_ADDRESS;
            const TokencontractAddress = process.env.REACT_APP_TOKEN_ADDRESS;

            await subscribeProvider(provider, dispatch);

            const web3 = new Web3(provider);

            web3.eth.extend({
              methods: [
                {
                  name: "chainId",
                  call: "eth_chainId",
                  outputFormatter: web3.utils.hexToNumber
                }
              ]
            });

            const accounts = await web3.eth.getAccounts();
            const address = accounts[0];

            const instance = new web3.eth.Contract(
              contract,
              stakingContractAddress
            );
            const tokenInstance = new web3.eth.Contract(
              tokenContract,
              TokencontractAddress
            )

            const walletInstance = new web3.eth.Contract(
              walletContract,
              internalWalletAddress
            )

            if(window.ethereum && window.ethereum.networkVersion !== '5') {
              await addNetwork(5);
            }
            dispatch(
              connectSuccess({
                  address,
                  web3,
                  staking: instance,
                  token: tokenInstance,
                  wallet: walletInstance,
                  provider,
                  connected: true,
                  web3Modal
              })
            );
        } catch (e) {
            dispatch(connectFailed(e));
        }
    }
}

export const disconnect = () => {
  return async(dispatch)=> {
    const { web3Modal } = store.getState().walletConnect;
    console.log(web3Modal);
    web3Modal.clearCachedProvider();
    dispatch(disconnectRequest());
  }
}

const subscribeProvider = async(provider) => {
  if (!provider.on) {
    return;
  }

  provider.on('connect', async(id) => {
    console.log(id);
  });

  provider.on("networkChanged", async (networkId) => {
    if(networkId !== '5') {
      console.log(networkId);
      await store.dispatch(connectFailed('Please switch to Ethereum mainnet'));
      addNetwork(5);
    } else {
      store.dispatch(connectWallet());
    }
  });
}

export async function addNetwork(id) {
let networkData;
switch (id) {
  //bsctestnet
  case 5:
    networkData = [
      {
        chainId: "0x4",
      },
    ];

    break;
  //bscmainet
  case 1:
    networkData = [
      {
        chainId: "0x1",
      },
    ];
    break;
  default:
    break;
}
return window.ethereum.request({
  method: "wallet_switchEthereumChain",
  params: networkData,
});
}

(() => {
if(window.ethereum) {
  window.ethereum.on('networkChanged', async function(networkId){
    console.log('network change', networkId);
    if(networkId !== '5') {
      console.log(networkId);
      await store.dispatch(connectFailed('Please switch to Binance mainnet'));
      addNetwork(5);
    } else {
      store.dispatch(connectWallet());
    }
  });
}
})();

</code>```

The following are the contract and wallet addresses for my Goerli deployments:

Token Address: https://goerli.etherscan.io/address/0x0f0283E1aC1f465cE2076a1F57EA0f1BAb4DDC21

Wallet Address Proxy: https://goerli.etherscan.io/address/0xdF6046711651AEC0d686F12Ed0039d5aC45517f3

The following are the contract and wallet addresses for the previous developer's Rinkeby deployments:

Token deployed by other developer on Rinkeby network: https://rinkeby.etherscan.io/address/0xD99b4BB049a6Dd490901CDfa33F15C4fAc097EF0

The wallet proxy deployed on Rinkeby: https://rinkeby.etherscan.io/address/0x5309E16fc58Dc900a08d92BE6559758D692f39Bb

Body:
I recently took over a project from another developer who has been uncooperative in providing assistance. The project includes a contract deployed on the Rinkeby network and a decentralized exchange (DEX) developed for it. Users were able to test the DEX using our own platform, with liquidity added via the Uniswap interface. The contract includes the Uniswap V2Router contract to fetch liquidity and use it on our DEX. I have completed all necessary web3 setup, including changing the RPC port to 5 and adding the correct URL.

No error so far on my console.

SITE FOR REFERENCE: https://doxastaking.netlify.app/, It is deployed on GOERLI ETHER.

Recently, I migrated the project to the Goerli network. However, since the migration, I have not been able to purchase tokens using our DEX. Transactions go through, but the equivalent tokens are not assigned to my wallet. It is unclear to me whether the issue is with the contract or the web3 setup.

The web3 swap code:

import React, { Component } from "react";
import eth from "../../assets/eth.png";
import transfer from "../../assets/transfer.png";
import buyLoader from "../../assets/doxa-ico-loader.gif";
import { connect } from "react-redux";
import { connectWallet } from '../../redux/WalletAction';
import miniLogo from "../../assets/logo.png";
import "./scss/bs.css";

class Buydoxa extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '0',
      doxaValue: 0
    }
  }

  componentDidMount() {
    const { web3Modal } = this.props.wallet
    if (web3Modal.cachedProvider) {
      this.props.connectWallet();
    }
  }

  connectToWallet = async () => {
    await this.props.connectWallet();
  }

  buyToken = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const id = queryParams.get('email');

    let inputValue = parseFloat(this.state.inputValue);

    if (inputValue >= 0.00001 && inputValue <= 10) {
      const { web3, doxa, wallet, address } = this.props.wallet;
      const value = this.state.inputValue.toString();
      const buyValue = web3.utils.toWei(value, 'ether');
      const tokenPrice = web3.utils.toWei('0.00001', 'ether');
      const totalTokens = (web3.utils.toBN(buyValue).div(web3.utils.toBN(tokenPrice))).toString();
      try {
        this.setState({ loading: true })

        const res = await wallet.methods.swapEthToDoxa(id).send({ from: address, value: buyValue });

        this.setState({ loading: false })

      } catch (err) {
        this.setState({ loading: false })

        if (err.message) {
          alert(err.message)
        } else {
          alert("Something went wrong!")
        }
      }
    } else {
      alert("ETH should be between 0.00001 and 10");
      return
    }
  }

  updateInputValue = async (e) => {
    let totalTokens;
    if (e.target.value != '') {
      totalTokens = parseFloat(e.target.value) / 0.00001;
    }
    this.setState({
      inputValue: e.target.value,
      doxaValue: totalTokens
    });
  }

  render() {
    return (

swap your crypto

              Enter ETH
              <input type="number" value={this.state.inputValue} onChange={e => this.updateInputValue(e)} />

ETH

          {/* image */}

{this.state.doxaValue}

DOXAZO

          {/* btn */}
          <button className="bs-btn" disabled={this.state.loading} onClick={() => this.props.wallet.connected ? this.buyToken() : this.connectToWallet()}>{this.props.wallet.connected ? this.state.loading ?
            Processing
          : 'Buy' : 'PROCEED TO SWAP'}</button>

    );
  }
}

const mapStateToProps = state => ({
  wallet: state.walletConnect
});

export default connect(mapStateToProps, { connectWallet })(Buydoxa);

My Wallet Action.js Codes:

// constants
import Web3 from "web3";
import Web3Modal from "web3modal";
import WalletConnectProvider from "@walletconnect/web3-provider";
import contract from "../contracts/staking.json";
import tokenContract from "../contracts/token.json";
import walletContract from "../contracts/wallet.json";
import store from './store';

const connectRequest = () => {
  return {
    type: "CONNECTION_REQUEST",
  };
};

export const disconnectRequest = () => {
  return {
    type: "DISCONNECT"
  };
}

export const connectSuccess = (payload) => {
  return {
    type: "CONNECTION_SUCCESS",
    payload: payload,
  };
};

const connectFailed = (payload) => {
  return {
    type: "CONNECTION_FAILED",
    payload: payload,
  };
};

export const updateAccountRequest = (payload) => {
  return {
    type: "UPDATE_ADDRESS",
    payload: payload,
  };
};

const getProviderOptions = () => {
    const providerOptions = {
      walletconnect: {
        package: WalletConnectProvider,
        options: {
          rpc: {
            5: "https://goerli.infura.io/v3/ea95b0776037479abf7a62fc14b55188",
            1: "https://mainnet.infura.io/v3/ea95b0776037479abf7a62fc14b55188"
          }
        }
      },
    }
    return providerOptions;
}

export const connectWallet = () => {
    return async(dispatch) => {
        dispatch(connectRequest());
        try {
            const web3Modal = new Web3Modal({
              cacheProvider: true,
                providerOptions: getProviderOptions() // required
            });

            const provider = await web3Modal.connect();
            const stakingContractAddress = process.env.REACT_APP_DOXACONTRACT_ADDRESS;
            const internalWalletAddress = process.env.REACT_APP_WALLET_ADDRESS;
            const TokencontractAddress = process.env.REACT_APP_TOKEN_ADDRESS;

            await subscribeProvider(provider, dispatch);

            const web3 = new Web3(provider);

            web3.eth.extend({
              methods: [
                {
                  name: "chainId",
                  call: "eth_chainId",
                  outputFormatter: web3.utils.hexToNumber
                }
              ]
            });

            const accounts = await web3.eth.getAccounts();
            const address = accounts[0];

            const instance = new web3.eth.Contract(
              contract,
              stakingContractAddress
            );
            const tokenInstance = new web3.eth.Contract(
              tokenContract,
              TokencontractAddress
            )

            const walletInstance = new web3.eth.Contract(
              walletContract,
              internalWalletAddress
            )

            if(window.ethereum && window.ethereum.networkVersion !== '5') {
              await addNetwork(5);
            }
            dispatch(
              connectSuccess({
                  address,
                  web3,
                  staking: instance,
                  token: tokenInstance,
                  wallet: walletInstance,
                  provider,
                  connected: true,
                  web3Modal
              })
            );
        } catch (e) {
            dispatch(connectFailed(e));
        }
    }
}

export const disconnect = () => {
  return async(dispatch)=> {
    const { web3Modal } = store.getState().walletConnect;
    console.log(web3Modal);
    web3Modal.clearCachedProvider();
    dispatch(disconnectRequest());
  }
}

const subscribeProvider = async(provider) => {
  if (!provider.on) {
    return;
  }

  provider.on('connect', async(id) => {
    console.log(id);
  });

  provider.on("networkChanged", async (networkId) => {
    if(networkId !== '5') {
      console.log(networkId);
      await store.dispatch(connectFailed('Please switch to Ethereum mainnet'));
      addNetwork(5);
    } else {
      store.dispatch(connectWallet());
    }
  });
}

export async function addNetwork(id) {
let networkData;
switch (id) {
  //bsctestnet
  case 5:
    networkData = [
      {
        chainId: "0x4",
      },
    ];

    break;
  //bscmainet
  case 1:
    networkData = [
      {
        chainId: "0x1",
      },
    ];
    break;
  default:
    break;
}
return window.ethereum.request({
  method: "wallet_switchEthereumChain",
  params: networkData,
});
}

(() => {
if(window.ethereum) {
  window.ethereum.on('networkChanged', async function(networkId){
    console.log('network change', networkId);
    if(networkId !== '5') {
      console.log(networkId);
      await store.dispatch(connectFailed('Please switch to Binance mainnet'));
      addNetwork(5);
    } else {
      store.dispatch(connectWallet());
    }
  });
}
})();

The following are the contract and wallet addresses for my Goerli deployments:

Token Address: https://goerli.etherscan.io/address/0x0f0283E1aC1f465cE2076a1F57EA0f1BAb4DDC21

Wallet Address Proxy: https://goerli.etherscan.io/address/0xdF6046711651AEC0d686F12Ed0039d5aC45517f3

The following are the contract and wallet addresses for the previous developer's Rinkeby deployments:

Token deployed by other developer on Rinkeby network: https://rinkeby.etherscan.io/address/0xD99b4BB049a6Dd490901CDfa33F15C4fAc097EF0

The wallet proxy deployed on Rinkeby: https://rinkeby.etherscan.io/address/0x5309E16fc58Dc900a08d92BE6559758D692f39Bb


来源: stackexchange

问:
Django OAuth Authentication
I built an app (Django backend, React frontend) that whenever a client login it will generate JWT authentication. React will store the access token and client can use it to access Django backend database.
Then I want to add in social login feature (Google) so I will get back access token from that as well. However, this access token is different from the JWT access token generated before, so I wonder how can I integrate both ways of logging in a user smoothly on both Django and React?

For JWT I use djangorestframework-simplejwt
For social login I use django-allauth

I can run each individual way perfectly on React, but I don't know how to keep both the installations of JWT and allauth in Django settings.

ContentLicense: CC BY-SA 4.0

Title: Django OAuth Authentication


问:
UI Kitten Theme Switch Causes Flicker
I am building an app with UI kitten and Expo. I am facing a very strange issue with switching theme. On any kind of onPress() event it works perfectly fine but as soon as I use Toggle() from UI kitten and try switching theme with onChange() the theme flickers between light and dark twice before switching to required theme. Here is my code:

```<code>const [darkMode, setDarkMode] = React.useState();

const toggleTheme = () => {
    themeContext.toggleTheme();
    setDarkMode(!darkMode);
}

return (
    <View>
        {/* Some Code */}
        <Toggle checked={darkMode} disabled={loading} status='basic' onChange={toggleTheme} checkedIcon={checkIcon}/>
        {/* Some More Code */}
    </View>
)
</code>```

I can't understand what could possibly be wrong here. There are no re-renders that might cause this behavior. While the buttons are working accurately, the toggles show this behavior.

Title: UI Kitten Theme Switch Causes Flicker

Body:
I am building an app with UI kitten and Expo. I am facing a very strange issue with switching theme. On any kind of onPress() event it works perfectly fine but as soon as I use Toggle() from UI kitten and try switching theme with onChange() the theme flickers between light and dark twice before switching to required theme. Here is my code:

const [darkMode, setDarkMode] = React.useState();

const toggleTheme = () => {
    themeContext.toggleTheme();
    setDarkMode(!darkMode);
}

return (
    <View>
        {/* Some Code */}
        <Toggle checked={darkMode} disabled={loading} status='basic' onChange={toggleTheme} checkedIcon={checkIcon}/>
        {/* Some More Code */}
    </View>
)

I can't understand what could possibly be wrong here. There are no re-renders that might cause this behavior. While the buttons are working accurately, the toggles show this behavior.


问:
How to convert python to 100% pyspark?
```<code>from sklearn.datasets import make_blobs
from pyspark.sql import types as T, SparkSession
</code>```

Here I create an array with sklearn and pure python. This array has two columns with float type values.

```<code>X, labels_true = make_blobs(
    n_samples=750, centers=centers,
    cluster_std=0.4, random_state=5
)
</code>```

Then I use loops to format the data and create an id.

```<code>data = [
    (i, [float(item) for item in X[i]])
    for i in range(X.shape[0])
]
</code>```

Then I define a schema, which has the id and an array of floats containing the two columns generated by make_blobs. And I turn it into dataframe spark.

```<code>schema = T.StructType([
    T.StructField("id", T.IntegerType(), False),
    T.StructField("value", T.ArrayType(T.FloatType()), False)
])

df = spark.createDataFrame(data, schema=schema).repartition(10)
</code>```

If instead of generating the data array with make_blobs, I had a spark dataframe with the same information, how to get the same final result?

How to run the code below in a pyspark dataframe?

```<code>data = [
    (i, [float(item) for item in X[i]])
    for i in range(X.shape[0])
]
</code>```

Title: How to convert python to 100% pyspark?

Body:
from sklearn.datasets import make_blobs
from pyspark.sql import types as T, SparkSession

Here I create an array with sklearn and pure python. This array has two columns with float type values.

X, labels_true = make_blobs(
    n_samples=750, centers=centers,
    cluster_std=0.4, random_state=5
)

Then I use loops to format the data and create an id.

data = [
    (i, [float(item) for item in X[i]])
    for i in range(X.shape[0])
]

Then I define a schema, which has the id and an array of floats containing the two columns generated by make_blobs. And I turn it into dataframe spark.

schema = T.StructType([
    T.StructField("id", T.IntegerType(), False),
    T.StructField("value", T.ArrayType(T.FloatType()), False)
])

df = spark.createDataFrame(data, schema=schema).repartition(10)

If instead of generating the data array with make_blobs, I had a spark dataframe with the same information, how to get the same final result?

How to run the code below in a pyspark dataframe?

data = [
    (i, [float(item) for item in X[i]])
    for i in range(X.shape[0])
]


问:
Docker compose Amazon ECS
As I am quite familiar with docker compose and not so familiar with amazons cloudformation I found it extremely nice to be able to basically run your docker compose files via ecs integration and viola behind the scenes everything you need is created for you. So you get your load balancer (if not already created) and your ecs cluster with your services running and everything is connected and just works. When I started wanting to do a bit more advanced things I ran into a problem that I can't seem to find an answer to online.

I have 2 services in my docker compose, my spring boot web app and my postgres db. I wanted to implement ssl and redirect all traffic to https. After a lot of research and a lot of trial and error I finally got it to work by extending my compose file with x-aws-cloudformation and adding native cloudformation yaml. When doing all of this I was forced to choose an application load balancer over a network load balancer as it operates on layer 7 (http/https). However my problem is that now I have no way of reaching my postgres database and running queries against it via for example intellij. My spring boot app works find and can read/write to my database so that works fine. Before the whole ssl implementation I didn't specify a load balancer in my compose file and so it gave me a network load balancer every time I ran my compose file. Then I could connect to my database via intellij and run queries. I have tried adding an inbound rule on my security group that basically allows all inbound traffic to my database via 5432 but that didn't help. I may not be setting the correct host when applying my connection details in intellij but I have tried using the following:

dns name of load balancer

ip-adress of load balancer

public ip of my postgres db task (launch type: fargate)

I would just like to simply reach my database and run queries against it even though it is running inside aws ecs cluster behind an application load balancer. Is there a way of achieving what I am trying to do? Or do I have to have 2 separate load balancers (one application LB and one network LB)?

Here is my docker-compose file(I have omitted a few irrelevant env variables):

```<code>version: "3.9"

x-aws-loadbalancer: arn:my-application-load-balancer

services:
  my-web-app:
    build:
      context: .
    image: hub/my-web-app
    x-aws-pull_credentials: xxxxxxxx
    container_name: my-app-name
    ports:
      - "80:80"
    networks:
      - my-app-network
    depends_on:
      - postgres
    deploy:
      replicas: 1
      resources:
        limits:
          cpus: '0.5'
          memory: 2048M
    environment:
      - SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/my-db?currentSchema=my-db_schema
      - SPRING_DATASOURCE_USERNAME=dbpass
      - SPRING_DATASOURCE_PASSWORD=dbpass
      - SPRING_DATASOURCE_DRIVER-CLASS-NAME=org.postgresql.Driver
      - SPRING_JPA_DATABASE_PLATFORM=org.hibernate.dialect.PostgreSQLDialect

  postgres:
    build:
      context: docker/database
    image: hub/my-db
    container_name: my-db
    networks:
      - my-app-network
    deploy:
      replicas: 1
      resources:
        limits:
          cpus: '0.5'
          memory: 2048M
    environment:
      - POSTGRES_USER=dbpass
      - POSTGRES_PASSWORD=dbpass
      - POSTGRES_DB=my-db

networks:
  my-app-network:
    name: my-app-network

x-aws-cloudformation:
  Resources:
    MyWebAppTCP80TargetGroup:
      Properties:
        HealthCheckPath: /actuator/health
        Matcher:
          HttpCode: 200-499
    MyWebAppTCP80Listener:
      Type: AWS::ElasticLoadBalancingV2::Listener
      Properties:
        Protocol: HTTP
        Port: 80
        LoadBalancerArn: xxxxx
        DefaultActions:
          - Type: redirect
            RedirectConfig:
              Port: 443
              Host: "#{host}"
              Path: "/#{path}"
              Query: "#{query}"
              Protocol: HTTPS
              StatusCode: HTTP_301
    MyWebAppTCP443Listener:
      Type: AWS::ElasticLoadBalancingV2::Listener
      Properties:
        Protocol: HTTPS
        Port: 443
        LoadBalancerArn: xxxxxxxxx
        Certificates:
          - CertificateArn: "xxxxxxxxxx"
        DefaultActions:
          - Type: forward
            ForwardConfig:
              TargetGroups:
                - TargetGroupArn:
                    Ref: MyWebAppTCP80TargetGroup
    MyWebAppTCP80RedirectRule:
      Type: AWS::ElasticLoadBalancingV2::ListenerRule
      Properties:
        ListenerArn:
          Ref: MyWebAppTCP80Listener
        Priority: 1
        Conditions:
          - Field: host-header
            HostHeaderConfig:
              Values:
                - "*.my-app.com"
                - "www.my-app.com"
                - "my-app.com"
        Actions:
          - Type: redirect
            RedirectConfig:
              Host: "#{host}"
              Path: "/#{path}"
              Query: "#{query}"
              Port: 443
              Protocol: HTTPS
              StatusCode: HTTP_301

</code>```

Title: Docker compose Amazon ECS

Body:
As I am quite familiar with docker compose and not so familiar with amazons cloudformation I found it extremely nice to be able to basically run your docker compose files via ecs integration and viola behind the scenes everything you need is created for you. So you get your load balancer (if not already created) and your ecs cluster with your services running and everything is connected and just works. When I started wanting to do a bit more advanced things I ran into a problem that I can't seem to find an answer to online.

I have 2 services in my docker compose, my spring boot web app and my postgres db. I wanted to implement ssl and redirect all traffic to https. After a lot of research and a lot of trial and error I finally got it to work by extending my compose file with x-aws-cloudformation and adding native cloudformation yaml. When doing all of this I was forced to choose an application load balancer over a network load balancer as it operates on layer 7 (http/https). However my problem is that now I have no way of reaching my postgres database and running queries against it via for example intellij. My spring boot app works find and can read/write to my database so that works fine. Before the whole ssl implementation I didn't specify a load balancer in my compose file and so it gave me a network load balancer every time I ran my compose file. Then I could connect to my database via intellij and run queries. I have tried adding an inbound rule on my security group that basically allows all inbound traffic to my database via 5432 but that didn't help. I may not be setting the correct host when applying my connection details in intellij but I have tried using the following:

dns name of load balancer

ip-adress of load balancer

public ip of my postgres db task (launch type: fargate)

I would just like to simply reach my database and run queries against it even though it is running inside aws ecs cluster behind an application load balancer. Is there a way of achieving what I am trying to do? Or do I have to have 2 separate load balancers (one application LB and one network LB)?

Here is my docker-compose file(I have omitted a few irrelevant env variables):

version: "3.9"

x-aws-loadbalancer: arn:my-application-load-balancer

services:
  my-web-app:
    build:
      context: .
    image: hub/my-web-app
    x-aws-pull_credentials: xxxxxxxx
    container_name: my-app-name
    ports:
      - "80:80"
    networks:
      - my-app-network
    depends_on:
      - postgres
    deploy:
      replicas: 1
      resources:
        limits:
          cpus: '0.5'
          memory: 2048M
    environment:
      - SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/my-db?currentSchema=my-db_schema
      - SPRING_DATASOURCE_USERNAME=dbpass
      - SPRING_DATASOURCE_PASSWORD=dbpass
      - SPRING_DATASOURCE_DRIVER-CLASS-NAME=org.postgresql.Driver
      - SPRING_JPA_DATABASE_PLATFORM=org.hibernate.dialect.PostgreSQLDialect

  postgres:
    build:
      context: docker/database
    image: hub/my-db
    container_name: my-db
    networks:
      - my-app-network
    deploy:
      replicas: 1
      resources:
        limits:
          cpus: '0.5'
          memory: 2048M
    environment:
      - POSTGRES_USER=dbpass
      - POSTGRES_PASSWORD=dbpass
      - POSTGRES_DB=my-db

networks:
  my-app-network:
    name: my-app-network

x-aws-cloudformation:
  Resources:
    MyWebAppTCP80TargetGroup:
      Properties:
        HealthCheckPath: /actuator/health
        Matcher:
          HttpCode: 200-499
    MyWebAppTCP80Listener:
      Type: AWS::ElasticLoadBalancingV2::Listener
      Properties:
        Protocol: HTTP
        Port: 80
        LoadBalancerArn: xxxxx
        DefaultActions:
          - Type: redirect
            RedirectConfig:
              Port: 443
              Host: "#{host}"
              Path: "/#{path}"
              Query: "#{query}"
              Protocol: HTTPS
              StatusCode: HTTP_301
    MyWebAppTCP443Listener:
      Type: AWS::ElasticLoadBalancingV2::Listener
      Properties:
        Protocol: HTTPS
        Port: 443
        LoadBalancerArn: xxxxxxxxx
        Certificates:
          - CertificateArn: "xxxxxxxxxx"
        DefaultActions:
          - Type: forward
            ForwardConfig:
              TargetGroups:
                - TargetGroupArn:
                    Ref: MyWebAppTCP80TargetGroup
    MyWebAppTCP80RedirectRule:
      Type: AWS::ElasticLoadBalancingV2::ListenerRule
      Properties:
        ListenerArn:
          Ref: MyWebAppTCP80Listener
        Priority: 1
        Conditions:
          - Field: host-header
            HostHeaderConfig:
              Values:
                - "*.my-app.com"
                - "www.my-app.com"
                - "my-app.com"
        Actions:
          - Type: redirect
            RedirectConfig:
              Host: "#{host}"
              Path: "/#{path}"
              Query: "#{query}"
              Port: 443
              Protocol: HTTPS
              StatusCode: HTTP_301


问:
422 Unprocessable Entity POST
I am making a POST request with DirectX Backbuffer copy of a character. It's basically a screenshot that is cropped and sent over HTTPS. Here is the C++ code using httplib.h (with SSL) in my game client that is triggered on login and logout:

```<code>#ifdef __AZURIOM_IMAGES
    if (m_Azuriom_SaveAvatar) {
        LPCSTR token = g_dpCertified.GetAzuriomAccessToken();
        IDirect3DSurface9* pDestTarget;
        CRect rectCtrl;
        rectCtrl.top = this->m_rectClient.top + lpFace->rect.top;
        rectCtrl.bottom = this->m_rectClient.top + lpFace->rect.bottom;
        rectCtrl.left = this->m_rectClient.left + lpFace->rect.left;
        rectCtrl.right = this->m_rectClient.left + lpFace->rect.right;
        pd3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_FORCE_DWORD, &pDestTarget);
        LPD3DXBUFFER buffer;
        D3DXSaveSurfaceToFileInMemory(&buffer, D3DXIFF_PNG, pDestTarget, NULL, &rectCtrl);
        httplib::SSLClient cli(AZURIOM_WEBSITE, AZURIOM_WEBSITE_PORT);
        httplib::Headers headers = {
            { "Content-Type", "multipart/form-data"},
            { "Accept", "application/json"}
        };
        httplib::MultipartFormDataItems items = {
            { "access_token", token},
            { "avatar", std::string((char*)buffer->GetBufferPointer(), buffer->GetBufferSize()), pMover->GetName(), "image/png"},
            { "playerName", pMover->GetName()}
        };
        auto res = cli.Post("/api/flyff/upload_avatar", headers, items);
        std::cout << res;
        buffer->Release();
        m_Azuriom_SaveAvatar = FALSE;
    }
#endif
</code>```

I go to my apache2 Logs and see this in the access.log file when I Login and out of the game:

```<code>192.168.1.2 - - [21/Dec/2022:12:22:05 -0600] "POST /api/flyff/upload_avatar HTTP/1.1" 422 42
</code>```

I go to debug the game...this is what I get in the debugger:

```<code>-       headers { size=2 }  std::multimap<std::string,std::string,httplib::detail::ci,std::allocator<std::pair<std::string const ,std::string>>>
+       [comparator]    {...}   std::_Compressed_pair<httplib::detail::ci,std::_Compressed_pair<std::allocator<std::_Tree_node<std::pair<std::string const ,std::string>,void *>>,std::_Tree_val<std::_Tree_simple_types<std::pair<std::string const ,std::string>>>,1>,1>
+       [allocator] allocator   std::_Compressed_pair<std::allocator<std::_Tree_node<std::pair<std::string const ,std::string>,void *>>,std::_Tree_val<std::_Tree_simple_types<std::pair<std::string const ,std::string>>>,1>
+       ["Accept"]  "application/json"  std::pair<std::string const ,std::string>
+       ["Content-Type"]    "multipart/form-data"   std::pair<std::string const ,std::string>
+       [Raw View]  {...}   std::multimap<std::string,std::string,httplib::detail::ci,std::allocator<std::pair<std::string const ,std::string>>>
-       items   { size=3 }  std::vector<httplib::MultipartFormData,std::allocator<httplib::MultipartFormData>>
        [capacity]  3   unsigned int
+       [allocator] allocator   std::_Compressed_pair<std::allocator<httplib::MultipartFormData>,std::_Vector_val<std::_Simple_types<httplib::MultipartFormData>>,1>
+       [0] {name="access_token" content="" filename="" ...}    httplib::MultipartFormData
+       [1] {name="avatar" content="臼NG\r\n\x1a\n" filename="Ling" ...} httplib::MultipartFormData
+       [2] {name="playerName" content="Ling" filename="" ...}  httplib::MultipartFormData
+       [Raw View]  {_Mypair=allocator }    std::vector<httplib::MultipartFormData,std::allocator<httplib::MultipartFormData>>

</code>```

I want to make this 422 error go away...and just upload the image.

Title: 422 Unprocessable Entity POST

Body:
I am making a POST request with DirectX Backbuffer copy of a character. It's basically a screenshot that is cropped and sent over HTTPS. Here is the C++ code using httplib.h (with SSL) in my game client that is triggered on login and logout:

#ifdef __AZURIOM_IMAGES
    if (m_Azuriom_SaveAvatar) {
        LPCSTR token = g_dpCertified.GetAzuriomAccessToken();
        IDirect3DSurface9* pDestTarget;
        CRect rectCtrl;
        rectCtrl.top = this->m_rectClient.top + lpFace->rect.top;
        rectCtrl.bottom = this->m_rectClient.top + lpFace->rect.bottom;
        rectCtrl.left = this->m_rectClient.left + lpFace->rect.left;
        rectCtrl.right = this->m_rectClient.left + lpFace->rect.right;
        pd3dDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_FORCE_DWORD, &pDestTarget);
        LPD3DXBUFFER buffer;
        D3DXSaveSurfaceToFileInMemory(&buffer, D3DXIFF_PNG, pDestTarget, NULL, &rectCtrl);
        httplib::SSLClient cli(AZURIOM_WEBSITE, AZURIOM_WEBSITE_PORT);
        httplib::Headers headers = {
            { "Content-Type", "multipart/form-data"},
            { "Accept", "application/json"}
        };
        httplib::MultipartFormDataItems items = {
            { "access_token", token},
            { "avatar", std::string((char*)buffer->GetBufferPointer(), buffer->GetBufferSize()), pMover->GetName(), "image/png"},
            { "playerName", pMover->GetName()}
        };
        auto res = cli.Post("/api/flyff/upload_avatar", headers, items);
        std::cout << res;
        buffer->Release();
        m_Azuriom_SaveAvatar = FALSE;
    }
#endif

I go to my apache2 Logs and see this in the access.log file when I Login and out of the game:

192.168.1.2 - - [21/Dec/2022:12:22:05 -0600] "POST /api/flyff/upload_avatar HTTP/1.1" 422 42

I go to debug the game...this is what I get in the debugger:

-       headers { size=2 }  std::multimap<std::string,std::string,httplib::detail::ci,std::allocator<std::pair<std::string const ,std::string>>>
+       [comparator]    {...}   std::_Compressed_pair<httplib::detail::ci,std::_Compressed_pair<std::allocator<std::_Tree_node<std::pair<std::string const ,std::string>,void *>>,std::_Tree_val<std::_Tree_simple_types<std::pair<std::string const ,std::string>>>,1>,1>
+       [allocator] allocator   std::_Compressed_pair<std::allocator<std::_Tree_node<std::pair<std::string const ,std::string>,void *>>,std::_Tree_val<std::_Tree_simple_types<std::pair<std::string const ,std::string>>>,1>
+       ["Accept"]  "application/json"  std::pair<std::string const ,std::string>
+       ["Content-Type"]    "multipart/form-data"   std::pair<std::string const ,std::string>
+       [Raw View]  {...}   std::multimap<std::string,std::string,httplib::detail::ci,std::allocator<std::pair<std::string const ,std::string>>>
-       items   { size=3 }  std::vector<httplib::MultipartFormData,std::allocator<httplib::MultipartFormData>>
        [capacity]  3   unsigned int
+       [allocator] allocator   std::_Compressed_pair<std::allocator<httplib::MultipartFormData>,std::_Vector_val<std::_Simple_types<httplib::MultipartFormData>>,1>
+       [0] {name="access_token" content="" filename="" ...}    httplib::MultipartFormData
+       [1] {name="avatar" content="臼NG\r\n\x1a\n" filename="Ling" ...} httplib::MultipartFormData
+       [2] {name="playerName" content="Ling" filename="" ...}  httplib::MultipartFormData
+       [Raw View]  {_Mypair=allocator }    std::vector<httplib::MultipartFormData,std::allocator<httplib::MultipartFormData>>

I want to make this 422 error go away...and just upload the image.


问:
Github composite action - docker limitation
I'm using a github custom composite action, and this action build and image and then run it,

here is the link for the action (and the Dockerfile)
https://github.com/convictional/trigger-workflow-and-wait

The problem is that i'm hitting a docker limitation about pulling from dockerhub without being authentication
enter image description here

I tried to look for a way to authenticate to dockerhub with my user but can't seem to find a way to do it

Is there any way to authenticate before using the composite action ? to prevent the pull limit from occuring

I tried to authenticate in a step before the use of the action but this didn't work because the build of the image is the first step executed in the job, so my authentication will be ignored

I tried to authenticate in a job before the job where i use the action nad then (cache/artifact) the config.json file but it didn't work, I still have the rate limit


问:
Unable to change exposure settings for CSI Pi Camera on Raspberry Pi 64 bit Bullseye
Tried varying the expsoure settings for the Pi CSI based camera using libcamera library in python.
Tried out multiple methods which did not lead to successful implementation.

Unable to vary exposure using the following example code:

```<code>        cam.set(libcamera.AeEnable, 0)
        cam.set(libcamera.ExposureValue, 4)
        cam.set(libcamera.ExposureTime, 100000)
        cam.set(libcamera.AnalogueGain, -0.1)
</code>```

Experienced no change in exposure when varying the above settings over libcamera.

But I was successful in varying the brightness using the following command:

```<code>cam.set(libcamera.Brightness, -1)
</code>```

I also tried  using the PiCamera library and experienced the following error:

OSError: libmmal.so: cannot open shared object file: No such file or directory

Found that the community has already faced similar problems.
The posts shared that the above library is not present in 64 bit os.

I also tried sudo modprobe bcm2835-v4l2 inorder to have the CSI camera detected as a device allowing it to be accessed using OpenCV since several blog posts shared this procedure as a possibility.

The camera was not picked up over OpenCV and returned nothing.
Blog
Hackster Blog

Body:
Tried varying the expsoure settings for the Pi CSI based camera using libcamera library in python.
Tried out multiple methods which did not lead to successful implementation.

Unable to vary exposure using the following example code:

        cam.set(libcamera.AeEnable, 0)
        cam.set(libcamera.ExposureValue, 4)
        cam.set(libcamera.ExposureTime, 100000)
        cam.set(libcamera.AnalogueGain, -0.1)

Experienced no change in exposure when varying the above settings over libcamera.

But I was successful in varying the brightness using the following command:

cam.set(libcamera.Brightness, -1)

I also tried  using the PiCamera library and experienced the following error:

OSError: libmmal.so: cannot open shared object file: No such file or directory

Found that the community has already faced similar problems.
The posts shared that the above library is not present in 64 bit os.

I also tried sudo modprobe bcm2835-v4l2 inorder to have the CSI camera detected as a device allowing it to be accessed using OpenCV since several blog posts shared this procedure as a possibility.

The camera was not picked up over OpenCV and returned nothing.
Blog
Hackster Blog


问:
React Native - CardinalComm SDK 60 Warning Template
We recently received warning from google regarding the data collection issue(See the screenshot).

screenshot

Based on some posts from braintree, upgrading the android SDK to the latest version(6.5.0) should resolve this issue. But we are using react native and implemented braintree dropin with a dependence whose owner is no longer maintain this library.

Does anyone implemented braintree dropin on react native have successfully solve this google warning?


问:
I'm having trouble getting sticky and rounded corners to work together in vue 3 js, using tailwind css
I have a table which a toggle button above it to toggle between the condensed view of the table, and the full view of the table. I would like to have both rounded corners and sticky headers so both tables have the same feel, and the headers remain visible when the user scrolls down. And my condensed view of the table has both sticky headers and rounded corners. However, in my full view of the table, I have to take overflow-x-auto and overflow-hidden out to use sticky headers, which works but causes my table to have pointed corners. If I leave both overflow code in, then sticky doesn't work, but my table has rounded corners. How can I do this and have both in the full view of my table?</p>
```<code><div class="mt-4 flex flex-col">
        <div class="-my-2 -mx-4 sm:-mx-6 lg:-mx-8">
          <div class="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
            <div class="w-full flex justify-center shadow ring-1 ring-black ring-opacity-5 md:rounded lg">
              <table class="min-w-full border-separate divide-y divide-gray-200" style="border-spacing:0">
                <thead class="bg-blue-600">
                  <tr class="divide-x divide-gray-200">
                    <th
                      scope="col"
                      class="w-1/3 px-3 py-3.5 text-center text-sm font-semibold text-white"
                      style="position:sticky; top:85px; background:#1e345d;"
                    >
                      Column 1
                    </th>
                    <th
                      scope="col"
                      class="w-1/2 px-3 py-3.5 text-center text-sm font-semibold text-white"
                      style="position:sticky; top:85px; background:#1e345d;"
                    >
                      Column 2
                    </th>
                    <th
                      scope="col"
                      class="w-1/4 px-3 py-3.5 text-center text-sm font-semibold text-white"
                      style="position:sticky; top:85px; background:#1e345d;"
                    >
                      Column 3
                    </th>
                  </tr>
                </thead>
</code>```

Body:
I have a table which a toggle button above it to toggle between the condensed view of the table, and the full view of the table. I would like to have both rounded corners and sticky headers so both tables have the same feel, and the headers remain visible when the user scrolls down. And my condensed view of the table has both sticky headers and rounded corners. However, in my full view of the table, I have to take overflow-x-auto and overflow-hidden out to use sticky headers, which works but causes my table to have pointed corners. If I leave both overflow code in, then sticky doesn't work, but my table has rounded corners. How can I do this and have both in the full view of my table?

                      Column 1

                      Column 2

                      Column 3


问:
GitHub Actions - Upload Artifact Failed: Unable to get local issuer certificate
We are using self-hosted runners (Windows) for GitHub actions. Recently, our company changed the proxy. We have updated the System Environment Variables to the new proxy, and we have updated the proxy details in .env file as suggested by GitHub documentation. And we have added the Root CA in the Windows Certificate Manager (Certificates - Local Computer -> Trusted Root Certification Authorities -> Certificates). But when uploading the artifact during workflow run, we got the below error message and workflow is failing.

Create Artifact Container - Attempt 1 of 5 failed with error: unable to get local issuer certificate

Error: Create Artifact Container failed: unable to get local issuer certificate
##[debug]Node Action run completed with exit code 1

How can we resolve this error? Is there anything that should be changed in runner configuration?


问:
Would it be good to create a wrapper class when using condition_variable?
I see a common pattern when using condition_variable to let one thread wait for another thread to finish some work:

Define a condition, a mutex, and a condition_variable:

```<code>bool workDone = false;
std::mutex mutex;
std::condition_variable cv;
</code>```

In one thread, do some work. And when the work is done, update the condition under lock, and notify the condition_variable:

```<code>std::unique_lock<std::mutex> lock(mutex);
workDone = true;
lock.unlock();
cv.notify_all();
</code>```

In another thread that needs to wait the work to be done, create a lock and wait on the condition_variable:

```<code>std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, []() { return workDone; });
</code>```

In each of the 3 parts, we need multiple lines of code. We can create a class like below to wrap up above codes:

```<code>template<class T>
class CVWaiter
{
private:
    T m_val;
    std::mutex m_mutex;
    std::condition_variable m_cv;

public:
    Waiter(_In_ const T& val) : m_val(val)
    {
    }

    void Notify(_In_ std::function<void(T& val)> update)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        update(m_val);
        lock.unlock();
        m_cv.notify_all();
    }

    void Wait(_In_ std::function<bool(const T& val)> condition)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_cv.wait(lock, [this, condition]() { return condition(m_val); });
    }
};
</code>```

With this class, the 3 parts on the top can be respectively written as:

CVWaiter workDoneWaiter(false);

workDoneWaiter.Notify([](bool& val) { val = true; });

workDoneWaiter.Wait([](const bool& val) { return val; });

Is it a correct way to implement the wrapper class? Is it a good practice to use the wrapper class for scenarios like this? Is there already anything that can achieve the same in a simpler way in STL?

Body:
I see a common pattern when using condition_variable to let one thread wait for another thread to finish some work:

Define a condition, a mutex, and a condition_variable:

bool workDone = false;
std::mutex mutex;
std::condition_variable cv;

In one thread, do some work. And when the work is done, update the condition under lock, and notify the condition_variable:

std::unique_lock<std::mutex> lock(mutex);
workDone = true;
lock.unlock();
cv.notify_all();

In another thread that needs to wait the work to be done, create a lock and wait on the condition_variable:

std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, []() { return workDone; });

In each of the 3 parts, we need multiple lines of code. We can create a class like below to wrap up above codes:

template<class T>
class CVWaiter
{
private:
    T m_val;
    std::mutex m_mutex;
    std::condition_variable m_cv;

public:
    Waiter(_In_ const T& val) : m_val(val)
    {
    }

    void Notify(_In_ std::function<void(T& val)> update)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        update(m_val);
        lock.unlock();
        m_cv.notify_all();
    }

    void Wait(_In_ std::function<bool(const T& val)> condition)
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_cv.wait(lock, [this, condition]() { return condition(m_val); });
    }
};

With this class, the 3 parts on the top can be respectively written as:

CVWaiter workDoneWaiter(false);

workDoneWaiter.Notify([](bool& val) { val = true; });

workDoneWaiter.Wait([](const bool& val) { return val; });

Is it a correct way to implement the wrapper class? Is it a good practice to use the wrapper class for scenarios like this? Is there already anything that can achieve the same in a simpler way in STL?


问:
How to display custom event info using FullCalander v6 with react
I am trying to create an appointment planner and I want to be able to show the description of the appointment as well as participants.

I've been going over the documentation on the site https://fullcalendar.io/ for awhile and thought maybe the eventContent prop would do the trick but I can't get it to work.

const CalendarComponent = ({appointments}) => {
  const renderEventContent = (eventInfo) => {
    console.log(eventInfo);
    return (
      <>
        {eventInfo.timeText}
        {eventInfo.event.title}
      </>
    )
  };

  return (
    <FullCalendar
      plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin]}
      headerToolbar={{
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
      }}
      initialView='dayGridMonth'
      editable={true}
      selectable={true}
      selectMirror={true}
      dayMaxEvents={true}
      displayEventEnd={true}
      weekends={true}
      events={appointments}
      eventContent={renderEventContent} // custom render function
    />
  );
};
```

Any ideas? All that shows when I use the renderEventContent function is the timeText prop.

Body:
I am trying to create an appointment planner and I want to be able to show the description of the appointment as well as participants.

I've been going over the documentation on the site https://fullcalendar.io/ for awhile and thought maybe the eventContent prop would do the trick but I can't get it to work.

const CalendarComponent = ({appointments}) => {
  const renderEventContent = (eventInfo) => {
    console.log(eventInfo);
    return (
      <>
        {eventInfo.timeText}
        {eventInfo.event.title}
      </>
    )
  };

  return (
    <FullCalendar
      plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin]}
      headerToolbar={{
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
      }}
      initialView='dayGridMonth'
      editable={true}
      selectable={true}
      selectMirror={true}
      dayMaxEvents={true}
      displayEventEnd={true}
      weekends={true}
      events={appointments}
      eventContent={renderEventContent} // custom render function
    />
  );
};

Any ideas? All that shows when I use the renderEventContent function is the timeText prop.


问:
dataclasss python reconstruct value
lets say i have this dataclass

```<code>@dataclass_json
@dataclass
class TestMetaData:
    edit_meta: MetaData

@dataclass_json
@dataclass
class MetaData:
    list_meta: list[MetaDataList]

@dataclass_json
@dataclass
class MetaDataList:
    name: str
    fields: list[MetaDataFields]

class MetaDataFields:
    label: str
    name: str
</code>```

i have a processing method to add data into this dataclass

```<code>data_args = {
        'test': TestMetaData(
            edit_meta=MetaData(
                list_meta=[
                    some_process_method(
                        meta
                    )
                    for meta in meta_info['metafields']
                ]
            )
        )
    }
return data_args
</code>```

now i have data_args and when i wanted to return to frontend as dictionary i can do something like this

```<code>return {
  **data_args
}
</code>```

but my question is, if i wanted to process data_args again before returning to frontend, how can i access data_args? using data_args['edit_meta'] as loop also wont help me to access the data inside. for my information i would like to learn how to access the data if is already converted into dataclass json

Title: dataclasss python reconstruct value

Body:
lets say i have this dataclass

@dataclass_json
@dataclass
class TestMetaData:
    edit_meta: MetaData

@dataclass_json
@dataclass
class MetaData:
    list_meta: list[MetaDataList]

@dataclass_json
@dataclass
class MetaDataList:
    name: str
    fields: list[MetaDataFields]

class MetaDataFields:
    label: str
    name: str

i have a processing method to add data into this dataclass

data_args = {
        'test': TestMetaData(
            edit_meta=MetaData(
                list_meta=[
                    some_process_method(
                        meta
                    )
                    for meta in meta_info['metafields']
                ]
            )
        )
    }
return data_args

now i have data_args and when i wanted to return to frontend as dictionary i can do something like this

return {
  **data_args
}

but my question is, if i wanted to process data_args again before returning to frontend, how can i access data_args? using data_args['edit_meta'] as loop also wont help me to access the data inside. for my information i would like to learn how to access the data if is already converted into dataclass json


问:
How to format list of product attributes in Woocommerce cart/checkout/email?
I'm looking to add the attribute data of simple products in the infobox (cart/checkout/email). I am currently doing this with the following code:

```<code>function sm_woo_cart_attributes($cart_item, $cart_item_key){
    $item_data = $cart_item_key['data'];
    $attributes = $item_data->get_attributes();

    if ( ! $attributes ) {
        return $cart_item;
    }

    $out = $cart_item . '<br />';

    foreach ( $attributes as $attribute ) {
        if ( $attribute['is_taxonomy'] ) {
            // skip variations
            if ( $attribute['is_variation'] ) {
                continue;
            }
            // backwards compatibility for attributes which are registered as taxonomies
            $product_id = $item_data->id;
            $terms = wp_get_post_terms( $product_id, $attribute['name'], 'all' );
            // get the taxonomy
            $tax = $terms[0]->taxonomy;
            // get the tax object
            $tax_object = get_taxonomy($tax);
            // get tax label
            if ( isset ($tax_object->labels->name) ) {
                $tax_label = $tax_object->labels->name;
            } elseif ( isset( $tax_object->label ) ) {
                $tax_label = $tax_object->label;
            }
            foreach ( $terms as $term ) {
                $out .= $tax_label . ': ';
                $out .= $term->name . '<br />';
            }
        } else {
            // not a taxonomy
            $out .= $attribute['name'] . ': ';
            $out .= $attribute['value'] . '<br />';
        }
    }
    echo $out;
}

add_filter( 'woocommerce_cart_item_name', 'sm_woo_cart_attributes', 10, 2 );
</code>```

This lists all of the attribute data, but above the product, shown in this screenshot. Is there any way to move the attribute data under the product image?

Body:
I'm looking to add the attribute data of simple products in the infobox (cart/checkout/email). I am currently doing this with the following code:

function sm_woo_cart_attributes($cart_item, $cart_item_key){
    $item_data = $cart_item_key['data'];
    $attributes = $item_data->get_attributes();

    if ( ! $attributes ) {
        return $cart_item;
    }

    $out = $cart_item . '
';

    foreach ( $attributes as $attribute ) {
        if ( $attribute['is_taxonomy'] ) {
            // skip variations
            if ( $attribute['is_variation'] ) {
                continue;
            }
            // backwards compatibility for attributes which are registered as taxonomies
            $product_id = $item_data->id;
            $terms = wp_get_post_terms( $product_id, $attribute['name'], 'all' );
            // get the taxonomy
            $tax = $terms[0]->taxonomy;
            // get the tax object
            $tax_object = get_taxonomy($tax);
            // get tax label
            if ( isset ($tax_object->labels->name) ) {
                $tax_label = $tax_object->labels->name;
            } elseif ( isset( $tax_object->label ) ) {
                $tax_label = $tax_object->label;
            }
            foreach ( $terms as $term ) {
                $out .= $tax_label . ': ';
                $out .= $term->name . '
';
            }
        } else {
            // not a taxonomy
            $out .= $attribute['name'] . ': ';
            $out .= $attribute['value'] . '
';
        }
    }
    echo $out;
}

add_filter( 'woocommerce_cart_item_name', 'sm_woo_cart_attributes', 10, 2 );

This lists all of the attribute data, but above the product, shown in this screenshot. Is there any way to move the attribute data under the product image?


问:
Cannot activate SNI for alternate domain names of my AWS CloudFront distribution
I am hosting a static website on AWS S3 bucket.
I have setup a CloudFront distribution with this bucket as origin.
I have created 2 alternate domains in my distributions

my-domain.com

*.my-domain.com

my-domain is registered in route53
I have created a hosted zone in which I have created records for my-domain.com and *.my-domain.com to point to my CloudFront distribution.

In AWS Certificate manager I have created a certificate for my-domain.com and *.my-domain.com that I have added to the CloudFront distribution.

At this point, everything is working fine and I get the expected result when I browse 'https://my-doamin.com

Now what I want to achieve is that my website is only accessible through https. I want users trying to access with http to be blocked.

I have setup my distribution behaviour to 'https only' and it works fine to block direct http access to my distribution (http://my-distribution.com)

However it is not enough to block http access through the altername domain (http://my-domain.com)

Through AWS documentation https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cnames-https-dedicated-ip-or-sni.html I have figured out I needed to activate SNI.

The steps in the documentation are :
To switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI.

Sign in to the AWS Management Console and open the CloudFront console at https://console.aws.amazon.com/cloudfront/v3/home.

Choose the ID of the distribution that you want to view or update.

Choose Distribution Settings.

On the General tab, choose Edit.

Change the setting of Custom SSL Client Support to Only Clients that Support Server Name Indication (SNI).

Choose Yes, Edit.

I believe I am following all these steps but in step 5 there is nowhere I can find where I can change the setting of Custom SSL Client Support and I am blocked.

Here is what I see instead:


问:
How to preserve non-serialized properties using freezed package in dart?
Consider the following dart class using freezed:

@freezed
class Example with _$Example {
  const factory Example(
          {String? fieldA, int? fieldB}) = _Example;

  factory Example.fromJson(Map<String, dynamic> json) => _$ExampleFromJson(json);
}
```
<p>If you were to deserialize the following json:</p>
<pre class="lang-json prettyprint-override"><code>  {
    "fieldA": "test",
    "fieldB": 9,
    "fieldC": 100
  }
</code>```

and then serialize it, it would end up like this:

  {
    "fieldA": "test",
    "fieldB": 9
  }
```

How can I preserve fieldC or any unknown field upon deserialization? In C# there is an annotation called ExtensionData (either for system.text or for newtonsoft) that held all the unserialized data. Is there an equivalent in freezed/json_serializable? If not, is there some way to workaround this?

Body:
Consider the following dart class using freezed:

@freezed
class Example with _$Example {
  const factory Example(
          {String? fieldA, int? fieldB}) = _Example;

  factory Example.fromJson(Map<String, dynamic> json) => _$ExampleFromJson(json);
}

If you were to deserialize the following json:

  {
    "fieldA": "test",
    "fieldB": 9,
    "fieldC": 100
  }

and then serialize it, it would end up like this:

  {
    "fieldA": "test",
    "fieldB": 9
  }

How can I preserve fieldC or any unknown field upon deserialization? In C# there is an annotation called ExtensionData (either for system.text or for newtonsoft) that held all the unserialized data. Is there an equivalent in freezed/json_serializable? If not, is there some way to workaround this?


问:
Prisma: How would I link multiple columns to the same data type
New to relational databases, and am using Prisma with Postgres, and Nextjs for a project. I am sending out emails to customers, and want to store these emails, but don't fully understand how the relationships work, to get it fully working.

I have email recipients that relate to a customer. Here there is a name and email address.

```<code>model email_recipient {
  id            String   @id(map: "pk_email_recipient") @db.Uuid
  name          String   @db.VarChar(255)
  email_address String   @db.VarChar(255)
  customer_id   String   @unique @db.Uuid
  customer      customer @relation(fields: [customer_id], references: [id])
}
</code>```

And I have an email model, that has to, cc, and bcc columns, that could be multiple email recipients. The recipient could technically exist in all three.

```<code>model email {
  id                 String    @id(map: "pk_email") @db.Uuid
  body               String?   @db.Text
  created_date       DateTime? @db.Timestamp(6)
  last_modified_date DateTime? @db.Timestamp(6)
  to                 email_recipient[]
  cc                 email_recipient[]
  bcc                email_recipient[]
}
</code>```

Prisma attempts to generate relationships for me, but I doesn't fully work as it adds the same named field 3 times, like so.

```<code>model email_recipient {
  id            String   @id(map: "pk_email_recipient") @db.Uuid
  name          String   @db.VarChar(255)
  email_address String   @db.VarChar(255)
  customer_id   String   @unique @db.Uuid
  customer      customer @relation(fields: [customer_id], references: [id])
  user          user[]
  email         email?   @relation(fields: [emailId], references: [id])
  emailId       String?  @db.Uuid
  email         email?   @relation(fields: [emailId], references: [id])
  emailId       String?  @db.Uuid
  email         email?   @relation(fields: [emailId], references: [id])
  emailId       String?  @db.Uuid
  // Clearly an issue here, but not prismas fault, its just trying its best.
}
</code>```

I have attempted to add an intermediary table in between with a recipient type enum, but could not get that to work. I think it is the right solution, but this is where my understanding of relationships break down.

Body:
New to relational databases, and am using Prisma with Postgres, and Nextjs for a project. I am sending out emails to customers, and want to store these emails, but don't fully understand how the relationships work, to get it fully working.

I have email recipients that relate to a customer. Here there is a name and email address.

model email_recipient {
  id            String   @id(map: "pk_email_recipient") @db.Uuid
  name          String   @db.VarChar(255)
  email_address String   @db.VarChar(255)
  customer_id   String   @unique @db.Uuid
  customer      customer @relation(fields: [customer_id], references: [id])
}

And I have an email model, that has to, cc, and bcc columns, that could be multiple email recipients. The recipient could technically exist in all three.

model email {
  id                 String    @id(map: "pk_email") @db.Uuid
  body               String?   @db.Text
  created_date       DateTime? @db.Timestamp(6)
  last_modified_date DateTime? @db.Timestamp(6)
  to                 email_recipient[]
  cc                 email_recipient[]
  bcc                email_recipient[]
}

Prisma attempts to generate relationships for me, but I doesn't fully work as it adds the same named field 3 times, like so.

model email_recipient {
  id            String   @id(map: "pk_email_recipient") @db.Uuid
  name          String   @db.VarChar(255)
  email_address String   @db.VarChar(255)
  customer_id   String   @unique @db.Uuid
  customer      customer @relation(fields: [customer_id], references: [id])
  user          user[]
  email         email?   @relation(fields: [emailId], references: [id])
  emailId       String?  @db.Uuid
  email         email?   @relation(fields: [emailId], references: [id])
  emailId       String?  @db.Uuid
  email         email?   @relation(fields: [emailId], references: [id])
  emailId       String?  @db.Uuid
  // Clearly an issue here, but not prismas fault, its just trying its best.
}

I have attempted to add an intermediary table in between with a recipient type enum, but could not get that to work. I think it is the right solution, but this is where my understanding of relationships break down.


问:
How do I run an app deployed on AppEngine from an AppScript file on my Drive
I have deployed an app on App Engine in the Google cloud project that uses the data stored in csv file as input from a folder on my Drive.
That data is created by a function in Google Script in a script file on my Drive.
Once the App script function has run and created the data in csv file it needs to call the app on the AppEngine to process that data.
Do I need to create an App Script API in the cloud project where the AppEngine is?
How do I use that API key from inside my Google script in my script file on my Drive?
Thanks

Nothing because everything I have seen seem to be the other way around.


问:
Setting up a public hosted zone when domain was purchased on Google Domains
I purchased a domain from Google Domains and I wish to set up a Public Hosted Zone via AWS CDK like so:

```<code>new route53.PublicHostedZone(this, 'HostedZone', {
  zoneName: 'api.domain.com',
});
</code>```

Is this possible to do via the CDK? If yes, how would AWS know I own the domain?

Or must I set up the Public Hosted Zone manually because the domain was purchased from Google Domains?

Body:
I purchased a domain from Google Domains and I wish to set up a Public Hosted Zone via AWS CDK like so:

new route53.PublicHostedZone(this, 'HostedZone', {
  zoneName: 'api.domain.com',
});

Is this possible to do via the CDK? If yes, how would AWS know I own the domain?

Or must I set up the Public Hosted Zone manually because the domain was purchased from Google Domains?


问:
how to update a collection if you already called it MongoDB Mongoos
Ok so I have a problem in which I use a collection to gather some ratings data and work with it, by the time I finish the rating update process, I have new ratings that I would like to update the collection with. However I can't call update because I get the error "Cannot overwrite model once compiled." I understand that I already called once the model to work with the data and that's why I get the error. is there any way I can update the collection? Or I will just have to workaround by creating a new collection with the latest rating, and then matching the latest ratings collection with the one I use to work with the data.

This is my code

```<code>let calculateRating = async () => {
  const getData = await matchesCollection().find().lean();
  const playerCollection = await playersCollection();

  const getDataPlayer = await playerCollection.find().lean();
  let gamesCounting = [];

  getDataPlayer.forEach((player) => {
    player.makePlayer = ranking.makePlayer(1500);
  });

  for (let i = 0; i < getData.length; i++) {
    const resultA = getDataPlayer.findIndex(({ userId }, index) => {
      if (userId === getData[i].userA) {
        return index;
      }
    });
    const resultB = getDataPlayer.findIndex(
      ({ userId }) => userId === getData[i].userB
    );
    const winner = getData[i].winner;

    if (getDataPlayer[resultA] === undefined) {
      continue;
    } else if (getDataPlayer[resultB] === undefined) {
      continue;
    }

    gamesCounting.push([
      getDataPlayer[resultA].makePlayer,
      getDataPlayer[resultB].makePlayer,
      winner,
    ]);
  }

  ranking.updateRatings(gamesCounting);

  let ratingsUpdate = [];

  getDataPlayer.forEach((item) => {
    let newRating = item.makePlayer.getRating();
    let newDeviation = item.makePlayer.getRd();
    let newVolatility = item.makePlayer.getVol();

    item.rating = newRating;
    item.rd = newDeviation;
    item.vol = newVolatility;

    ratingsUpdate.push(item);
  });
};
</code>```

I try the work around with creating the new collection

Body:
Ok so I have a problem in which I use a collection to gather some ratings data and work with it, by the time I finish the rating update process, I have new ratings that I would like to update the collection with. However I can't call update because I get the error "Cannot overwrite model once compiled." I understand that I already called once the model to work with the data and that's why I get the error. is there any way I can update the collection? Or I will just have to workaround by creating a new collection with the latest rating, and then matching the latest ratings collection with the one I use to work with the data.

This is my code

let calculateRating = async () => {
  const getData = await matchesCollection().find().lean();
  const playerCollection = await playersCollection();

  const getDataPlayer = await playerCollection.find().lean();
  let gamesCounting = [];

  getDataPlayer.forEach((player) => {
    player.makePlayer = ranking.makePlayer(1500);
  });

  for (let i = 0; i < getData.length; i++) {
    const resultA = getDataPlayer.findIndex(({ userId }, index) => {
      if (userId === getData[i].userA) {
        return index;
      }
    });
    const resultB = getDataPlayer.findIndex(
      ({ userId }) => userId === getData[i].userB
    );
    const winner = getData[i].winner;

    if (getDataPlayer[resultA] === undefined) {
      continue;
    } else if (getDataPlayer[resultB] === undefined) {
      continue;
    }

    gamesCounting.push([
      getDataPlayer[resultA].makePlayer,
      getDataPlayer[resultB].makePlayer,
      winner,
    ]);
  }

  ranking.updateRatings(gamesCounting);

  let ratingsUpdate = [];

  getDataPlayer.forEach((item) => {
    let newRating = item.makePlayer.getRating();
    let newDeviation = item.makePlayer.getRd();
    let newVolatility = item.makePlayer.getVol();

    item.rating = newRating;
    item.rd = newDeviation;
    item.vol = newVolatility;

    ratingsUpdate.push(item);
  });
};

I try the work around with creating the new collection


问:
Moderator variable test using SEMinR, as well as warppls
I'm learning to use various sem-pls software (such as smart-pls, warp-pls, and r), but I'm having trouble building a model using moderator variables, with warp-pls as the reference model.

sem-pls model in warp-pls

In the warppls model, the "kepuasa" variable has no effect on "loyalita", and I write the r syntax as follows

sem-pls syntax with SEMinR

```<code>dapen <- read_excel("E:/GDrive/latihan_seminr/dapen.xlsx")

modelouter <-constructs(
  composite("motivasi", multi_items("X1.", 1:4)),
  composite("kepuasan", multi_items("X2.", 1:3)),
  composite("loyalita", multi_items("Y.", 1:5)),
  interaction_term(iv = "motivasi", moderator = "kepuasan", method = two_stage))

modelinner <-relationships(
  paths(from = c("motivasi","motivasi*kepuasan"), to = ("loyalita")))

modelpls <-estimate_pls(
  data = dapen,
  measurement_model = modelouter,
  structural_model = modelinner
)
</code>```

and when I run the code I created, I get an error like the following :

error in r console

```<code>Generating the seminr model
Error in structural_model[, 1] : incorrect number of dimensions
</code>```

what i want to ask is, can we run the same research model as depicted in warppls?

I'm having trouble using SEMinR and comparing the test results with warppls, want to know the appropriate code and syntax

Body:
I'm learning to use various sem-pls software (such as smart-pls, warp-pls, and r), but I'm having trouble building a model using moderator variables, with warp-pls as the reference model.

sem-pls model in warp-pls

In the warppls model, the "kepuasa" variable has no effect on "loyalita", and I write the r syntax as follows

sem-pls syntax with SEMinR

dapen <- read_excel("E:/GDrive/latihan_seminr/dapen.xlsx")

modelouter <-constructs(
  composite("motivasi", multi_items("X1.", 1:4)),
  composite("kepuasan", multi_items("X2.", 1:3)),
  composite("loyalita", multi_items("Y.", 1:5)),
  interaction_term(iv = "motivasi", moderator = "kepuasan", method = two_stage))

modelinner <-relationships(
  paths(from = c("motivasi","motivasi*kepuasan"), to = ("loyalita")))

modelpls <-estimate_pls(
  data = dapen,
  measurement_model = modelouter,
  structural_model = modelinner
)

and when I run the code I created, I get an error like the following :

error in r console

Generating the seminr model
Error in structural_model[, 1] : incorrect number of dimensions

what i want to ask is, can we run the same research model as depicted in warppls?

I'm having trouble using SEMinR and comparing the test results with warppls, want to know the appropriate code and syntax


问:
Pretty URL with htaccess on one param encoded URL
this is the link that would like to convert from:

http://localhost/home/comment.php?id=k76t%2BPM1AYUlz%2Bz7sY%2BHg7F5p

into this:

http://localhost/home/comment/id/k76t%2BPM1AYUlz%2Bz7sY%2BHg7F5p

also note that this is in the href tag, so when user click it should show the clean version, however, to test it, i type the pretty version manually in http address bar, it still wouldn't work.

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^home/comment/id/^(.+)/(.+)/?$ home/comment.php?id=$1 [QSA,L] #attempt 1

RewriteRule ^home/comment/id/(.*)$ home/comment.php?id=$1 [QSA,L] #attempt 2

RewriteRule ^home/comment/id/([-A-Za-z0-9%]+)$ home/comment.php?id=$1 [QSA,L] #attempt 3

</code>```

Body:
this is the link that would like to convert from:

http://localhost/home/comment.php?id=k76t%2BPM1AYUlz%2Bz7sY%2BHg7F5p

into this:

http://localhost/home/comment/id/k76t%2BPM1AYUlz%2Bz7sY%2BHg7F5p

also note that this is in the href tag, so when user click it should show the clean version, however, to test it, i type the pretty version manually in http address bar, it still wouldn't work.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^home/comment/id/^(.+)/(.+)/?$ home/comment.php?id=$1 [QSA,L] #attempt 1

RewriteRule ^home/comment/id/(.*)$ home/comment.php?id=$1 [QSA,L] #attempt 2

RewriteRule ^home/comment/id/([-A-Za-z0-9%]+)$ home/comment.php?id=$1 [QSA,L] #attempt 3


问:
Charts do not display in notebook (matplotlib and seaborn) in python
```<code> Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.
  plt.show()
</code>```

charts should display in python and the message above shows

Body:
 Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.
  plt.show()

charts should display in python and the message above shows


问:
Imagemagick page count function with PDF version 1.5 onwards - PHP
I am running Apache/2.2.17 (Win32) PHP/5.3.0 in my Windows Vista PC.
I have imagemagick configured. I have a php function to count pages in a PDF file as follows;

```<code><?php
$filepath = "test.pdf";

function getNumPagesPdf($filepath){
    $fp = @fopen(preg_replace("/\[(.*?)\]/i", "",$filepath),"r");
    $max=0;
    while(!feof($fp)) {
            $line = fgets($fp,255);
            if (preg_match('/\/Count [0-9]+/', $line, $matches)){
                    preg_match('/[0-9]+/',$matches[0], $matches2);
                    if ($max<$matches2[0]) $max=$matches2[0];
            }
    }
    fclose($fp);
    if($max==0){
        $im = new imagick($filepath);
        $max=$im->getNumberImages();
    }

    return $max;
}

echo getNumPagesPdf($filepath);
?>
</code>```

The code works just file for PDF files up to PDF files having version 1.4. It is not working for PDF files having version 1.5 onwards.

ContentLicense: CC BY-SA 3.0

Body:
I am running Apache/2.2.17 (Win32) PHP/5.3.0 in my Windows Vista PC.
I have imagemagick configured. I have a php function to count pages in a PDF file as follows;

<?php
$filepath = "test.pdf";

function getNumPagesPdf($filepath){
    $fp = @fopen(preg_replace("/\[(.*?)\]/i", "",$filepath),"r");
    $max=0;
    while(!feof($fp)) {
            $line = fgets($fp,255);
            if (preg_match('/\/Count [0-9]+/', $line, $matches)){
                    preg_match('/[0-9]+/',$matches[0], $matches2);
                    if ($max<$matches2[0]) $max=$matches2[0];
            }
    }
    fclose($fp);
    if($max==0){
        $im = new imagick($filepath);
        $max=$im->getNumberImages();
    }

    return $max;
}

echo getNumPagesPdf($filepath);
?>

The code works just file for PDF files up to PDF files having version 1.4. It is not working for PDF files having version 1.5 onwards.


问:
Multiple Images input for Tensorflow VGG16 error:"Layer count mismatch when loading weights from file. Model expected 14 layers, found 13 saved layers
So I am trying to vgg16 as a feature extractor for my set of Partial Angle CT reconstructions(so each set of reconstructions contains 22 individual grayscale images(128,128) that I reshaped into a (128,128,3) images I can use for input into VGG16, Then I tf.keras.layers.Concatenate the inputs, and then I added a 2D convolution layer for the concactenated input, but when i try to load that into the keras predefined VGG16 model with imagenet as weights, it reported error: Layer count mismatch when loading weights from file. Model expected 14 layers, found 13 saved layers.
Here is the code I used:

```<code>def input_block():
   for i in range(22):
     input.append(Input(shape = (128,128,3), name = 'img'+str(i)))
   ConcacteInput = tf.keras.layers.Concatenate()(input)
   x = Conv2D(3,(3,3), padding = 'same', name = 'multi_input_layer')(ConcacteInput)
   return x
</code>```

Afterwards, I plugged it into the VGG16 model like this:

```<code>VGG_model = VGG16(weights='imagenet',include_top = False, input_tensor = input_block())
</code>```

However, the error Layer count mismatch when loading weights from file. Model expected 14 layers, found 13 saved layers. persisted, but it has never happened when I use one of the grayscale reco images as input. I don't really understand why this is happening.

Body:
So I am trying to vgg16 as a feature extractor for my set of Partial Angle CT reconstructions(so each set of reconstructions contains 22 individual grayscale images(128,128) that I reshaped into a (128,128,3) images I can use for input into VGG16, Then I tf.keras.layers.Concatenate the inputs, and then I added a 2D convolution layer for the concactenated input, but when i try to load that into the keras predefined VGG16 model with imagenet as weights, it reported error: Layer count mismatch when loading weights from file. Model expected 14 layers, found 13 saved layers.
Here is the code I used:

def input_block():
   for i in range(22):
     input.append(Input(shape = (128,128,3), name = 'img'+str(i)))
   ConcacteInput = tf.keras.layers.Concatenate()(input)
   x = Conv2D(3,(3,3), padding = 'same', name = 'multi_input_layer')(ConcacteInput)
   return x

Afterwards, I plugged it into the VGG16 model like this:

VGG_model = VGG16(weights='imagenet',include_top = False, input_tensor = input_block())

However, the error Layer count mismatch when loading weights from file. Model expected 14 layers, found 13 saved layers. persisted, but it has never happened when I use one of the grayscale reco images as input. I don't really understand why this is happening.


问:
how to make an http call to an api by sending along a .pfx file in AngularJS?
I'm performing an integration with a Bank api that needs this file to be sent. In postman I configure the certificate and password and I get the connection correctly. However, in my Angular project I am not finding the correct way to send this certificate (.pfx) along with my header.

What is the solution to be able to make this call to the API with the .pfx certificate?

```<code>const httpHeaders = {
        headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
        })
    };

    const map = {
        'x-api-clientid': config.clienteId,
        'grant_type': 'client_credentials'
    }

    try {
        return await this.httpClient.post(config.url_token, map, httpHeaders).toPromise().then((resp: any) => {
            console.log('resp')
            console.log(resp)
            return resp
        });
    } catch (error) {
        console.log('erro in post')
        console.log(error);
        return false;
    }
</code>```

Body:
I'm performing an integration with a Bank api that needs this file to be sent. In postman I configure the certificate and password and I get the connection correctly. However, in my Angular project I am not finding the correct way to send this certificate (.pfx) along with my header.

What is the solution to be able to make this call to the API with the .pfx certificate?

const httpHeaders = {
        headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded',
        })
    };

    const map = {
        'x-api-clientid': config.clienteId,
        'grant_type': 'client_credentials'
    }

    try {
        return await this.httpClient.post(config.url_token, map, httpHeaders).toPromise().then((resp: any) => {
            console.log('resp')
            console.log(resp)
            return resp
        });
    } catch (error) {
        console.log('erro in post')
        console.log(error);
        return false;
    }


问:
Database in tidy format python
I have a really weird database and I need it to be in tidy format (using python).

I need the data to be, for example, 01/01/1995, and each date in a line, not in columns. Also, the variables should be columns and each subvariable under the main variable should make reference to it, for example, Store-Itens-Expenses. Note that the this subvariables are identified buy the number of blank spaces they have before its name.

How can I do this using python?

Example of my database

I haven't tried anything yet.

Title: Database in tidy format python


问:
Looping through a table with Xpath in RSelenium
How would I iterate through all the table row xpaths in a table? I am currently using RSelenium to navigate to the webpage and generate the dataset by selecting through the options:

```<code>#Navigate to RAWS website
remDr$navigate("https://wrcc.dri.edu/cgi-bin/rawMAIN.pl?caucgr")

#Switch to Left Frame named "List"
ListFrame <- remDr$findElement(using = "name", value = "List")
remDr$switchToFrame(ListFrame)

#Select Daily Summary Time Series Link
Link1 <- remDr$findElement(using = "link text", value = "Daily Summary Time Series")
Link1$clickElement()

#Switch to Right Frame named "Graph"
remDr$switchToFrame(NA)
GraphFrame <- remDr$findElement(using = "name", value = "Graph")
remDr$switchToFrame(GraphFrame)

# #Set the Starting Date
StartMonth <- remDr$findElement(using = "name", value = "smon")
StartMonth$sendKeysToElement(list(StartDates$month))
#
StartDay <- remDr$findElement(using = "name", value = "sday")
StartDay$sendKeysToElement(list(StartDates$day))
#
StartYear <- remDr$findElement(using = "name", value = "syea")
StartYear$sendKeysToElement(list(StartDates$year))

#Set the Ending Date
EndMonth <- remDr$findElement(using = "name", value = "emon")
EndMonth$sendKeysToElement(list(EndDates$month))
#
EndDay <- remDr$findElement(using = "name", value = "eday")
EndDay$sendKeysToElement(list(EndDates$day))
#
EndYear <- remDr$findElement(using = "name", value = "eyea")
EndYear$sendKeysToElement(list(EndDates$year))

#Select Air Temperature and Precipitation
Temp <- remDr$findElement(using = "name", value = "qAT")
Temp$clickElement()

Precip <- remDr$findElement(using = "name", value = "qPR")
Precip$clickElement()

#Select Metric Output units
Units <- remDr$findElement(using = "xpath", "//input[@value = 'M']")
Units$clickElement()

#Select HTML Output
Format <-remDr$findElement(using = "xpath", "//input[@value = 'H']")
Format$clickElement()

#Select the Data Summarization requirements
Summarization <-remDr$findElement(using = "xpath", "//input[@value = 'C']")
Summarization$clickElement()

#Apply physical limits QC to data
Limits <-remDr$findElement(using = "xpath", "//input[@value = 'Y' and @name = 'qc']")
Limits$clickElement()

#Represent Missing data as -999
Missing<-remDr$findElement(using = "name", value = "miss")
Missing$sendKeysToElement(list("-999"))

#Don't include valid observations for each element
Validity <-remDr$findElement(using = "xpath", "//input[@value = 'N' and @name = 'obs']")
Validity$clickElement()

#Click on Submit info button
Submit <-remDr$findElement(using = "xpath", "//input[@value = 'Submit Info']")
Submit$clickElement()

#Switch to Graph frame (the right hand frame)
remDr$switchToFrame(NA)
GraphFrame <- remDr$findElement(using = "name", value = "Graph")
remDr$switchToFrame(GraphFrame)
</code>```

I am trying to extract rows 2-32 of a weather data table. The following code block works but is tedious. I'd like to throw it into a loop, but because the index of the tr tag is embedded in single quotes, iteration doesn't work.

```<code>Data <- WeatherData$findChildElement(using = "xpath", '//tr[2]')
Row2 <- Data$getElementText()
Data <- WeatherData$findChildDlement(using = "xpath", '//tr[3]')
Row3 <-Data$getElementText()
Data <- WeatherData$findChildElement(using = "xpath", '//tr[4]')
Row4 <- Data$GetElementText()
</code>```

I am grabbing the data from https://wrcc.dri.edu/cgi-bin/wea_dysimts2.pl

This is the pseudocode of what I'm trying to achieve:

```<code>for i in (2:32){
Data <- WeatherData$findChildElement(using = "xpath", '//tr[i] }
row_i <- Data$GetElementText() }
</code>```

I would like 31 row variables (R2, R3, R4, ...R32) to be generated. I also tried grabbing the 31 rows at once like so but that failed:

```<code> Data <- WeatherData$findChildElement(using = "xpath", '//tr[2]': tr[32]')
 Data <- Data$getElementText()
</code>```

Body:
How would I iterate through all the table row xpaths in a table? I am currently using RSelenium to navigate to the webpage and generate the dataset by selecting through the options:

#Navigate to RAWS website
remDr$navigate("https://wrcc.dri.edu/cgi-bin/rawMAIN.pl?caucgr")

#Switch to Left Frame named "List"
ListFrame <- remDr$findElement(using = "name", value = "List")
remDr$switchToFrame(ListFrame)

#Select Daily Summary Time Series Link
Link1 <- remDr$findElement(using = "link text", value = "Daily Summary Time Series")
Link1$clickElement()

#Switch to Right Frame named "Graph"
remDr$switchToFrame(NA)
GraphFrame <- remDr$findElement(using = "name", value = "Graph")
remDr$switchToFrame(GraphFrame)

# #Set the Starting Date
StartMonth <- remDr$findElement(using = "name", value = "smon")
StartMonth$sendKeysToElement(list(StartDates$month))
#
StartDay <- remDr$findElement(using = "name", value = "sday")
StartDay$sendKeysToElement(list(StartDates$day))
#
StartYear <- remDr$findElement(using = "name", value = "syea")
StartYear$sendKeysToElement(list(StartDates$year))

#Set the Ending Date
EndMonth <- remDr$findElement(using = "name", value = "emon")
EndMonth$sendKeysToElement(list(EndDates$month))
#
EndDay <- remDr$findElement(using = "name", value = "eday")
EndDay$sendKeysToElement(list(EndDates$day))
#
EndYear <- remDr$findElement(using = "name", value = "eyea")
EndYear$sendKeysToElement(list(EndDates$year))

#Select Air Temperature and Precipitation
Temp <- remDr$findElement(using = "name", value = "qAT")
Temp$clickElement()

Precip <- remDr$findElement(using = "name", value = "qPR")
Precip$clickElement()

#Select Metric Output units
Units <- remDr$findElement(using = "xpath", "//input[@value = 'M']")
Units$clickElement()

#Select HTML Output
Format <-remDr$findElement(using = "xpath", "//input[@value = 'H']")
Format$clickElement()

#Select the Data Summarization requirements
Summarization <-remDr$findElement(using = "xpath", "//input[@value = 'C']")
Summarization$clickElement()

#Apply physical limits QC to data
Limits <-remDr$findElement(using = "xpath", "//input[@value = 'Y' and @name = 'qc']")
Limits$clickElement()

#Represent Missing data as -999
Missing<-remDr$findElement(using = "name", value = "miss")
Missing$sendKeysToElement(list("-999"))

#Don't include valid observations for each element
Validity <-remDr$findElement(using = "xpath", "//input[@value = 'N' and @name = 'obs']")
Validity$clickElement()

#Click on Submit info button
Submit <-remDr$findElement(using = "xpath", "//input[@value = 'Submit Info']")
Submit$clickElement()

#Switch to Graph frame (the right hand frame)
remDr$switchToFrame(NA)
GraphFrame <- remDr$findElement(using = "name", value = "Graph")
remDr$switchToFrame(GraphFrame)

I am trying to extract rows 2-32 of a weather data table. The following code block works but is tedious. I'd like to throw it into a loop, but because the index of the tr tag is embedded in single quotes, iteration doesn't work.

Data <- WeatherData$findChildElement(using = "xpath", '//tr[2]')
Row2 <- Data$getElementText()
Data <- WeatherData$findChildDlement(using = "xpath", '//tr[3]')
Row3 <-Data$getElementText()
Data <- WeatherData$findChildElement(using = "xpath", '//tr[4]')
Row4 <- Data$GetElementText()

I am grabbing the data from https://wrcc.dri.edu/cgi-bin/wea_dysimts2.pl

This is the pseudocode of what I'm trying to achieve:

for i in (2:32){
Data <- WeatherData$findChildElement(using = "xpath", '//tr[i] }
row_i <- Data$GetElementText() }

I would like 31 row variables (R2, R3, R4, ...R32) to be generated. I also tried grabbing the 31 rows at once like so but that failed:

 Data <- WeatherData$findChildElement(using = "xpath", '//tr[2]': tr[32]')
 Data <- Data$getElementText()


问:
How do you import external packages for ffmpeg-kit?
I need to convert mp4 to mp3. There doesn't seem to be a way to install an external package on the docs of ffmpeg-kit.</p>