How to initialized an observable for async pipe in the template trying to mimic an assignation in the subscription?

The current code is trying to use the async pipe approach instead of using an assignation in the subscription. But if the delay is happeing in the service, the initial value is not rendering in the template, when the data is ready the value is rendering as expected, I am trying to mimic the rendeing behavior that is presented when I am using this this.title2.

The component:

title$: Observable<string> = of('Default Title'); // I am not sure if this assignation is right
title2 = 'Default Title 2';

constructor(private sampleService: SampleService) {}

// Load title has a delay in the response
this.title$ = this.sampleService.loadTitle();

this.sampleService.loadTitle().subscribe((title) => {
  this.title2 = title; // the assignation 
});

The template:

<h4>{{ title$ | async }}</h4>
<h4>{{ title2 }}</h4>

The sample is in this stackblitz

Create excel-like data structure from JSON object Javascript Typescript

Hi I would like to convert a JSON type of data to CSV or Excel-like data with columns

here is JSON that contains the date name of the product and the price

let products = [
    [
        { date: '2022-05-09', name: 'laptop', price: '2245.430531634567' },
        { date: '2022-05-10', name: 'laptop', price: '2343.5108884928645' },
        { date: '2022-05-11', name: 'laptop', price: '2072.1086793072855' },
        { date: '2022-05-12', name: 'laptop', price: '1961.701582831061' },
        { date: '2022-05-13', name: 'laptop', price: '2014.4182339084884' },
        { date: '2022-05-14', name: 'laptop', price: '2056.273914657406' },
        { date: '2022-05-15', name: 'laptop', price: '2145.7066657035143' },
        { date: '2022-05-16', name: 'laptop', price: '2022.7259340437865' },
        { date: '2022-05-17', name: 'laptop', price: '2090.409245952252' },
        { date: '2022-05-18', name: 'laptop', price: '1993.262079076959' }
    ],
    [
        { date: '2022-05-09', name: 'usbCable', price: '0.9999087550995304' },
        { date: '2022-05-10', name: 'usbCable', price: '0.9997913625904791' },
        { date: '2022-05-11', name: 'usbCable', price: '0.9958721390751034' },
        { date: '2022-05-12', name: 'usbCable', price: '0.9976093690492182' },
        { date: '2022-05-13', name: 'usbCable', price: '0.9982388360597627' },
        { date: '2022-05-14', name: 'usbCable', price: '0.9987798583521733' },
        { date: '2022-05-15', name: 'usbCable', price: '0.9990687532601263' },
        { date: '2022-05-16', name: 'usbCable', price: '0.9987786971425011' },
        { date: '2022-05-17', name: 'usbCable', price: '0.998909095447568' },
        { date: '2022-05-18', name: 'usbCable', price: '0.998884287678029' }
    ],
    [
        { date: '2022-05-09', name: 'server', price: '30296.953400053055' },
        { date: '2022-05-10', name: 'server', price: '31022.905412225315' },
        { date: '2022-05-11', name: 'server', price: '28936.35503111219' },
        { date: '2022-05-12', name: 'server', price: '29047.751003853846' },
        { date: '2022-05-13', name: 'server', price: '29283.103811543002' },
        { date: '2022-05-14', name: 'server', price: '30101.266445984806' },
        { date: '2022-05-15', name: 'server', price: '31305.1125686764' },
        { date: '2022-05-16', name: 'server', price: '29862.918241291864' },
        { date: '2022-05-17', name: 'server', price: '30425.85727679598' },
        { date: '2022-05-18', name: 'server', price: '29421.647697692864' }
    ]
];

I would like to get this type of data after converting:

date;laptop;usbCable;server
2022-05-09;2245.430531634567;0.94545;30296.953400053055
2022-05-10;2247.430531634567;0.95545;31296.953400053055
2022-05-11;2243.430531634567;0.97545;32296.953400053055
2022-05-12;2243.430531634567;0.92545;34296.953400053055

I was browsing lodash library to have a conversion like this but didn’t manage to find anything as well was checking json2csv converters but they always give me flat type of data output.

enter image description here

FizzBuzz Problem – I failed to write logic with more functionality. I already explained in the Comment Section of Code

My FizzBuzz application which counts from 1 to 100 and outputs either the corresponding number or if one of the following rules apply output the corresponding text.

Rules:

  • dividable by 3 without a remainder -> Fizz
  • dividable by 5 without a remainder -> Buzz
  • dividable by 3 or 5 without a remainder -> FizzBuzz

I want to add this? Please refactor this code so that it can be extended in the future with other rules, such as

  • “if it is dividable by 7 without a remainder output Bar”
  • “if multiplied by 10 is larger than 100 output Foo”

You can uncomment if($i * 10 > 100) first and then see the result. I need exactly the same output when I removed this below code. But its compulsory is greater than 100 then it would be Foo, and follow the same structure for example at 30: it should be FizzBuzz not FizzBuzzFoo

My Code Is:

 class FizzBuzzEngine
    {
       public function run($limit = 100)
    {
     for ($i = 1; $i <= $limit; $i++) {
        $output = '';
        if ($i % 3 == 0) {
            $output .= "Fizz";
        }
        if ($i % 5 == 0) {
            $output .= "Buzz";
        }
        
        if($i * 10 > 100){
            $output = "";
            $output = "Foo";
        }
        if($i % 7 == 0 ){
            $output = "";
            $output.= "Bar";
        }
        if (empty($output)) {
            $output = 'None';
        }
        echo sprintf('%d: %s', $i, $output . PHP_EOL);
     }
  }
}

$engine = new FizzBuzzEngine();
$engine->run();

sending SNS push notifications to multiple devices

I need to send push notifications to multiple devices using aws-sns-javascript
when I create createPlatformEndpoint I can just add one device token but I need to send notifications to multiple devices like an array token

Create Platform Application

var params = {
  Attributes: {
    'PlatformCredential': 'My API KEY'
  },
  Name: 'dist-ba-dist',
  Platform: 'GCM'
};
sns.createPlatformApplication(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Create Platform Endpoint

var params = {
  PlatformApplicationArn:`data.PlatformApplicationArn` , 
  Token: 'My Device Token',
  CustomUserData: 'STRING_VALUE'
};
sns.createPlatformEndpoint(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Sends a message to an Amazon SNS topic

var payload = {
    default: 'Hello World',
    GCM: {
        notification: {
            body: "Sample message",
            title: "Hello World"
        }
    }
};
console.log("endpointArn", data.EndpointArn)
payload.GCM = JSON.stringify(payload.GCM);
payload = JSON.stringify(payload);
console.log('payload', payload)

console.log('sending push');
sns.publish({
    Message: payload,
    MessageStructure: 'json',
    TargetArn: data.EndpointArn,
}, function (err, data) {
    if (err) {
        console.log(err.stack);
        return;
    }

    console.log('push sent');
    console.log(data);
});   

How would I display text under an iframe?

First of all, I’m new here, and I really tried my best to get rid of the X/Y problem. I am trying to display some sort of loading text under a youtube embed. This is what I have tried so far.

$(document).ready(function() {
    $('#song1').hover(function() {
        $(this).html('rickroll <p id="song1load" style="position: absolute">Loading...</p><iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>')
        $(this).animate({
            maxHeight: '344px',
            height: '344px'
        })
    }, function() {
        $(this).html('1. door')
        $(this).animate({
            maxHeight: '30px',
            height: '30px'
        })
    })
})
body {
    background-color: black;
    color: white
}

.video {
  background-color: white;
  max-width: 560px;
  width: 560px;
  max-height: 30px;
  height: 30px;
  border-radius: 10px;
  color: black;
  text-align: center;
  font-family: Koulen;
  margin: auto;
  margin-bottom: 100px;
  overflow: hidden;
}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <link rel="stylesheet" href="Resources/stylesheet.css">
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Koulen&display=swap" rel="stylesheet">
  </head> 
  <body>
    <div class="video" id="song1">rickroll<p id="song1load"></p></div>
  </body>
</html>

I don’t think stackoverflow can load yt embeds in snippets, but you hopefully get my point. I’m open to any solutions!

How to resolve Bad Request error in graphql api

const endpoint = “http://localhost:1337/graphql”;
const headers = {
“content-type”: “application/json”,
};
const graphqlQuery = {
“query” : mutation AddNewProducts ($deal_type:String!, $products: [ProductInput]) { addProductsByDeals( deal_type: $deal_type, products:$products ){ id title } } ,
“variables” : {
“deal_type”: EBAY_DEAL_TYPE,
“products” : offers
}
}

const response = await axios({
url:endpoint,
method:’POST’,
headers : headers,
data: graphqlQuery
})

Getting Error : Bad request 400

how do i get the coordinates of a click in jquery?

I have a div in it with an 8×8 div. I want to use jquery for practicing. How can i get which div in which row and column i clicked on? I tried to use event.pageX and event.pageY but it specifies the coordinate of the click and I would like to get the row and the column

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="script.js"></script>
    <title></title>
</head>
<body>

    <div id="gameArea"></div>

</body>
</html>

I have a css file too

body{
    margin: 0;
    padding: 20px;
}

.tile {
    position: absolute;
    background-color: rgb(115, 255, 50);
    cursor: pointer;
}

.tile:hover {
    background-color: darkgreen;
}

.disabled {
    background-color: black;
    border:1px solid black;
}

.enabled{
    background-color: white;
    border: 1px solid white;

}

#gameArea {
    background-color: black;
    position: relative;
    padding: 0px;
    border: 2px solid black;

}

And here’s my js file with my code

const max_clicks = 3;

const table_sz = 8;
const tile_sz = 88;
const border_w = 4;
const margin_w = 2;


let game_area;


function createTile(row, col){

    let tile;

    if ((row + col) % 2 === 0){

        tile = $('<div class = "tile disabled"></div>');
    }
    else{

        tile = $('<div class = "tile enabled"></div>');

        tile.attr('clicks', 0);
    }

    tile.css("margin", margin_w.toString() + "px");
    tile.css("border-width", border_w.toString() + "px");

    tile.attr('row', row);
    tile.attr('col', col);

    tile.css( {

        top: row * (tile_sz + 2 * (border_w + margin_w) ),
        left: col * (tile_sz + 2 * (border_w + margin_w) ),
        height: tile_sz,
        width: tile_sz,
    } );

    return tile;
}

function createTable(){

    for (let row = 0; row < table_sz; ++row){

        for (let col = 0; col < table_sz; ++col) {

            let tile = createTile(row, col);

            game_area.append(tile);
        }
    }
}

function createGameArea(){

    game_area = $('#gameArea');

    game_area.css( {

        height: 800,
        width: 800
    } );
}




function selectTileAt(position){

    return $(".tile[row=" + position[0].toString() + "][col=" + position[1].toString() + "]");
}



$(document).ready(function(){

    createGameArea();

    createTable();

} );

I don’t understand this error : “SequelizeEagerLoadingError”

I want to test my routes.

controllers/post.js :

exports.getAllPost = (req, res, next) => {
    /*** on récupère tous les posts ***/
    Post.findAll({
            include: [{
                model: User,
                attributes: ['username']
            }],
        })
        /*** si tout est ok ***/
        .then(post => res.status(200).json({
            post
        }))
        /*** sinon on envoie une erreur ***/
        .catch(error => res.status(400).json({
            error,
        }))

};

models/index.js :

require('dotenv').config();
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const { applyExtraSetup } = require('./extra-setup');

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.users = require("./user.js")(sequelize, Sequelize);
db.posts = require("./post.js")(sequelize, Sequelize);
db.comments = require("./comment.js")(sequelize, Sequelize);

applyExtraSetup(sequelize);

module.exports = db;

models/post.js :

module.exports = (sequelize, Sequelize) => {
    const Post = sequelize.define(
      "post", {
        userId: {
          type: Sequelize.INTEGER
        },
        title: {
          type: Sequelize.STRING(40)
        },
      },     
    );
    return Post;
  };

models/extra-setup.js :

function applyExtraSetup(sequelize) {
    const { user, post, comment} = sequelize.models;

      user.hasMany(post, {
        foreignKey : 'userId',
        targetKey: 'id'
      });
      
      post.hasMany(comment, {
        foreignKey : 'postId',
        targetKey: 'id'
      });
      
      user.hasMany(comment, {
        foreignKey : 'userId',
        targetKey: 'id'
      });
}

module.exports = { applyExtraSetup };

When i test my route with postman i have this error :”SequelizeEagerLoadingError”.
I have try to create a extra-setup for my foreign key because i have fin this solution (https://forum.freecodecamp.org/t/nodejs-sequelize-eager-loading-error/480312/7) but the problem is similar.

Can you help me please.

update fusioncharts when selecting from select

good day! please help with the solution of the problem. the graph is not plotted if I select the select item . it seems the code is correct. I pass the selected select by ajax to a php file. the graphic plated only with a constant variable in the php file. tell me how to solve this problem. I think this is due to the fact that the graphic plated once when the page is opened and is not updated.

app.js:
    $(function() {
    $.ajax({

    url: 'chart_data.php',
    type: 'GET',
    success: function(data) {
        chartData = data;
        var chartProperties = {
            "xAxisName": "Type cell",
            "yAxisName": "Number of votes",
            "rotatevalues": "1",
            "theme": "zune"
        };

        apiChart = new FusionCharts({
            type: 'column2d',
            numbersuffix: " Transactions",
            renderAt: 'chart-container',
            width: '500',
            height: '350',
            dataFormat: 'json',
            dataSource: {
                "chart": chartProperties,
                "data": chartData
            }
        });
        apiChart.updateChart();
        

    },
   
});});

chart_data.php:
<?php session_start();

$servername = "";
$username = "";
$password = "";
$dbName = "";
$conn = mysqli_connect($servername, $username, $password, $dbName);

$id_marker = $_POST['id_marker'];

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$query = "SELECT celltype,count(celltype) AS sum FROM typebyimage INNER JOIN celltype ON typebyimage.id_celltype = celltype.id_celltype where id_marker='$id_marker' GROUP BY celltype";

$result = $conn->query($query);
$jsonArray = array();

//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
  //Converting the results into an associative array
  while($row = $result->fetch_assoc()) {
    $jsonArrayItem = array();
    $jsonArrayItem['label']  = $row['celltype'];
    $jsonArrayItem['value'] = $row['sum'];
    //append the above created object into the main array.
    array_push($jsonArray, $jsonArrayItem);
  }
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);
?>

stat.php:
<div id="pie">
          <div id="chart-container">The diagram will be displayed here</div>  
        </div>
<label for="exampleInputEmail1" class="form-label">Select a marker</label>
            <?php
            $db = mysqli_connect("", "", "","");
            $marker = mysqli_query($db, "SELECT * FROM marker where id_fullimage='$id'");
            echo '<select id="id_marker" name="id_marker" class="form-select"  aria-label="Default select example" required onchange="myFunction()">';
            while($result = mysqli_fetch_array($marker)){
            echo "<option value=".$result['id_marker'].">".$result['id_marker']."</option>";
            } 
            echo "</select>";
            ?>
<script>
function myFunction(){
            var id_marker = $('#id_marker').val();
            console.log(id_marker);
            $.ajax({
            type: 'POST',
            url: 'chart_data.php',
            dataFormat: 'json',
            data: {
              id_marker:id_marker
            },
            success: function () {
            

            },
            error: function () {
                alert("ошибка");
            }
        });
        };
</script>

Making an array from two another

I have two arrays of objects (10 objects in each arrray) -> arr1 = [{name: ”, age: ”}…] and arr2 = [{surname: ”, position: ”}…] which I hold in two separated states.
My goal is to create the third array of the objects which contains also 10 elements arr3=[{name: arr1.name, surname: arr2.surname}…].

How can I do this ?

Click Element in Selenium Javascript not working

I am automating a website in which I want to click on the x when a subscription popup comes up
The HTML for the X is

<button title="Close popup message" data-testid="email-popup-close-button" id="email-popup-close-button" class="dw-1hfj58t-CloseBtn--EmailContainer e1lwf35p0">×</button>

So to click on this I am using the below

await driver.findElement(By.id("email-popup-close-button")).click();

But it is coming up with the below error

NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="email-popup-close-button"]"}

How to javascript code convert to typscript?

How to javascript code convert to typscript?

updateVariable = (TData:any) => {
    var arr = Object.keys(TData);
    for (var index = 0; index < arr.length; index++) {
        if (this[arr[index]] != undefined) {
            this[arr[index]] = TData[arr[index]];
        }
    }
};

I got flow error, how to correct this?
enter image description here

this: this
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'KeyAssignManager'.
  No index signature with a parameter of type 'string' was found on type 'KeyAssignManager'.ts(7053)

Manipulating data in a different format

I managed to create a query to get some data from the database using the following script:

app.get("/diseases", async (req, res) => {
  const rows = await process.postgresql.query(
    "SELECT ds.disease, ds.symptom FROM diseases ds"
  );
  console.log(rows);
  res.status(200).send(JSON.stringify(rows));
});

The data comes in the following format:

[
  { disease: ' boală hipertensivă', symptom: ' durere toracică' },
  {
    disease: ' boală hipertensivă',
    symptom: ' respirație întretăiată'
  },
  { disease: ' boală hipertensivă', symptom: ' amețeală' },
  { disease: ' boală hipertensivă', symptom: ' astenie' },
  { disease: ' boală hipertensivă', symptom: ' toamnă (Fall)' },
  { disease: ' boală hipertensivă', symptom: ' sincopă' },
  { disease: ' diabet', symptom: ' poliurie' }
]

My question is how to transform this data in a format, like the following:

{"Hypertensive disease": ["Pain chest", "Shortness of breath", "Dizziness", "Asthenia", "Fall", "Syncope", "Vertigo", "Sweat", "Sweating increased", "Palpitation", "Nausea", "Angina pectoris", "Pressure chest"], "Diabetes": ["Polyuria"]}