Using then inside setTimeout callback function

I have some legacy code that is using React class based component. Inside the componentDidMount it is calling a function lets call it func1() after 1 second.

It is supposed to call func2() only once func1() has finished execution. However, it is calling func2() meanwhile func1() has not finished execution.

I have put the func1() structure as well

componentDidMount() {
  setTimeout(() => {
    this.func1().then(() => { 
     this.func2();
    });
  }, 1000);
}

func1 = async () => {
 // do some long running operation
 await httpCall();
}

httpCall = async () => {
  await post();
}

How to reverse CSS image animation?

I am trying to build an animation that uncovers an image from right to left. However it doesn’t seem to be working the way I expected, it is currently going from left to right even after I changed “linear-gradient(to right” to “linear-gradient(to left”. Is there a method that would be better suited for this or am I just missing something?

this is my code.

<div class="fade-in-img-2">
<img class="fade-img-2" src="url"/>
</div>
<style>

.fade-in-img-2 {
  animation: left-to-right-fade-in-2 1s ease-in;
  -webkit-mask-repeat: no-repeat;
  display: flex;
  justify-content: center;
}
.fade-in-img-2 .fade-img-2 {
    width: 60%;
}
@keyframes left-to-right-fade-in-2 {
  0% {
    -webkit-mask-size: 0%;
    -webkit-mask-image: linear-gradient(
      to right,
      rgba(0, 0, 0, 1) 70%,
      rgba(0, 0, 0, 0)
    );
  }
  100% {
    -webkit-mask-size: 100%;
    -webkit-mask-image: linear-gradient(
      to right,
      rgba(0, 0, 0, 1) 70%,
      rgba(0, 0, 0, 0)
    );
  }
}

</style>

I changed “linear-gradient(to right” to “linear-gradient(to left” and expected the animation to be reversed however the animation ran in the same direction and did not seem to do anything.

axios error code 499 for chrome extension

i’m using axios to send some queries to leetcode to access their graphql API. I’m using a chrome extension that reads the necessary cookie credentials so that i can use it as auth for the API. however, I’m getting Request failed with status code 499 errors as a response. my query and cookies work on postman, but it’s not working when i use axios. I’m not sure what postman is doing differently, but I’ll post my code here:

    let url = `https://leetcode.com/graphql`;
    const fetchSubmissionList = async (questionSlug) => {
        let query = `
            questionSubmissionList(
               offset: 0,
               limit: 20,
               questionSlug: ${questionSlug}
             ) {
                lastKey
                hasNext
                submissions {
                    id
                    title
                    titleSlug
                    status
                    statusDisplay
                    lang
                    langName
                    runtime
                    timestamp
                    url
                    isPending
                    memory
                    hasNotes
                    notes
                }
            }
        }
        `

        chrome.storage.local.get(["LEETCODE_SESSION"]).then((result) => {
            console.log("LEETCODE_SESSION - " + JSON.stringify(result));
            setSession(result["LEETCODE_SESSION"])
            document.cookie = `LEETCODE_SESSION=${result["LEETCODE_SESSION"]}; SameSite=None; Secure`;
            chrome.storage.local.get(["csrftoken"]).then(async (result) => {
                console.log("csrftoken - " + JSON.stringify(result));
                setToken(result["csrftoken"])
                document.cookie = `csrftoken=${result["csrftoken"]}; SameSite=None; Secure`;
                await axios.post(
                    url, { query: JSON.stringify(query) }, 
                    {
                        headers: {
                            'Content-Type': 'application/json',
                            'Access-Control-Allow-Origin':  '*',
                            'Access-Control-Allow-Methods': 'POST',
                            'Access-Control-Allow-Headers': 'Content-Type, Authorization',
                        },
                        withCredentials: true
                    }).then(res => res.json()).then(data => console.log(data))
            });
        });
    }

i found some posts addressing this in other systems (like, nginx?), but not in axios. also, i read that this error stems from your client closing your connection too soon, but i don’t know how i can change that.

thanks

Jquery: How to highlight some numbers in bold within a numeric sequence from 0 to 99 after a click event?

I have a numeric sequence from 0 to 99:

0 1 2 3 4 5 . . . 99

In this case, i’m trying to put some numbers in bold after clicking a button. For example, within a first input there is the number 2 and within a second input there is the number 99, and after clicking on a button, the number 2 and 99 are in bold as below:

0 1 2 3 4 5 . . . 99

I tried to find some similar questions, but unfortunatly i didn’t find some solution to improve my script yet:

  1. Jquery how to check if a input has a number higher then 99

  2. I Want To Print 1 to 100 Numbers Using Arrays In Javascript Only

  3. How to format numbers by prepending 0 to single-digit numbers?

At first i’m trying with the following HTML code and a jquery script to apply this solution, but i’m not able to improve it to get the final result:

HTML code:


<input type="number" id="field1" value="2"/>
<br>
<input type="number" id="field2" value="99"/>
<br>
<button type="button" id="getBtn">show me the highlighted numbers</button>
<br>

<div id="sequence"></div>

Jquery script to call click event:

$('#getBtn').on( "click", function() {

  var field1 = $('#field1').val();
  var field2 = $('#field2').val();

// From this point, i don't know how to improve the script to display a sequence number with the highlighted numbers.

for(let i = 0;i <= 100;i++){

    console.log(i);

}

$("#sequence").html();


});


How can i improve my script to find a viable solution?

Add Same Product with different sizes and prices to the cart

I can add different products as individual arrays and I can also increase and decrease the quantities if the same product added. But I would want to add same product with different size. Below is my code.. Please help out..!

Context screen:

 const initialState = {
  
  products: ProductData,
    cart: [],
  };
 
const reducer = (state = initialState, action)=>{
    switch(action.type){
        case 'ADD':
            const item = state.products.find(
                (product) => product.id === action.payload.id
              );
              // Check if Item is in cart already
              const inCart = state.cart.find((item) =>
                item.id === action.payload.id ? true : false
              );
        
              return {
                ...state,
                cart: inCart
                  ? state.cart.map((item) =>
                      item.id === action.payload.id
                        ? { ...item, qty: item.qty + 1 }
                        : item
                    )
                  : [...state.cart, { ...item, qty: 1 }],
              };
            
        case 'DELETE':
        return {
            ...state,
            cart: state.cart.filter((item) => item.id !== action.payload.id),
          };
       
        case 'INCREASE':
               const tempCart = state.cart.map((cartItem) => {
                if (cartItem.id === action.payLoad.id) {
                  return { ...cartItem, qty: cartItem.qty + 1 };
                }
                return cartItem;
              });
              return { ...state, cart: tempCart };
        
        case 'DECREASE':
                const temp = state.cart.map((cartItem) => {
                    if (cartItem.id === action.payLoad.id) {
                      return { ...cartItem, qty: cartItem.qty - 1 };
                    }
                 return cartItem;
                  })
                  .filter((cartItem) => cartItem.qty !== 0);
                return { ...state, cart: temp };
              
        case 'CLEAR':
              return {cart :[]}
           
        default:
            throw new Error(`unknow action.${action.type}`)
    }

}

Product Data

 export const ProductData = [
{
  id: 'C1',
  name:'Coffee',
  categories: [1],
  price: 15.00,
  prices: [
    {size: 'S', price: '1.38', currency: '$'},
    {size: 'M', price: '3.15', currency: '$'},
    {size: 'L', price: '4.29', currency: '$'},
  ],
 
{
  id: 'C2',
  name: "Coffee",
  icon:icons.coffee_1,
  categories: [1,2],
  price: 15.00,
  prices: [
    {size: 'S', price: '1.38', currency: '$'},
    {size: 'M', price: '3.15', currency: '$'},
    {size: 'L', price: '4.29', currency: '$'},
  ],

}
]

I can add, delete, increase and decrease but I wanna add same product to the cart with different specification. your help is highly appreciate.

IaC Secrets Manager can’t find the specified secret when AWS CDK in Deploy

I’m having an issue when trying to create and replicate the secret of the database created within the provisioned cluster. I have attempted to specify the ARN of the secret in the Parameter Store within the variable /DB_SECRET/, but I have not been successful. I also tried adding a new policy to the roles, but I can’t get it to work.

My code is as follows:

rds.js


const { DatabaseClusterEngine, 
    ServerlessCluster,
    SecurityGroup,
    Port,
    SubnetGroup,
    Credentials,
    DatabaseSecret,
    AuroraCapacityUnit,
    RemovalPolicy,
    Duration,
  } = require('aws-cdk-lib/aws-rds');
  const { SubnetType } = require('aws-cdk-lib/aws-ec2');
const { SecretsManager } = require('aws-sdk');
  
  const createRelationalDatabase = (
    scope,
    { name, vpc, secretManagerKey, encryptionKey,
      mySqlVersion, username, dbSubnets, subnetGroup,
      cluster, securityGroup, clusterSecurityGroups, defaultDatabaseName,
      dbExists, clusterIdentifier, dbSecurityGroupId, secretArn
    }
  ) => {
    if (!scope) throw new Error('Error scope missing');
    if (!vpc) throw new Error('Error vpc missing');
    if (!mySqlVersion) throw new Error('Error mySqlVersion missing');
    if (!name) throw new Error('Error name missing');
    if (!username) throw new Error('Error username missing');
    if (!cluster) throw new Error('Error cluster missing');
    if (!clusterSecurityGroups) throw new Error('Error clusterSecurityGroups missing');
    if (!securityGroup) throw new Error('Error securityGroup missing');
    
    let dbSecurityGroup;
    let snGroup;
    let dbSecret;
    let relationalDb;

    // Verifica version de mysql
  
    if (!dbExists) {
      const engine = DatabaseClusterEngine.auroraMysql({
        version: mySqlVersion,
      });
  
      //crea grupo de seguridad
      dbSecurityGroup = new SecurityGroup(
        scope,
        `${securityGroup.name}`,
        {
          vpc,
          securityGroupName: `${securityGroup.name}`,
        }
      );
//aplica politicas anti eliminación. 
      dbSecurityGroup.applyRemovalPolicy(RemovalPolicy.RETAIN);
  
      clusterSecurityGroups.forEach(clusterSecurityGroup => {
        dbSecurityGroup.addIngressRule(
          clusterSecurityGroup,
          Port.tcp(securityGroup.port),
          securityGroup.description
        );
      });       
  
      snGroup = new SubnetGroup(scope, `${name}-subnet-group`, {
        description: subnetGroup.description,
        vpc,
        vpcSubnets: {
          subnets: dbSubnets,
        },
      });
      snGroup.applyRemovalPolicy(RemovalPolicy.RETAIN);
  
      dbSecret = new DatabaseSecret(scope, `${name}-secret`, {
        encryptionKey: encryptionKey,
        username: username,
        secretName: `${name}-rds-secret`,
      });
      dbSecret.applyRemovalPolicy(RemovalPolicy.RETAIN);

      // Realizar la replicación del secreto
    if (shouldReplicate) {
            const replicatedSecret = addReplication(dbSecret);
            // `replicatedSecret` ahora contiene el secreto replicado
        }

        replicatedSecret.applyRemovalPolicy(RemovalPolicy.RETAIN);
  
      const credentials = Credentials.fromSecret(dbSecret, username);


      // cluster con replica

        //const vpc: ec2.Vpc;
        relationalDb = new rds.DatabaseCluster(this, 'Database', {
        engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_3_01_0 }),
        securityGroups: [dbSecurityGroup],
        storageEncryptionKey: encryptionKey,
        backupRetention: Duration.days(cluster.backupRetention),
        subnetGroup: snGroup,
        defaultDatabaseName,
        credentials,
        writer: rds.ClusterInstance.provisioned('writer', {
            instanceType: ec2.InstanceType.of(ec2.InstanceClass.R6G, ec2.InstanceSize.XLARGE4),
        }),
        serverlessV2MinCapacity: 1,
        serverlessV2MaxCapacity: 2,
        readers: [
            // will be put in promotion tier 1 and will scale with the writer
            rds.ClusterInstance.serverlessV2('reader1', { scaleWithWriter: true })
            // will be put in promotion tier 2 and will not scale with the writer
            //rds.ClusterInstance.serverlessV2('reader2'),
        ],
        vpc,
        });

      relationalDb.applyRemovalPolicy(RemovalPolicy.RETAIN);
  
    } else {
      dbSecurityGroup = SecurityGroup.fromSecurityGroupId(scope, `${securityGroup.name}`, dbSecurityGroupId);
  
      clusterSecurityGroups.forEach(clusterSecurityGroup => {
        dbSecurityGroup.addIngressRule(
          clusterSecurityGroup,
          Port.tcp(securityGroup.port),
          securityGroup.description
        );
      });
  
      dbSecret = DatabaseSecret.fromSecretCompleteArn(scope, `${name}-secret`, secretArn);
  
      relationalDb = ServerlessCluster.fromServerlessClusterAttributes(scope, `${name}-db`, {
        clusterIdentifier,
      });
    }
    return {
      relationalDb,
      dbSecret,
    };
  };
  
  module.exports = { createRelationalDatabase };
  

my stack
cdk-iac-microservices-stack.js

const cdk = require('aws-cdk-lib');
const { getParam } = require('./iac/config');
//const { getVpcFromId } = require('@matrixtech/fw-iac/lib/network/vpc');
const { Vpc } = require('aws-cdk-lib/aws-ec2');
const { Key } = require('aws-cdk-lib/aws-kms');
const { Queue, QueueEncryption } = require('aws-cdk-lib/aws-sqs') ;
const { Stream } = require('aws-cdk-lib/aws-kinesis');
const { createSsm } = require('./iac/string-parameter');
const { createFargateCluster } = require('./iac/fargate');
const { createAdditionalPolicies } = -require('./iac/policy');
const { createDatabaseState } = require('./iac/database-state');
const { getSubnetFromId } = require('./iac/subnet');
const { createDatabase } = require('./iac/database');
const { createRelationalDatabase } = require('./iac/rds');
const { getKeyFromArn } = require('./iac/kms');
const { createBucket } = require('./iac/s3');
class CdkIacMicroservicesStack extends cdk.Stack {
  /**
   *
   * @param {cdk.Construct} scope
   * @param {string} id
   * @param {cdk.StackProps=} props
   */
  constructor(scope, id, props) {
    if (!scope) throw new Error('scope missing');
        if (!id) throw new Error('id missing');
        if (!props) throw new Error('props missing');
    super(scope, id, props);

    let vpc = null;
    let subnets = null;
    if (getParam('network')) {
        vpc = Vpc.fromLookup(this, 'demo-ecs-vpc', {
            vpcId : getParam('network.vpcId')
        });
            //vpc = getVpcFromId(this, 'demo-ecs-vpc', getParam('network.vpcId') );
            subnets = getParam('network.subnetsIds').map((id, index) =>
                getSubnetFromId(this, `demo-sn-${index.toString()}`, id)
            );          
    }
        const stream = getParam('stream');
        const sqs = getParam('sqs');
        let streamKey = null;
        let sqsKey = null;
        let msStream = null;    
        let msSQS = null;    
        if (stream) {
            streamKey = Key.fromKeyArn(
                this,
                `${getParam('stream.streamName')}-key-table`,
                getParam('stream.kmsArn')
            );
            msStream = new Stream(this,`${getParam('stream.streamName')}-stream`, Object.assign({ encryptionKey: streamKey }, getParam('stream')));
        }

        let arraySQS=[];
        // SQS
        if (sqs) {
            sqs.map((awssqs)=> {
                sqsKey = Key.fromKeyArn(
                    this,
                    `${awssqs.sqsName}-key-sqs`,
                    awssqs.kmsArn
                );  
                msSQS = new Queue(this, `${awssqs.sqsName}-sqs`,{
                    queueName: awssqs.sqsName,
                    encryption: QueueEncryption.KMS,
                    encryptionMasterKey: sqsKey
                });
                arraySQS.push(msSQS);
            });
        }
        
        // BASE DE DATOS
        const databaseParams = getParam('database');
        let  databaseKey;
        if(databaseParams && databaseParams.noRelational) {
            databaseKey  = Key.fromKeyArn(
                this,
                'database-key-table',
                databaseParams.noRelational.kmsArn
            );
        }
            


        const roles = [];
        const clusterSecurityGroups = [];

        // MICROSERVICE
        const microserviceContainers = [];
        const microserviceProp = getParam('microservice');
        if (microserviceProp) {
            for (const container of microserviceProp.containers) {
                const microserviceVersionTag = createSsm(
                    this,
                    Object.assign(container.ssm, {
                        paramExist: props.microserviceParamExist,
                    })
                );
                const isProducer = container.port ? true: false;
                const microservice = createFargateCluster(
                    this,
                    Object.assign(
                        container,
                        { vpc, subnets },
                        { tag: microserviceVersionTag.stringValue },
                        { isProducer, loadBalancerArn: container.loadBalancerArn },
                        { securityGroupIngress: container.securityGroupIngress}
                    )
                );
                if (isProducer) {
                    const loadBalancer = microservice.loadBalancer;
                    let urlBase = `http://${loadBalancer.loadBalancerDnsName}`;
                    if (container.portListener) {
                        urlBase += `:${container.portListener}`;
                    }
                    urlBase += '/';
                    // URL BASE
                    createSsm( this, {
                        name: container.baseUrlParameter, valueVersionDefault: urlBase,
                        descriptionStringParameter: `${props.outputParameters[container.baseUrlParameter].description} - ${new Date().toISOString()}`,
                        paramExist: props.outputParameters[container.baseUrlParameter].exists,
                        ownerStack: true
                    });
                }
                roles.push(microservice.cluster.taskRole);
                clusterSecurityGroups.push(microservice.securityGroup);
                // additional policies permissions
                const additionalPolicy = createAdditionalPolicies( this, container.policy );                
                microservice.cluster.taskRole.attachInlinePolicy(additionalPolicy);
                microserviceContainers.push(microservice);
            }
        }
        // Siempre se da permisos sobre el KMS para que pueda leer datos de otros streams y de dynamo
        if(streamKey || sqsKey || databaseKey){
            roles.forEach(role => {
                if (streamKey) {
                    streamKey.grantEncryptDecrypt(role);
                }
                if (sqsKey) {
                    sqsKey.grantEncryptDecrypt(role);
                }
                if(databaseKey)
                    databaseKey.grantEncryptDecrypt(role);
            });
        }       
        // STREAM
        if (stream) {
            const { statusDatabasePolicy } = createDatabaseState( this, getParam('kinesisDatabase') );
            roles.forEach(role => {
                role.attachInlinePolicy(statusDatabasePolicy);
                // kinesis stream permissions
                msStream.grantRead(role);
                msStream.grantWrite(role);
            });
        }
        // SQS
        if (sqs) {
            roles.forEach(role => {
                arraySQS.forEach(awssqs => {
                    // SQS queue permissions
                    awssqs.grantConsumeMessages(role);              
                    awssqs.grantSendMessages(role);
                });             
            });
        }
        // BASE DE DATOS
        if (databaseParams && databaseParams.relational) {
            const secretManagerKey = getKeyFromArn( this, 'secret-manager-key', databaseParams.relational.secretManagerKey );
            const encriptionKey = getKeyFromArn( this, 'relational-encription-key', databaseParams.relational.encriptionKey );
            const dbSubnets = getParam( 'network.sensibleSubnetsIds' ).map((id, index) =>
                getSubnetFromId(this, `sensible-sn-${index.toString()}`, id)
            );

            const dataDb = createRelationalDatabase(
                this,
                Object.assign(databaseParams.relational, {
                    vpc,
                    dbSubnets,
                    secretManagerKey,
                    encriptionKey,
                    clusterSecurityGroups,
                    ...props.dbData
                })
            );
            const relationalDb = dataDb.relationalDb;
            const dbSecret = dataDb.dbSecret;
            roles.forEach(role=> {
                dbSecret.grantRead(role);
                secretManagerKey.grantEncryptDecrypt(role);
                encriptionKey.grantEncryptDecrypt(role);
                //relationalDb.grantDataApiAccess(role);
            });
            // DB_SECRET
            createSsm( this, {
                name: databaseParams.relational.dbSecretParameter, valueVersionDefault: dbSecret.secretName,
                descriptionStringParameter: `${props.outputParameters[databaseParams.relational.dbSecretParameter].description} - ${new Date().toISOString()}`,
                paramExist: props.outputParameters[databaseParams.relational.dbSecretParameter].exists,
                ownerStack: true
            });
        }
        if (databaseParams&& databaseParams.noRelational&& databaseParams.noRelational.tables) {
            roles.forEach((role, index) => {
                createDatabase(
                    this,
                    Object.assign(databaseParams.noRelational, {
                        role: role,
                        indexRole: index,
                        databaseKey,
                        tableExist: props.tableExist,
                    })
                );
                props.tableExist.forEach(table => {
                    table.exist = true;
                });
            });
        }

        // bucket and permission policy
        const bucketProps = getParam('bucket');
        if (bucketProps && bucketProps.createBucket) {
            createBucket(
                this,
                Object.assign(bucketProps, {
                    bucketExist: props.bucketExist,
                })
            );
            // BUCKET_NAME
            createSsm( this, {
                name: bucketProps.bucketNameParameter, valueVersionDefault: bucketProps.bucketName,
                descriptionStringParameter: `${props.outputParameters[bucketProps.bucketNameParameter].description} - ${new Date().toISOString()}`,
                paramExist: props.outputParameters[bucketProps.bucketNameParameter].exists,
                ownerStack: true
            });
        }
        // parameters
        props.parameters.forEach(paramInfo => {
            paramInfo.list.forEach(param => {
                const parameter = createSsm(
                    this, {
                        name: `/${paramInfo.prefix}/${param.name}`,
                        valueVersionDefault: param.defaultValue,
                        descriptionStringParameter: param.description,
                        paramExist: param.exists
                    }
                );
                microserviceContainers.forEach(container => {
                    parameter.grantRead(container.cluster.taskRole);
                });
            });
        });     

        // buckets
        console.log(props.buckets);
        props.buckets.forEach(bucketProps => {          
            if (bucketProps && bucketProps.createBucket) {
                createBucket(
                    this,
                    bucketProps
                );
                // BUCKET_NAME
                createSsm( this, {
                    name: bucketProps.bucketNameParameter, valueVersionDefault: bucketProps.bucketName,
                    descriptionStringParameter: `${props.outputParameters[bucketProps.bucketNameParameter].description} - ${new Date().toISOString()}`,
                    paramExist: props.outputParameters[bucketProps.bucketNameParameter].exists,
                    ownerStack: true
                });
            }
        });
  }
}

module.exports = { CdkIacMicroservicesStack }

and my file yml

stackName: IacWireTransferMicroservicesStack
accountID: '${/GLOBAL/ACCOUNT_NUMBER}'
region: us-east-1
outputParameters:
  - name: /GLOBAL/PRODUCER_WIRETRANSFER_BASE_URL
    description: Url del productor del dominio WIRETRANSFER
  - name: /WIRETRANSFER/DB_SECRET
    description: Nombre completo con sufijo del secreto que contiene la información de la conexión a la base de datos de wiretransfer
stream:
  streamName: Wiretransfer
  shardCount: 1
  kmsArn: arn:aws:kms:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:key/${/GLOBAL/KMS_KINESIS}
sqs:
  - sqsName: WireTransfer
    kmsArn: arn:aws:kms:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:key/${/GLOBAL/KMS_KINESIS}         
kinesisDatabase:
  databaseKey: arn:aws:kms:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:key/${/GLOBAL/KMS_DYNAMO}
  policyName: wiretransfer-kinesisdb
  table:
    name: wiretransfer-stream
    tableName: wiretransfer-stream-state
bucket:
  createBucket: false
network:
  vpcId: ${/GLOBAL/VPC_ID}
  subnetsIds:
    - ${/GLOBAL/SUBNET1_ID}
    - ${/GLOBAL/SUBNET2_ID}
  sensibleSubnetsIds:
    - ${/GLOBAL/SENSIBLE_SUBNET1_ID}
    - ${/GLOBAL/SENSIBLE_SUBNET2_ID}
  subnetGroupName: default
database:
  isRelational: true
  noRelational:
    tableArn: arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/
    kmsArn: arn:aws:kms:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:key/${/GLOBAL/KMS_DYNAMO}
relational:
   dbSecretParameter: /WIRETRANSFER/DB_SECRET
   defaultDatabaseName: wiretransfer
   mySqlVersion: '8.0.34'
   encriptionKey: arn:aws:kms:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:key/${/GLOBAL/KMS_RDS}
   secretManagerKey: arn:aws:kms:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:key/${/GLOBAL/KMS_SECRETS}
   username: wiretransferDatabaseAdmin
   securityGroup:
     name: vpc-group20230520172742220100000001
     port: 3306
     sgIngressRuleDescription: Ingress rule for consumer fargate cluster
   cluster:
     backupRetention: 3
   subnetGroup:
     description: subnet group for wiretransfer relational database
parameters:
  - prefix: WIRETRANSFER
    list:
      - name: LOGLEVEL
        description: Nivel de logs
        defaultValue: 'info'
      - name: URL_LOAD_SECRET
        description: Default url mi post su red
        defaultValue: 'https://mipossuredqa.matrixtech.com.co/main/menu?t='
      - name: DB_SECRET
        description: Nombre completo con sufijo del secreto que contiene la información de la conexión a la base de datos de Wiretansfer
        defaultValue: wiretransfer-relational-rds-secret_23
microservice:
  containers:
    - baseUrlParameter: /GLOBAL/PRODUCER_WIRETRANSFER_BASE_URL
      name: wiretransfer-ms
      repoArn: arn:aws:ecr:us-east-1:${/GLOBAL/DEPLOYMENT_ACCOUNT_NUMBER}:repository/microservice-wiretransfer-develop
      port: 8080
      securityGroupIngress:
        - cidr: 10.150.8.0/23
          description: VPC de Developer      
        - cidr: 172.17.99.0/24
          description: VPN Matrixtech
        - cidr: 172.18.108.0/24
          description: VDI Desarrollo
        - cidr: 172.35.1.0/24
          description: Escritorios remotos sede
        - cidr: 172.35.2.0/24
          description: Escritorios remotos sede            
      portListener: 8093
      loadBalancerArn: ${/GLOBAL/GLOBAL_LOAD_BALANCER_ARN}
      environment:
        ENVIRONMENT: ${/GLOBAL/ENVIRONMENT}
        REGION: us-east-1
        PORT: '8080'
      metric:
        type: memory
        max: 2
        min: 1  
        percent: 80
        scaleOutCooldown: 120
        scaleInCooldown: 300
      policy:
        name: microservice-wiretransfer-policy
        statements:
          - 0:
            action:
              - s3:GetObject*
              - s3:GetBucket*
              - s3:List*
            resource:
              - arn:aws:s3:::${/GLOBAL/BUCKET_CERTS}
              - arn:aws:s3:::${/GLOBAL/BUCKET_CERTS}/*
              - arn:aws:s3:::configuration-${/GLOBAL/ACCOUNT_NUMBER}/*
              - arn:aws:s3:::configuration-${/GLOBAL/ACCOUNT_NUMBER}                   
          - 1:
            action:
              - ssm:GetParameter
            resource:
              - arn:aws:ssm:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:parameter/WIRETRANSFER/*
              - arn:aws:ssm:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:parameter/GLOBAL/*
              - arn:aws:ssm:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:parameter/PRODUCTS/KINESIS_LIMIT
              - arn:aws:ssm:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:parameter/PRODUCTS/KINESIS_POLL_DELAY
          - 2:
            action:
              - kinesis:DescribeStreamSummary
              - kinesis:GetRecords
              - kinesis:GetShardIterator
              - kinesis:ListShards
              - kinesis:PutRecord
              - kinesis:PutRecords
              - kinesis:SubscribeToShard
            resource:
              - arn:aws:kinesis:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:stream/Notifier
              - arn:aws:kinesis:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:stream/Products
              - arn:aws:kinesis:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:stream/Payments
              - arn:aws:kinesis:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:stream/Legacy
          - 3:
            action:
              - dynamodb:DescribeTable
              - dynamodb:GetItem
              - dynamodb:PutItem
              - dynamodb:Scan
              - dynamodb:UpdateItem
              - dynamodb:Query
            resource:
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/products-stream-state
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/master-config
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/mipos-tx 
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/master-export-file
          - 4:
            action:
              - secretsmanager:DescribeSecret
              - secretsmanager:GetSecretValue
              - secretsmanager:ListSecrets
              - secretsmanager:ListSecretVersionIds
            resource:
              - arn:aws:secretsmanager:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:secret:${/GLOBAL/KEYAES}                              
              - arn:aws:secretsmanager:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:secret:${/GLOBAL/MIPOS_SECRET}
              - arn:aws:secretsmanager:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:secret:${/WIRETRANSFER/DB_SECRET}*   
          - 5:
            action:
              - dynamodb:BatchGetItem
              - dynamodb:GetRecords
              - dynamodb:GetShardIterator
              - dynamodb:Query
              - dynamodb:GetItem
              - dynamodb:Scan
              - dynamodb:ConditionCheckItem
              - dynamodb:BatchWriteItem
              - dynamodb:PutItem
              - dynamodb:UpdateItem
              - dynamodb:DeleteItem
            resource:
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/transactions            
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/hierarchy-parameters                
              - arn:aws:dynamodb:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:table/global-queries              
          - 6:
            action:
              - xray:*
            resource:
              - "*"  
          - 7:
            action:
              - sqs:SendMessage
              - sqs:GetQueueAttributes
              - sqs:GetQueueUrl
            resource:
              - arn:aws:sqs:us-east-1:${/GLOBAL/ACCOUNT_NUMBER}:Transaction  
          - 8:
            action:
              - s3:*
            resource:
              - arn:aws:s3:::files-${/GLOBAL/ACCOUNT_NUMBER}
              - arn:aws:s3:::files-${/GLOBAL/ACCOUNT_NUMBER}/*             
      ssm:
        name: ms-wiretransfer-version
        valueVersionDefault: latest
        descriptionStringParameter: name version parameter

I tried in various ways:

I specified the ARN directly in the YAML without using the parameters from GLOBAL/DB_SECRET/.
I created it manually in the Secrets Manager module, but there is an error with GetValueSecret.
I created a new policy and associated it manually with the role.

`{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:*",
                "cloudformation:CreateChangeSet",
                "cloudformation:DescribeChangeSet",
                "cloudformation:DescribeStackResource",
                "cloudformation:DescribeStacks",
                "cloudformation:ExecuteChangeSet",
                "docdb-elastic:GetCluster",
                "docdb-elastic:ListClusters",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcs",
                "kms:DescribeKey",
                "kms:ListAliases",
                "kms:ListKeys",
                "lambda:ListFunctions",
                "rds:DescribeDBClusters",
                "rds:DescribeDBInstances",
                "redshift:DescribeClusters",
                "tag:GetResources",
                "secretsmanager:GetSecretValue"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "lambda:AddPermission",
                "lambda:CreateFunction",
                "lambda:GetFunction",
                "lambda:InvokeFunction",
                "lambda:UpdateFunctionConfiguration"
            ],
            "Resource": "arn:aws:lambda:*:*:function:SecretsManager*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "serverlessrepo:CreateCloudFormationChangeSet",
                "serverlessrepo:GetApplication"
            ],
            "Resource": "arn:aws:serverlessrepo:*:*:applications/SecretsManager*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::awsserverlessrepo-changesets*",
                "arn:aws:s3:::secrets-manager-rotation-apps-*/*"
            ]
        }
    ]
}`

Object show up in log, but cannot access some of its properties [closed]

I’m calling an api from a backend that returns information such as department name, id, and its plant id, the data is returned as an array of objects

browser log screenshoot

const { data }: { data: DepartmentType[] } = await axios.post(
      "https://localhost:4500/departments",
      {
        plantId: plantId,
      },
      {
        headers: {
          "Content-Type": "application/json", 
          "session-id": "XXXXXXXXXXXXXXXXXXXX",
        },
      }
    );

  
    console.log("api department")
    console.log("object array : ",data)
    console.log("first index : ",data[0])
    console.log("accessing department_id : ",data[0]?.department_id)
    console.log("accessing department_name : ",data[0]?.department_name)
    console.log("accessing plant_id : ",data[0]?.plant_id)
    console.log("has department_id ? ",data[0]?.hasOwnProperty("department_id"))
    console.log("has department_name ?", data[0]?.hasOwnProperty("department_name"))
    console.log("has plant_id ? ",data[0]?.hasOwnProperty("plant_id"))

does anyone have any idea why I can’t access some of its properties?

I expect to be able to retrieve the properties from the object

Get response data from intercepted http request

I’m using Firefox, and creating a personal web extension. I’m trying to get the data returned by GET requests sent out by a website. I can successfully intercept the requests using the background script:

browser.runtime.onInstalled.addListener(() => {
    browser.webRequest.onCompleted.addListener(function(details) {
        console.log(details);
    }, {urls: ["https://www.tumblr.com/*"]});
});

But… the data I get doesn’t seem to be what I want. The response is often like:

Object { requestId: "42624", url: "https://www.tumblr.com/api/v2/user/counts?unread=true&inbox=true&unread_messages=true&blog_notification_counts=true&private_group_blog_unread_post_counts=true", originUrl: "https://www.tumblr.com/a-blog", documentUrl: "https://www.tumblr.com/a-blog", method: "GET", type: "xmlhttprequest", timeStamp: 1701137740118, tabId: 128, frameId: 0, parentFrameId: -1, … }
cookieStoreId: "firefox-private"
documentUrl: "https://www.tumblr.com/a-blog"
frameAncestors: Array []
frameId: 0
fromCache: false
incognito: true
ip: "XXX.XXX.XXX.XXX"
method: "GET"
originUrl: "https://www.tumblr.com/a-blog"
parentFrameId: -1
proxyInfo: null
requestId: "X"
requestSize: 0
responseSize: 0
statusCode: 200
statusLine: "HTTP/2.0 200 "
tabId: 128
thirdParty: false
timeStamp: 1701137740118
type: "xmlhttprequest"
url: "https://www.tumblr.com/api/v2/user/counts?unread=true&inbox=true&unread_messages=true&blog_notification_counts=true&private_group_blog_unread_post_counts=true"
urlClassification: Object { firstParty: (2) […], thirdParty: [] }

What’s confusing to me here is how it returns “responseSize: 0” despite being able to see a valid response in Inspect. The response I want is json like:

{
  "blog_notification_counts":
  [
    {
      "blog_uuid":"t:<STRING>",
      "count":48
    }
  ],
  "unread":855,
  "inbox":4,
  "unread_messages":
  {
    "<UUID>":
    {
      "XXX":1,
      "XXX":1,
      "XXX":2
    }
  },
  "private_group_blog_unread_post_counts":[],
  "next_from":1701137956
}

The important sections are the “blog_notification_counts”, “unread”, “inbox”, and “unread_messages”. If anyone has any idea of how to obtain the given ‘correct’ response data instead of the lack of a response I get from intercepting it (it still updates correctly i think!?) that would be perfect.

Thank you!

What I tried and what I expected:

I wrote the background script to intercept GET requests exiting the website, but the data I got did not contain the response I wanted.

It is possible to know when the user clicked on “Allow” or “Deny” while using the Geolocation API and browser permissions?

I need to know whether the user clicked on “Allow” or “Deny” while accessing a webpage built using React+Typescript but so far I have been unable to get it working properly. See the following piece of code:

import { useEffect, useState } from "react";
import useGeolocation from "./useGeolocation";

export default function App() {
  const [locationAccess, setLocationAccess] = useState<boolean>(false);

  useEffect(() => {
    navigator.permissions
      .query({ name: "geolocation" })
      .then((permissionStatus) => {
        setLocationAccess(permissionStatus.state === "granted");
      });
  }, [locationAccess]);

  const geoLocation = useGeolocation({ locationAccess });

  console.log("geoLocation", geoLocation);

  return <></>;
}

When I access the page for the first time and you are requested to give permission to access your geolocation I am able to see the following object being return:

{
    "loaded": false,
    "coordinates": {
        "lat": "",
        "lng": ""
    },
    "locale": "",
    "countryCode": "",
    "error": {}
}

which is fine because useGeolocation does return such an object if no access has been allowed| or denied. Now if I click on “Allow” I would expect right away to see the following object being returned:

{
    "loaded": true,
    "coordinates": {
        "lat": 28.504016,
        "lng": -82.5510363
    },
    "locale": "en-us",
    "countryCode": "US",
    "error": {}
}

but instead, I have to reload the page to get the values back. Is it possible to achieve this once the user clicks the “Allow” button?

I have set up a CodeSanbox if you need access to the code and to play with it here

How to make JavaScript animations to take place simultaneously?

I am building a website wherein there are multiple carousels. Whenever the user clicks on any carousel, the viewport vertically centers the carousel after it expands. However, I want to make it so that the viewport vertically centers as the project’s dimensions change and not after.

My JavaScript is as follows:

import { gsap } from "gsap";
import { Draggable } from "gsap/Draggable";
gsap.registerPlugin(Draggable);

const bodyElement = document.querySelector('.wrapper');
const mainElement = document.querySelector('main');
const sections = document.querySelectorAll('section');

let isDragging = false;
let lastTouch = 0;
let isScrolling = false;
let scrollSpeed = 0;
let lastScrollTime = 0;
let lastScrollDelta = 0;
let sx = 0,
  sy = 0;
let dx = sx,
  dy = sy;
let scrollTimeout;
let expandTimeout;

sections.forEach(section => {
  const carousel = section.querySelector('.carousel');
  let startX = 0;

  carousel.addEventListener('mousedown', e => {
    isDragging = true;
    startX = e.clientX || e.touches[0].clientX;
  });

  carousel.addEventListener('mouseup', e => {
    if (isDragging) {
      isDragging = false;
      const distance = e.clientX || e.changedTouches[0].clientX - startX;
      const momentum = 0.9; // Adjust momentum factor as needed
      const duration = 750; // Adjust duration for animation
      const distanceWithMomentum = distance * momentum;
      const targetX = carousel.scrollLeft + distanceWithMomentum;

      gsap.to(carousel, { scrollLeft: targetX, duration: duration, ease: 'power2.out' });
    }
  });

  carousel.addEventListener('mouseleave', () => {
    isDragging = false;
  });

  const hidden = section.querySelectorAll('.hidden');

  section.addEventListener('click', e => {
    if (!isDragging && !section.classList.contains('active')) {
      sections.forEach(s => {
        if (s !== section && s.classList.contains('active')) {
          s.classList.remove('active');
          const projectInfo = s.querySelector('.project-info');
          projectInfo.querySelectorAll('.hidden.showObject').forEach(obj => {
            obj.classList.remove('showObject');
          });
          s.style.transition = 'transform 0.75s ease-in-out, height 0.75s, width 0.75s ease-in-out';
          s.style.transform = 'none';
          s.style.height = '30vh';
        }
      });

      // Add 'active' class and trigger scroll animation
      section.classList.add('active');
      section.style.transition = 'transform 0.75s ease-in-out, height 0.75s, width 0.75s ease-in-out';
      section.style.transformOrigin = 'center center';
      section.style.height = '80vh';
      section.style.width = '100%';

      // Listen for the transition start on the section element
      section.addEventListener('transitionend', function transitionStart(event) {
        if (event.propertyName === 'width') {
          // Smoothly scroll to the selected section
          bodyElement.classList.add('scrolling');
          section.scrollIntoView({ behavior: 'smooth', block: 'center' });

          // Remove the transition event listener after initiating the scroll
          section.removeEventListener('transitionend', transitionStart);
        }
      });

      // Add and remove the expand class
      bodyElement.classList.add('expand');
      clearTimeout(expandTimeout);
      expandTimeout = setTimeout(() => {
        bodyElement.classList.remove('expand');
      }, 0);
    }
  });

  section.addEventListener('touchstart', () => {
    isDragging = true;
  });

  section.addEventListener('touchend', () => {
    isDragging = false;
    lastTouch = new Date().getTime();
  });
});

window.addEventListener('wheel', event => {
  const currentTime = new Date().getTime();
  const isTrackpad = currentTime - lastTouch < 100; // Adjust the time threshold as needed

  if (!isDragging) {
    const delta = event.deltaY || event.detail || -event.wheelDelta;

    if (Math.abs(delta) > 1) {
      if (isTrackpad || event.deltaX !== undefined || event.deltaY !== undefined) {
        bodyElement.classList.add('expand');
        setTimeout(() => {
          bodyElement.classList.remove('expand');
        }, 100); // Adjust the delay time as needed
      }
    }
  }
});

function easeScroll() {
  sx = window.pageXOffset;
  sy = window.pageYOffset;
}

window.requestAnimationFrame(render);

function render() {
  dx = li(dx, sx, 0.07);
  dy = li(dy, sy, 0.07);
  dx = Math.floor(dx * 100) / 100;
  dy = Math.floor(dy * 100) / 100;

  mainElement.style.transform = `translate3d(-${dx}px, -${dy}px, 0px)`;

  document.body.style.height = '0';
  window.requestAnimationFrame(render);
}

function li(a, b, n) {
  return (1 - n) * a + n * b;
}

function updateScroll() {
  if (scrollSpeed !== 0) {
    window.scrollBy(0, scrollSpeed);
    scrollSpeed *= 0.9;

    if (Math.abs(scrollSpeed) < 0.1) {
      scrollSpeed = 0;
    }
  }
  requestAnimationFrame(updateScroll);
}

updateScroll();

I am willing to use any plugins or jQuery to fix this. thank you in advance!

Tried using jQuery but it didn’t work. Tried using GSAP.ScrollTo as well but that didn’t work.

How to reuse createApp() method in Vue Server Side rendering

I have an ejs file excerpt that is as follows:

<body>
    <% var test = "App"; %>
    <div id="app"></div>
    <% if (environment === 'production') { %>
    <script type="module" src="<%= manifest['main.ts'].file %>"></script>
    <% } else { %>
    <script type="module" src="http://localhost:5173/@vite/client"></script>
    <script type="module" src="http://localhost:5173/main.ts"></script> <!--line in question-->
    <% } %>
  </body>

this uses server side rendering to run main.ts, which is as follows

import { createSSRApp } from 'vue'
import App from "./src/views/App.vue"

createSSRApp(App).mount('#app')

I obviously need to access different .vue files other than App.vue, but that would mean creating several different versions of the main.ts file, all pointing to seperate .vue files. This seems incredibly redundant and inefficient. How can I change what .vue file main.ts is pointing to based on some information in the .ejs file?

I attempted to import App.vue directly into the .ejs file but nothing rendered because the app wasn’t mounted.

If there is a fundamental flaw in my rendering method, don’t hesitate to call it out. Everything works in this format but I don’t see how this can scale.

Can I use a fetching library like SWR when using ccxt in react?

By using the fetching library, you can take advantage of many benefits such as isLoading, isError, caching, auto refreshing, mutatuion, and conditional fetching.
When using ccxt, I wonder if these benefits can be maintained by using it with the fetching library.

const ccxtBitmex = new ccxt['bitmex']({
  proxyUrl: PROXY_URL,
  apiKey: bitmexApiKey,
  secret: bitmexSecret,
})

export const fetchBalance = async () => {
  return await ccxtBitmex.fetchBalance()
}

// Where is the opportunity to cut in?

If this is not possible, it would be difficult to find a reason to use the ccxt library in react. Maybe I should just access the exchange api without ccxt?

Uploading file triggers the “Unknown Error” caused by ERR_UPLOAD_FILE_CHANGED

I am using C# ASP.NET Web API for the back-end API and angular 16 for the front-end. When I upload a file to my localhost controller, all is good until I change the content of the file. When I do that I am getting an error “Unknown Error”, but it is caused by “net::ERR_UPLOAD_FILE_CHANGED” – that what my Chrome console window displays.
Why am I not getting simply some exception that would clearly spell out what the problem is (stating that file has changed) instead of reporting “Unknown Error” which is pretty much useless.
This is what my Chrome console displays:
enter image description here

Optimization Challenge- Merging arrays

I’d like to host a challenge,
I’ve made a JavaScript function that is very unoptimized and can be improved in a million ways,
Could you optimize it to the max?

function merge(array1, array2, array3, array4, array5){
  var result = [];
  var arrays = [array1, array2, array3, array4, array5];
  
  for (var i = 0; i < arrays.length; i++) {
    var array = arrays[i];
    for (var j = 0; j < array.length; j++) {
      var item = array[j];
      if (result.indexOf(item) === -1) {
        result.push(item);
      }
    }
  }
  
  return result;
}

const x = ['hi','hello','hey']
const y = ['apple','banana','orange']
const z = ['hie','helloe','heye']
const w = ['applei','bananai','orangei']
const e = ['hio','helloo','heyo']

console.log(merge(x,y,z,w,e));

Good luck optimizing it as best as you can!

I’ll give out a 2 hints:

  1. Instead of multiple parameters, you could turn it into one parameter that supports infinite arrays,

  2. Instead of using function(), there is an another way that uses less memory